diff --git a/README.md b/README.md index 2c1f0b8..3d677c0 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This repository and the BGS listing remain **private**. Supplied artwork and gam ## Development -Node 24+, pnpm. `pnpm install`, `pnpm build`, `pnpm dev` (port 5238). `pnpm test` runs rules tests; `pnpm test:browser` checks the viewer. +Node 24+, pnpm. `pnpm install`, `pnpm build`, `pnpm dev` (port 5246). `pnpm test` runs rules tests; install the browser once with `pnpm exec playwright install chromium`; `pnpm test:browser` checks the viewer. Supported scope: 2–5 players, all eleven characters, the official two-player variant, optional Rising Waters, replay and finished-game analysis, bots, BGS chat, player hover cards and board thumbnails. @@ -18,3 +18,11 @@ Supported scope: 2–5 players, all eleven characters, the official two-player v - [BoardGameGeek](https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition) Component uncertainties and implementation validation are recorded in the beta report. + +## Beta review + +Read [the beta report](docs/BETA-REPORT.md) before public release: the supplied ocean values and one outer board location still need confirmation. Bots are suitable for practice and automated coverage, not a claim of strong competitive play. + +Guided lessons are available locally at `/?lesson=planning`, `/?lesson=fishing` and `/?lesson=islands`. Add `?players=2&new`, `?water&new` or `?hotseat&new` for practice variants. Practice progress stays in this browser. + +Release: `pnpm build && pnpm test && pnpm test:browser`, then `node scripts/publish-private.mjs`. The publisher reads the admin token from `~/.bgs`, keeps the version private and checks the unlisted flag. It refuses to overwrite a public version. `node test/simulations.mjs` runs the longer complete-game sweep. diff --git a/docs/BETA-REPORT.md b/docs/BETA-REPORT.md new file mode 100644 index 0000000..a025672 --- /dev/null +++ b/docs/BETA-REPORT.md @@ -0,0 +1,67 @@ +# Vanuatu private beta — implementation and open questions + +25 September 2026 · Second edition, Quined Games (2016) + +## Available + +- Private, unlisted [BGS game](https://boardgamers.space/boardgame/vanuatu), access granted to **coyotte508**. +- Private [Codeberg repository](https://codeberg.org/boardgamers/vanuatu). +- Local practice: `http://127.0.0.1:5246/` (start with `pnpm build && pnpm dev`). +- Three guided lessons: planning, fishing/trade, and island development. + +The engine covers eight rounds, 2–5 players, all eleven characters, the official two-player rules, optional play without characters for 3–5 players, and Rising Waters. It automates setup, replenishment, income conversion, turn order, mandatory retrieval when no decision remains, floods and final scoring. Free treasure sales and the Beggar remain available out of turn. + +The viewer uses a large interactive map, a compact action dock and player supplies below the board. It supports tap-based mobile play, legal destination highlights, character bonuses, resource pictograms, shared sound/color-blind preferences, English/French game text, BGS chat with translation and editing, journal, replay, finished-game analysis, player hover cards, fullscreen and board-thumbnail rendering. Tutorial text is currently English. + +## Points requiring publisher confirmation + +These are explicit beta assumptions, **not resolved official errata**. They should be checked before a public release; changing a tile value or board footprint may require starting fresh beta games. + +| Question | Evidence | Implemented choice | +| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Fish and treasure quantities | The rulebook lists 14 fish tiles (8×1, 4×2, 2×3) and 10 treasure tiles (4×1, 4×2, 2×3). The supplied cut-tile faces instead total **16 fish markers and 8 treasure markers**. | Use the readable values on the supplied tile faces. Fish/treasure rewards follow the remaining count on the ocean tile; no artificial shortage of reward tiles. | +| Exact outer board outline | The supplied board has faint, irregular tile outlines. The rules establish 15 placed tiles plus the fixed island, but do not enumerate their coordinates. | A 16-location footprint traced from that board, rendered as regular hexagons. In particular, the far upper-right location (`3,0` in the source) remains provisional. Please compare against a physical final board. | +| Governor during Rising Waters | The Governor moves markers **instead of** performing an action. The flood rule counts performed actions; no explicit Governor exception was found. | Governor transfers and discarded stacks do **not** decrease the flood die. Normal actions do. | + +The supplied demand art also contains repeated patterns: cards 1/10 have one of each good; cards 2/8 have two kava and one copra. Duplicates can be intentional; they are preserved, not “corrected” speculatively. + +### Tile values currently used + +The fixed starting island is additional to this table. Two tiles of each letter A–F are split between the two ordered stacks, following the rulebook. + +| Tile | Source cut image | Fish | Treasure | Island capacity: huts / drawings / tourists | Goods | +| -------------- | ---------------- | ---: | -------: | ------------------------------------------- | ----------- | +| Starting fish | 1 | 2 | 0 | — | — | +| Starting wreck | 3 | 1 | 2 | — | — | +| Starting boats | 5 | 0 | 0 | — | — | +| A1 | 7 | — | — | 3 / 2 / 4 | kava, beef | +| A2 | 9 | — | — | 3 / 2 / 4 | kava, copra | +| B1 | 11 | 1 | 3 | — | — | +| B2 | 13 | 3 | 0 | — | — | +| C1 | 15 | 0 | 0 | — | — | +| C2 | 17 | 1 | 2 | — | — | +| D1 | 19 | — | — | 2 / 3 / 3 | 2 kava | +| D2 | 21 | — | — | 3 / 1 / 4 | kava, copra | +| E1 | 23 | 0 | 0 | — | — | +| E2 | 25 | 2 | 0 | — | — | +| F1 | 27 | 3 | 1 | — | — | +| F2 | 29 | 3 | 0 | — | — | + +## Validation + +- 22 focused engine/tutorial tests: majorities, prerequisites, optional powers, money conversion, two-player blocking, illegal-move immutability, hidden information, dropped players, deterministic replay, floods and complete tutorials. +- 80 full simulated games (14,653 moves in the final sweep), across 2/3/4/5 players with and without Rising Waters. Both purposeful bots and varied legal choices exercise all nine actions and the Governor. These check termination, resource invariants and deterministic reconstruction; they do not establish strategic bot strength or resolve component discrepancies. +- Browser checks at **1440 px** and **390 px**: all nine actions, planning, tile placement, final scores, no page-width overflow, color symbols, replay, analysis chat hiding, player hover, board thumbnails, chat scroll-to-bottom, translation controls and ↑ editing. +- The installed production engine completed an eight-round bot game and reconstructed its history. The uploaded viewer is checked through a protocol harness. A signed-out browser correctly cannot open the private game; a real multi-account online session remains a useful beta playtest. + +## Sources + +Rules take precedence over artwork where they specify the behavior. Supplied component faces are used for values not individually listed in the rules. + +- [Publisher’s English rulebook](https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_UK_WEBversion-4.pdf), especially setup, actions, characters and Rising Waters. +- [Publisher’s French rulebook](https://quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_FR-WEBversion.pdf). +- [Official two-player rules](https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf). +- [BGG second-edition page](https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition), including its listing of the publisher’s corrected English rulebook. BGG’s direct page fetch was blocked, so no unverified forum clarification has been treated as authoritative. +- [BGG discussion of fish sales and optional treasure sales](https://boardgamegeek.com/thread/1883649/fish-price-and-treasure), consistent with the English rulebook: the market decreases once per sale action; treasure liquidation is optional. + +Artwork remains the property of its rights holders. The private repository and beta are not permission to redistribute the supplied materials. diff --git a/engine/index.js b/engine/index.js index 94a6256..94a0236 100644 --- a/engine/index.js +++ b/engine/index.js @@ -445,7 +445,50 @@ function freeVariants(s, p) { } return out; } +const planningCache = new WeakMap(); export function canPlan(s, p, target, markers = s.players[p].markers) { + return canPlanUncached(s, p, target, markers); +} +function cachedCanPlan(s, p, target, markers = s.players[p].markers) { + const cacheKey = `${p}:${target}:${ACTIONS.map((a) => (markers[a] > 0 ? 1 : 0)).join("")}`; + let cache = planningCache.get(s); + if (!cache) { + cache = new Map(); + planningCache.set(s, cache); + } + if (cache.has(cacheKey)) return cache.get(cacheKey); + const result = canPlanUncached(s, p, target, markers); + cache.set(cacheKey, result); + return result; +} +function canPlanUncached(s, p, target, markers) { + const islands = Object.values(s.board).filter( + (t) => t.type === "island" && !t.submerged, + ); + if (target === "fish" && !Object.values(s.board).some((t) => t.fish > 0)) + return false; + if ( + target === "explore" && + !Object.values(s.board).some((t) => t.treasure > 0) + ) + return false; + if ( + target === "draw" && + !islands.some((t) => t.drawings < TILES[t.id].drawings) + ) + return false; + if ( + target === "tourist" && + (!s.tourists || !islands.some((t) => t.tourists < TILES[t.id].tourists)) + ) + return false; + if ( + target === "buy" && + !islands.some((t) => Object.values(t.goods).some((n) => n > 0)) + ) + return false; + if (target === "sell" && !s.players[p].fish.length && !markers.fish) + return false; const actions = ACTIONS.filter( (a) => markers[a] > 0 && a !== target && a !== "rest", ); @@ -541,16 +584,17 @@ export function availableMoves(s, p = s.actor) { })); break; case "plan": { + planningCache.delete(s); const count = s.planningPass === 2 ? 1 : 2; for (const action of ACTIONS) { - if (!canPlan(s, p, action)) continue; + if (!cachedCanPlan(s, p, action)) continue; if (count === 1) { moves.push({ type: "plan", actions: [action] }); continue; } const markers = { ...a.markers, [action]: a.markers[action] + 1 }; for (const next of ACTIONS) - if (canPlan(s, p, next, markers)) + if (cachedCanPlan(s, p, next, markers)) moves.push({ type: "plan", actions: [action, next] }); } break; @@ -824,7 +868,7 @@ function execute(s, m, p) { a.markers[m.from] = 0; a.used = true; a.governorAction = m.to; - actionDone(s, p); + actionDone(s, p, false); return; case "rest": a.rest = m.token; @@ -854,7 +898,11 @@ function automate(s) { const moves = availableMoves(s).filter( (m) => !["beg", "treasure"].includes(m.type), ); - if (moves.length === 1 && moves[0].type === "discard") { + if ( + moves.length === 1 && + moves[0].type === "discard" && + freeMoves(s, s.actor).length === 0 + ) { execute(s, moves[0], s.actor); continue; } @@ -862,7 +910,7 @@ function automate(s) { } check(guard < 100, "Automatic turn limit"); } -export function move(data, input, p) { +function applyMove(data, input, p) { check(!data.finished, "The game has ended"); check( Number.isInteger(p) && p >= 0 && p < data.players.length, @@ -884,6 +932,17 @@ export function move(data, input, p) { saveFrame(s); return s; } +function playDropped(data) { + let s = data, + n = 0; + while (!s.finished && s.players[s.actor]?.dropped && n++ < 1000) + s = applyMove(s, chooseAI(s, s.actor), s.actor); + check(n < 1000, "Dropped player automation limit"); + return s; +} +export function move(data, input, p) { + return playDropped(applyMove(data, input, p)); +} export const ended = (s) => s.finished; export const scores = (s) => s.players.map((p) => p.score); export function rankings(s) { @@ -922,6 +981,9 @@ function publicFrame(frame, p, finished = false) { if (q !== p && !finished) a.rest = a.rest ? "hidden" : null; if (!(out.phase === "rest" && out.actor === p) && !finished) delete out.restAvailable; + out.lastEvents = (out.lastEvents ?? []).map((e) => + e.type === "rest" && e.p !== p && !finished ? { ...e, token: "hidden" } : e, + ); return out; } export function stripSecret(s, p) { @@ -958,7 +1020,7 @@ export function replay(s, { to = logLength(s) } = {}) { ); const b = s._setup; let r = init(b.count, b.expansions, b.options, b.seed); - for (const h of s._history.slice(0, to - 1)) r = move(r, h.move, h.p); + for (const h of s._history.slice(0, to - 1)) r = applyMove(r, h.move, h.p); s.players.forEach((p, i) => { r.players[i].name = p.name; r.players[i].dropped = p.dropped; @@ -970,7 +1032,7 @@ export function createAnalysis(s, { to }) { r.players.forEach((p) => (p.dropped = false)); return r; } -export function moveAI(s, p) { +function chooseAI(s, p) { check(p === s.actor); const moves = availableMoves(s, p); check(moves.length, "No legal bot move"); @@ -995,11 +1057,6 @@ export function moveAI(s, p) { s.neutral[action]), 0, ); - if (false) - return ( - ({ sail: 4, sell: 3, fish: 2, rest: 1 }[m.action] ?? 0) - - s.neutral[m.action] - ); if (m.type === "character") return ( ({ @@ -1086,16 +1143,14 @@ export function moveAI(s, p) { const ranked = moves .map((m, i) => ({ m, i, value: value(m) })) .sort((a, b) => b.value - a.value || a.i - b.i); - return move(s, ranked[0].m, p); + return ranked[0].m; +} +export function moveAI(s, p) { + return move(s, chooseAI(s, p), p); } export function dropPlayer(s, p) { + check(Number.isInteger(p) && !!s.players[p], "Unknown player"); const out = copy(s); out.players[p].dropped = true; - let n = 0; - while (!out.finished && out.players[out.actor]?.dropped && n++ < 1000) { - const next = moveAI(out, out.actor); - Object.assign(out, next); - } - check(n < 1000, "Dropped player automation limit"); - return out; + return playDropped(out); } diff --git a/package.json b/package.json index 51e44c2..cd42746 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "build": "node scripts/build.mjs", "test": "node --test test/*.test.js", "dev": "node scripts/dev.mjs", - "test:browser": "node test/browser.mjs" + "test:browser": "node test/browser.mjs", + "check": "pnpm build && pnpm test && pnpm test:browser" }, "dependencies": { "@boardgamers/protocol": "0.6.0", diff --git a/scripts/dev.mjs b/scripts/dev.mjs index 2524fe7..25feb57 100644 --- a/scripts/dev.mjs +++ b/scripts/dev.mjs @@ -2,7 +2,7 @@ import { createServer } from "node:http"; import { readFile } from "node:fs/promises"; import { resolve, extname } from "node:path"; const root = resolve("dist"); -const port = Number(process.env.PORT ?? 5238); +const port = Number(process.env.PORT ?? 5246); createServer(async (req, res) => { try { const url = new URL(req.url, "http://local"); diff --git a/scripts/prepare-assets.py b/scripts/prepare-assets.py index dbd9a71..68568a8 100644 --- a/scripts/prepare-assets.py +++ b/scripts/prepare-assets.py @@ -18,7 +18,9 @@ for n in range(1,11):save('demand-'+str(n),root/'Demand'/f'Demand{n}.jpg',(400,2 for n in range(1,5):save('rest-'+str(n),root/'rest_tokens'/f'REST{n}.jpg',(220,220)) board=root/'Game Board/Game_Board_Vanuatu_RGB.jpg' save('efate',board,(480,480),(3030,2450,4280,3700)) -save('ocean',root/'archipelagos/archipelago03.jpg',(600,600),(150,150,1070,1070)) +ocean=root/'archipelagos/archipelago03.jpg' +w,h=Image.open(ocean).size +save('ocean',ocean,(480,480),(int(w*.3),int(h*.3),int(w*.7),int(h*.7))) save('sand',root/'Demand/BACKSIDE_Demand.jpg',(500,280)) save('cover',root/'Game Box/Vanuatu_box_FRONT_NEW_small.jpg',(1100,1100)) for i,action in enumerate(['buy','explore','sail','build','rest','tourist','fish','sell','draw']): diff --git a/scripts/publish-private.mjs b/scripts/publish-private.mjs new file mode 100644 index 0000000..02f7f01 --- /dev/null +++ b/scripts/publish-private.mjs @@ -0,0 +1,166 @@ +import { chapterMetadata } from "../viewer/tutorials.js"; +import { readFile, mkdir, writeFile } from "node:fs/promises"; +import { homedir } from "node:os"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import assert from "node:assert/strict"; +const token = (await readFile(`${homedir()}/.bgs`, "utf8")).trim(); +const base = "https://admin.boardgamers.space/api/admin/gameinfo/vanuatu"; +async function api(path, method = "GET", body, contentType) { + const response = await fetch(base + path, { + method, + headers: { + Authorization: `Bearer ${token}`, + ...(body ? { "Content-Type": contentType ?? "application/json" } : {}), + }, + body: body ? (contentType ? body : JSON.stringify(body)) : undefined, + }); + if (!response.ok) + throw Error( + `${method} ${path}: ${response.status} ${await response.text()}`, + ); + const text = await response.text(); + return text ? JSON.parse(text) : null; +} +const versions = await api("/versions"); +const existing = versions.some((v) => v.version === 1) ? await api("/1") : null; +if (existing?.public) + throw Error( + "Refusing to change a public release with the private-beta publisher.", + ); +const defaults = { + public: false, + meta: { botsPublic: true }, + label: "Vanuatu", + players: [2, 3, 4, 5], + unlisted: true, + description: + "Compete for prosperity in a growing Pacific archipelago. Plan actions, sail, trade and welcome tourists. Includes all eleven characters, the official two-player variant and Rising Waters.", + credits: + "Designed by **Alain Epron**. Artwork by **Konstantin Vohwinkel**; graphic design and rulebook by **Rafaël Theunis**.\n\n[Vanuatu — Quined Games, second edition (2016)](https://www.quined.nl/featured_item/vanuatu-2nd-edition/). Supplied artwork used with permission for this adaptation.\n\n[Source code (private beta)](https://codeberg.org/boardgamers/vanuatu).", + links: { + source: "https://codeberg.org/boardgamers/vanuatu", + publisher: "https://www.quined.nl/featured_item/vanuatu-2nd-edition/", + bgg: "https://boardgamegeek.com/boardgame/193927/vanuatu-second-edition", + }, + rules: + "[Original rules (English PDF)](https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_UK_WEBversion-4.pdf) · [Règles originales (PDF français)](https://quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_FR-WEBversion.pdf) · [Official two-player rules](https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf)\n\n**Eight rounds to prosper.** Choose a character, then place five action markers in batches of 2, 2 and 1. Resolve one action at a time where you have the most markers; ties follow player order. Retrieve all your markers from that action. With no majority, retrieve a stack without acting.\n\nSail to reach fish and treasure, or trade and build beside islands. Every 10 vatus becomes 5 prosperity immediately. At the end, remaining money and treasure score points; every hut earns 2 prosperity per tourist on its island. Most prosperity wins.", + viewer: { + url: "", + topLevelVariable: "vanuatu", + fullScreen: true, + fullScreenMobile: true, + replayable: true, + chat: true, + thumbnail: true, + dependencies: { scripts: [], stylesheets: [] }, + }, + preferences: [ + { + name: "colorBlind", + label: "Color-blind mode", + type: "checkbox", + default: false, + }, + { name: "sound", label: "Game sounds", type: "checkbox", default: false }, + { + name: "language", + label: "Language", + type: "select", + default: "auto", + items: [ + { name: "auto", label: "Automatic" }, + { name: "en", label: "English" }, + { name: "fr", label: "Français" }, + ], + }, + ], + tutorial: { chapters: chapterMetadata }, + options: [ + { + name: "characters", + label: "Character powers", + type: "checkbox", + default: true, + }, + ], + expansions: [{ name: "rising-waters", label: "Rising Waters" }], +}; +if (!existing) { + const { unlisted, ...initial } = defaults; + await api("/1", "PUT", initial); +} +await mkdir(".local/release", { recursive: true }); +if (existing) + await writeFile( + ".local/release/before.json", + JSON.stringify(existing, null, 2), + ); +execFileSync("pnpm", ["pack", "--pack-destination", ".local/release"], { + stdio: "inherit", +}); +const pkg = JSON.parse(await readFile("package.json", "utf8")); +const engine = await api( + "/1/engine", + "POST", + await readFile(`.local/release/boardgamers-vanuatu-${pkg.version}.tgz`), + "application/octet-stream", +); +const js = await readFile("dist/viewer.js"), + css = await readFile("dist/viewer.css"); +const hash = createHash("sha256") + .update(js) + .update(css) + .digest("hex") + .slice(0, 16); +const viewer = await api( + `/1/viewer/file?filename=viewer.js&bundle=${hash}`, + "POST", + js, + "application/octet-stream", +); +const style = await api( + `/1/viewer/file?filename=viewer.css&bundle=${hash}`, + "POST", + css, + "application/octet-stream", +); +await api("/1", "PUT", { + ...existing, + ...defaults, + engine: { ...engine.engine, entryPoint: "dist/engine.js" }, + viewer: { + ...defaults.viewer, + url: viewer.url, + dependencies: { scripts: [], stylesheets: [style.url] }, + }, +}); +await api("/meta", "PUT", { unlisted: true }); +await api( + "/assets/cover?name=Vanuatu", + "PUT", + await readFile("viewer/assets/cover.webp"), + "image/webp", +); +const access = await api("/beta-users"); +if (!access.some((u) => u.username === "coyotte508")) + await api("/beta-users", "POST", { usernameOrEmail: "coyotte508" }); +const published = await api("/1"), + meta = await api("/meta"); +assert.equal(published.public, false); +assert.equal(meta.unlisted, true); +assert.equal(published.engine.package.version, pkg.version); +assert.equal(published.viewer.chat, true); +await writeFile( + ".local/release/published.json", + JSON.stringify(published, null, 2), +); +console.log( + JSON.stringify({ + private: !published.public, + unlisted: meta.unlisted, + engine: published.engine.package.version, + viewer: published.viewer.url, + betaUsers: (await api("/beta-users")).map((u) => u.username), + }), +); diff --git a/test/browser.mjs b/test/browser.mjs new file mode 100644 index 0000000..14be9df --- /dev/null +++ b/test/browser.mjs @@ -0,0 +1,224 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { mkdir, readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { resolve, extname } from "node:path"; +import * as E from "../engine/index.js"; +await mkdir(".local/qa", { recursive: true }); +const dist = resolve("dist"); +const server = createServer(async (req, res) => { + try { + const url = new URL(req.url, "http://localhost"); + const path = resolve( + dist, + "." + (url.pathname === "/" ? "/index.html" : url.pathname), + ); + if (!path.startsWith(dist + "/")) throw Error("Invalid path"); + const body = await readFile(path); + res.setHeader( + "Content-Type", + { ".js": "text/javascript", ".css": "text/css", ".html": "text/html" }[ + extname(path) + ] ?? "application/octet-stream", + ); + res.end(body); + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +server.unref(); +const base = `http://127.0.0.1:${server.address().port}`; +const browser = await chromium.launch({ + headless: true, + ...(process.env.CHROME_PATH + ? { executablePath: process.env.CHROME_PATH } + : {}), +}); +const errors = []; +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.on("pageerror", (e) => errors.push(e.message)); +await page.goto(base + "/?new&hotseat"); +await page.waitForSelector("[data-character-choice]"); +await page.locator("[data-character-choice]").first().click(); +assert.equal(await page.locator("dialog[open]").count(), 1); +await page.locator("dialog [data-move]").click(); +assert.equal(await page.locator("dialog[open]").count(), 0); +for (let n = 0; n < 2; n++) { + await page.locator("[data-character-choice]").first().click(); + await page.locator("dialog [data-move]").click(); +} +await page.locator('[data-action="sail"]').click(); +await page.locator('[data-action="fish"]').click(); +await page.locator(".turn-tray [data-move]").click(); +const after = await page.evaluate(() => window.vanuatuDemo.state); +assert.equal(after.players[after.first].markers.sail, 1); +assert.equal(after.players[after.first].markers.fish, 1); +// Every action can be selected and committed with pointer/touch controls, no dragging. +function actionState() { + const s = E.init(3, [], {}, "ui-actions"); + s.actor = 0; + s.first = 0; + s.phase = "actions"; + s.players.forEach((p, i) => { + p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, i === 0 ? 1 : 0])); + p.money = 9; + p.boat = "1,0"; + }); + s.board["1,0"] = E.tileState("startWreck"); + s.board["0,1"] = E.tileState("startFish"); + s.board["1,1"] = E.tileState("startBoat"); + s.board["0,0"].huts = [0]; + s.tourists = 2; + s.players[0].fish = [1, 2]; + s.players[0].treasures = [1]; + return s; +} +for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: width === 390 ? 844 : 1000 }); + for (const action of E.ACTIONS) { + const s = actionState(); + await page.evaluate((s) => window.vanuatuDemo.setState(s), s); + await page.locator(`[data-action="${action}"]`).click(); + const targets = page.locator(".map-cell.legal"); + if (await targets.count()) await targets.first().click(); + const option = page.locator(".turn-tray [data-move]").first(); + assert.ok(await option.count(), `No UI choice ${width}/${action}`); + await option.click(); + if (action === "rest") + await page.locator(".turn-tray [data-move]").first().click(); + assert.equal( + await page.locator(".feedback:not([hidden])").count(), + 0, + `${action} feedback`, + ); + assert.ok( + (await page.evaluate(() => window.vanuatuDemo.state._history.length)) > 0, + ); + } + await page.evaluate((s) => window.vanuatuDemo.setState(s), actionState()); + assert.ok( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + 1, + ), + "Page overflows horizontally", + ); + await page.screenshot({ + path: `.local/qa/actions-${width}.png`, + fullPage: true, + }); + await page.locator("[data-help]").first().click(); + await page.locator('[data-pref="colorBlind"]').check(); + await page.locator("[data-close]").click(); + assert.ok(await page.locator(".color-symbol").count()); +} +// Extension placement and optional expansion remain usable. +let expansion = E.init(3, [], {}, "expand"); +while (expansion.round < 2) expansion = E.moveAI(expansion, expansion.actor); +await page.evaluate((s) => window.vanuatuDemo.setState(s), expansion); +await page.locator(".map-cell.legal").first().click(); +await page.locator(".turn-tray [data-move]").click(); +// Ended games and spectator states must not reference a missing actor. +let final = E.init(3, [], {}, "finish"); +while (!final.finished) final = E.moveAI(final, final.actor); +await page.evaluate((s) => window.vanuatuDemo.setState(s), final); +await page.locator("[data-scores]").click(); +assert.equal(await page.locator(".final-scores>div").count(), 3); +await page.locator("[data-close]").click(); +// Hosted protocol: replay, names, analysis chat visibility, hover anchors and board thumbnail. +await page.goto(base + "/"); +await page.evaluate(() => { + document.body.innerHTML = '
'; +}); +await page.addStyleTag({ url: base + "/viewer.css" }); +await page.addScriptTag({ url: base + "/viewer.js" }); +await page.evaluate(() => { + window.emitter = window.vanuatu.launch("#host"); + window.hostEvents = []; + for (const kind of [ + "player:hovered", + "boardgame:clicked", + "replay:info", + "thumbnail:ready", + ]) + window.emitter.on(kind, (v) => window.hostEvents.push({ kind, v })); +}); +await page.evaluate( + (s) => { + emitter.receive("player", { index: 0 }); + emitter.receive("state", s); + emitter.receive("preferences", { analysis: true, colorBlind: true }); + }, + E.stripSecret(final, 0), +); +assert.equal(await page.locator('[data-activity="chat"]').count(), 0); +await page.evaluate( + (s) => { + emitter.receive("replay:start"); + emitter.receive("replay:to", 1); + emitter.receive("gamelog", { start: 0, data: s }); + }, + E.logSlice(final, { player: 0, start: 0, end: 0 }), +); +assert.equal(await page.locator("[data-scores]").count(), 0); +await page.locator('[data-bgs-player="0"]').hover(); +assert.ok( + await page.evaluate(() => + hostEvents.some((e) => e.kind === "player:hovered"), + ), +); +await page.evaluate(() => { + emitter.receive("replay:end"); + emitter.receive("preferences", { analysis: false }); + emitter.receive("chat:state", { + canSend: true, + canEdit: true, + translationTarget: "fr", + }); + emitter.receive( + "chat:messages", + Array.from({ length: 80 }, (_, i) => ({ + _id: i.toString(16).padStart(24, "0"), + type: "text", + author: "You", + playerIndex: 0, + createdAt: new Date().toISOString(), + editableUntil: new Date(Date.now() + 600000).toISOString(), + text: "Practice message " + i, + language: "en", + })), + ); +}); +await page.locator('[data-tab="chat"]').click(); +const messageList = page.locator(".chat-messages"); +await messageList.scrollIntoViewIfNeeded(); +await page.waitForTimeout(250); +await messageList.evaluate((el) => { + el.scrollTop = el.scrollHeight; +}); +await page.screenshot({ path: ".local/qa/chat-mobile.png", fullPage: true }); +assert.ok( + await messageList.evaluate( + (el) => Math.abs(el.scrollHeight - el.scrollTop - el.clientHeight) < 2, + ), +); +await page.locator(".chat-composer input").press("ArrowUp"); +assert.equal( + await page.locator(".chat-composer input").inputValue(), + "Practice message 79", +); +assert.ok(await page.locator(".chat-translate").count()); +await page.screenshot({ path: ".local/qa/chat-mobile.png", fullPage: true }); +await page.evaluate(() => + emitter.receive("thumbnail:render", { width: 1000, height: 600 }), +); +await page.waitForTimeout(200); +assert.ok(await page.locator(".bgs-board-thumbnail svg").count()); +await page.screenshot({ path: ".local/qa/thumbnail.png" }); +assert.deepEqual(errors, []); +await browser.close(); +await new Promise((resolve) => server.close(resolve)); +console.log( + "Desktop, mobile, all nine actions, expansion, endgame, replay, hover cards and thumbnail checks passed.", +); diff --git a/test/engine.test.js b/test/engine.test.js index b3e5f12..46c4e2f 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -177,3 +177,71 @@ test("Rising Waters floods after its action countdown and dikes protect edges", assert.equal(s.board["0,0"].water, 2); assert.equal(s.waterTriggered, true); }); +test("rest choices stay secret in replay events as well as state", () => { + let s = actionState(); + s.phase = "rest"; + s.actor = 0; + s._restAvailable = ["first", "coin"]; + s = E.move(s, { type: "rest", token: "first" }, 0); + const last = E.logSlice(s, { player: 1, start: E.logLength(s) - 1 }) + .frames[0]; + assert.equal(last.players[0].rest, "hidden"); + assert.equal(last.lastEvents.find((e) => e.type === "rest").token, "hidden"); + assert.equal( + E.stripSecret(s, 0).lastEvents.find((e) => e.type === "rest").token, + "first", + ); +}); +test("dropped players are automated on future turns and replay boundaries remain valid", () => { + let s = E.init(3, [], {}, "drop"); + const dropped = (s.actor + 1) % 3; + s = E.dropPlayer(s, dropped); + for (let n = 0; n < 22 && !s.finished; n++) { + assert.notEqual(s.actor, dropped); + s = E.moveAI(s, s.actor); + } + assert.ok(s._history.some((h) => h.p === dropped)); + for (let n = 1; n <= E.logLength(s); n++) + assert.deepEqual( + E.createAnalysis(s, { to: n }).board, + s._frames[n - 1].board, + ); +}); +test("batched planning accounts for the first new marker as a prerequisite", () => { + const s = actionState(); + s.phase = "plan"; + s.planningPass = 0; + s.players[0].markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0])); + s.board["0,0"].huts = [0]; + s.players[0].fish = []; + assert.ok( + E.availableMoves(s).some( + (m) => + m.type === "plan" && m.actions[0] === "fish" && m.actions[1] === "sell", + ), + ); +}); +test("an optional treasure sale is not skipped by automatic marker retrieval", () => { + let s = actionState(); + s.actor = 0; + s.players[0].markers = { ...s.players[0].markers, fish: 1 }; + s.players[1].markers = Object.fromEntries( + E.ACTIONS.map((a) => [a, a === "sail" ? 1 : 0]), + ); + s.players[1].money = 0; + s.players[1].treasures = [2]; + s = E.move(s, act(s, 0, "fish"), 0); + assert.equal(s.actor, 1); + assert.ok(E.availableMoves(s, 1).some((m) => m.type === "treasure")); + s = E.move(s, { type: "treasure", values: [2] }, 1); + assert.ok(E.availableMoves(s, 1).some((m) => m.action === "sail")); +}); +test("Governor marker movement does not perform an action or advance the flood die", () => { + let s = actionState(); + s.players[0].character = "governor"; + s.options.risingWaters = true; + s.waterCountdown = 1; + s = E.move(s, { type: "governor", from: "fish", to: "explore" }, 0); + assert.equal(s.waterCountdown, 1); + assert.equal(s.waterTriggered, false); +}); diff --git a/test/simulations.mjs b/test/simulations.mjs new file mode 100644 index 0000000..880cd0d --- /dev/null +++ b/test/simulations.mjs @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import * as E from "../engine/index.js"; +const counts = {}; +let games = 0, + turns = 0; +for (let seed = 0; seed < 10; seed++) + for (const n of [2, 3, 4, 5]) + for (const water of [false, true]) { + let s = E.init(n, water ? ["rising-waters"] : [], {}, `qa-${seed}`), + k = 0; + while (!s.finished && k++ < 600) { + const legal = E.availableMoves(s); + assert.ok(legal.length, `${seed}/${n}/${water}/${s.round}/${s.phase}`); + // Alternate purposeful bots with varied legal choices to exercise uncommon characters/actions. + if (seed % 3 === 0) { + const moves = legal.filter( + (m) => !["beg", "treasure"].includes(m.type), + ); + const m = moves[(k * 73 + seed * 41) % moves.length]; + counts[m.action ?? m.type] = (counts[m.action ?? m.type] ?? 0) + 1; + s = E.move(s, m, s.actor); + } else s = E.moveAI(s, s.actor); + assert.ok( + s.players.every( + (p) => p.money >= 0 && p.money < 10 && p.hutsLeft >= 0, + ), + ); + assert.ok( + Object.values(s.board).every( + (t) => + t.fish >= 0 && + t.treasure >= 0 && + Object.values(t.goods).every((x) => x >= 0), + ), + ); + assert.ok(s.round <= 8); + turns++; + } + assert.ok(s.finished, `Unfinished ${seed}/${n}/${water}`); + assert.equal(E.currentPlayer(s), undefined); + const restored = E.replay(s); + assert.deepEqual(E.scores(restored), E.scores(s)); + assert.deepEqual(restored.board, s.board); + games++; + if (games % 8 === 0) console.log(`${games} full games passed`); + } +console.log(JSON.stringify({ games, turns, coverage: counts })); diff --git a/test/tutorial.test.js b/test/tutorial.test.js new file mode 100644 index 0000000..5a7088e --- /dev/null +++ b/test/tutorial.test.js @@ -0,0 +1,25 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createTutorial } from "@boardgamers/protocol/tutorial"; +import { chapters } from "../viewer/tutorials.js"; +import { availableMoves } from "../engine/index.js"; +for (const [id, chapter] of Object.entries(chapters)) + test(`tutorial ${id} is completable with real engine moves`, async () => { + const lesson = await createTutorial(chapter); + let count = 0; + while (!lesson.snapshot.completed && count++ < 20) { + const snap = lesson.snapshot; + if (snap.canContinue) { + await lesson.continue(); + continue; + } + const step = chapter.steps[snap.step]; + const moves = availableMoves(snap.state, 0).filter( + (m) => !step.validateMove?.(snap.state, m), + ); + assert.ok(moves.length, `${id}/${snap.step}`); + assert.equal(await lesson.play(moves[0]), true); + } + assert.equal(lesson.snapshot.completed, true); + lesson.destroy(); + }); diff --git a/viewer/activity.js b/viewer/activity.js new file mode 100644 index 0000000..f1ddf15 --- /dev/null +++ b/viewer/activity.js @@ -0,0 +1,173 @@ +import { mountChat } from "@boardgamers/protocol/chat/dom"; +import { icon, token, esc } from "./art.js"; +import { translator } from "./labels.js"; +import { CHARACTERS } from "../engine/catalog.js"; +export function mountActivity( + target, + { chat, openPlayer, onBack, language = "en" } = {}, +) { + const root = document.createElement("section"); + root.className = "activity"; + root.innerHTML = `
    `; + const shortcut = document.createElement("button"); + shortcut.className = "chat-shortcut"; + shortcut.hidden = true; + shortcut.type = "button"; + target.append(root, shortcut); + const list = root.querySelector("ol"), + journal = root.querySelector(".journal-panel"), + panel = root.querySelector(".chat-panel"); + let mode = "journal", + analysis = false, + state, + lang = language, + t = translator(lang), + following = true, + key = "", + visible = false; + const view = chat + ? mountChat(panel, { + chat, + openPlayer, + styles: true, + labels: + language === "fr" + ? { + send: "Envoyer", + sending: "Envoi…", + empty: "Aucun message", + message: "Message", + edited: "modifié", + } + : undefined, + }) + : null; + const observer = new IntersectionObserver( + (entries) => { + visible = entries[0]?.isIntersecting ?? false; + syncVisibility(); + }, + { threshold: 0.15 }, + ); + observer.observe(panel); + function syncVisibility() { + chat?.setOpen(mode === "chat" && !analysis && visible); + } + function select(kind) { + mode = kind === "chat" && chat && !analysis ? "chat" : "journal"; + journal.hidden = mode !== "journal"; + panel.hidden = mode !== "chat"; + for (const b of root.querySelectorAll("[data-tab]")) { + b.setAttribute("aria-selected", String(b.dataset.tab === mode)); + b.tabIndex = b.dataset.tab === mode ? 0 : -1; + } + if (mode === "chat") view?.open(); + else if (view) view.element.open = false; + syncVisibility(); + } + function open(kind) { + select(kind); + root.scrollIntoView({ behavior: "smooth", block: "start" }); + if (kind === "journal") list.focus({ preventScroll: true }); + } + function eventHtml(e) { + const name = state?.players[e.p]?.name ?? ""; + const actor = name + ? `${esc(name)}` + : ""; + switch (e.type) { + case "action": + return `${actor} ${icon(e.action)}${e.good ? icon(e.good) : ""}${e.fish ? e.fish.map((n) => token("fish", n)).join("") : ""}${e.path ? ` ${e.path.length} ${icon("sail")}` : ""}${e.bonus ? ` ${esc(CHARACTERS[state.players[e.p]?.character]?.[lang === "fr" ? "fr" : "name"] ?? "")}` : ""}`; + case "plan": + case "neutral": + return `${actor} ${e.actions.map((a) => icon(a)).join("")}${e.type === "neutral" ? ` ●` : ""}`; + case "character": + return `${actor} ${esc(CHARACTERS[e.character]?.[lang === "fr" ? "fr" : "name"] ?? e.character)}`; + case "conversion": + return `${actor} ${token("coin", e.points * 2)} → ${token("point", e.points)}`; + case "treasure": + return `${actor} ${token( + "explore", + e.values.reduce((a, b) => a + b, 0), + )} → ${token( + "coin", + e.values.reduce((a, b) => a + b, 0), + )}`; + case "beg": + return `${actor} ${token("point", e.amount)} → ${token("coin", e.amount)}`; + case "discard": + return `${actor} ${icon("undo")} ${icon(e.action)}`; + case "governor": + return `${actor} ${icon(e.from)} → ${icon(e.to)}`; + case "rest": + return `${actor} ${icon("rest")}`; + case "restBonus": + return `${actor} ${e.token === "first" ? icon("first") : e.token === "both" ? token("coin", 1) + token("point", 1) : token(e.token, 1)}`; + case "round": + return `${t("round")} ${e.round}/8`; + case "place": + return `${actor} ${t("expand")}`; + case "flood": + return `${icon("water")} ${t("water")}`; + case "end": + return `${t("finished")}`; + default: + return ""; + } + } + function refresh() { + if (!state) return; + const next = JSON.stringify(state.events ?? state.lastEvents ?? []) + lang; + if (next === key) return; + key = next; + list.innerHTML = (state.events ?? state.lastEvents ?? []) + .map((e) => ({ e, html: eventHtml(e) })) + .filter((x) => x.html) + .map(({ e, html }) => `
  1. ${e.round}${html}
  2. `) + .join(""); + if (following) + requestAnimationFrame(() => (list.scrollTop = list.scrollHeight)); + } + root.addEventListener("click", (e) => { + const b = e.target.closest("button"); + if (!b) return; + if (b.dataset.tab) open(b.dataset.tab); + if ("back" in b.dataset) onBack?.(); + }); + shortcut.onclick = () => open("chat"); + list.addEventListener("scroll", () => { + following = list.scrollHeight - list.scrollTop - list.clientHeight < 40; + }); + select("journal"); + return { + open, + update(s, isAnalysis) { + state = s; + analysis = isAnalysis; + root.querySelector('[data-tab="chat"]').hidden = !chat || analysis; + if (analysis && mode === "chat") select("journal"); + refresh(); + }, + setUnread(n) { + const badge = root.querySelector(".unread"); + badge.textContent = n; + badge.hidden = !n; + shortcut.hidden = !n || analysis; + shortcut.innerHTML = `${icon("chat")} ${n}`; + shortcut.setAttribute("aria-label", `${t("chat")}: ${n}`); + }, + setLanguage(l) { + lang = l; + t = translator(l); + root.querySelector("[data-back] span").textContent = t("board"); + root.querySelector('[data-tab="chat"] span').textContent = t("chat"); + refresh(); + }, + destroy() { + observer.disconnect(); + view?.destroy(); + root.remove(); + shortcut.remove(); + }, + }; +} diff --git a/viewer/art.js b/viewer/art.js new file mode 100644 index 0000000..84236d9 --- /dev/null +++ b/viewer/art.js @@ -0,0 +1,59 @@ +export const esc = (x) => + String(x ?? "").replace( + /[&<>"']/g, + (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + c + ], + ); +const paths = { + sail: '', + fish: '', + sell: '', + explore: + '', + build: + '', + draw: '', + tourist: + '', + rest: '', + coin: 'V', + point: + '', + first: + '', + water: + '', + dike: '', + kava: '', + copra: + '', + beef: '', + buy: '', + marker: + '', + chat: '', + journal: + '', + help: '', + fullscreen: + '', + close: + '', + undo: '', + check: + '', + eye: '', + zoom: '', + sound: + '', +}; +export function icon(name, label = "") { + return `${paths[name] ?? paths.point}`; +} +export function svgIcon(name, x, y, size = 26, color = "currentColor") { + return ``; +} +export const token = (name, n) => + `${icon(name)}${esc(n)}`; diff --git a/viewer/assets.js b/viewer/assets.js index f830c79..42825a1 100644 --- a/viewer/assets.js +++ b/viewer/assets.js @@ -56,4 +56,63 @@ import action_tourist from "./assets/action-tourist.webp"; import action_fish from "./assets/action-fish.webp"; import action_sell from "./assets/action-sell.webp"; import action_draw from "./assets/action-draw.webp"; -export const assets={"tile-1":tile_1,"tile-3":tile_3,"tile-5":tile_5,"tile-7":tile_7,"tile-9":tile_9,"tile-11":tile_11,"tile-13":tile_13,"tile-15":tile_15,"tile-17":tile_17,"tile-19":tile_19,"tile-21":tile_21,"tile-23":tile_23,"tile-25":tile_25,"tile-27":tile_27,"tile-29":tile_29,"tile-31":tile_31,"tile-33":tile_33,"tile-35":tile_35,"tile-37":tile_37,"tile-39":tile_39,"character-diver":character_diver,"character-preacher":character_preacher,"character-drawer":character_drawer,"character-purchaser":character_purchaser,"character-fisher":character_fisher,"character-merchant":character_merchant,"character-governess":character_governess,"character-guide":character_guide,"character-worker":character_worker,"character-baggar":character_baggar,"character-navigator":character_navigator,"demand-1":demand_1,"demand-2":demand_2,"demand-3":demand_3,"demand-4":demand_4,"demand-5":demand_5,"demand-6":demand_6,"demand-7":demand_7,"demand-8":demand_8,"demand-9":demand_9,"demand-10":demand_10,"rest-1":rest_1,"rest-2":rest_2,"rest-3":rest_3,"rest-4":rest_4,"efate":efate,"ocean":ocean,"sand":sand,"cover":cover,"action-buy":action_buy,"action-explore":action_explore,"action-sail":action_sail,"action-build":action_build,"action-rest":action_rest,"action-tourist":action_tourist,"action-fish":action_fish,"action-sell":action_sell,"action-draw":action_draw}; +export const assets = { + "tile-1": tile_1, + "tile-3": tile_3, + "tile-5": tile_5, + "tile-7": tile_7, + "tile-9": tile_9, + "tile-11": tile_11, + "tile-13": tile_13, + "tile-15": tile_15, + "tile-17": tile_17, + "tile-19": tile_19, + "tile-21": tile_21, + "tile-23": tile_23, + "tile-25": tile_25, + "tile-27": tile_27, + "tile-29": tile_29, + "tile-31": tile_31, + "tile-33": tile_33, + "tile-35": tile_35, + "tile-37": tile_37, + "tile-39": tile_39, + "character-diver": character_diver, + "character-preacher": character_preacher, + "character-drawer": character_drawer, + "character-purchaser": character_purchaser, + "character-fisher": character_fisher, + "character-merchant": character_merchant, + "character-governess": character_governess, + "character-guide": character_guide, + "character-worker": character_worker, + "character-baggar": character_baggar, + "character-navigator": character_navigator, + "demand-1": demand_1, + "demand-2": demand_2, + "demand-3": demand_3, + "demand-4": demand_4, + "demand-5": demand_5, + "demand-6": demand_6, + "demand-7": demand_7, + "demand-8": demand_8, + "demand-9": demand_9, + "demand-10": demand_10, + "rest-1": rest_1, + "rest-2": rest_2, + "rest-3": rest_3, + "rest-4": rest_4, + efate: efate, + ocean: ocean, + sand: sand, + cover: cover, + "action-buy": action_buy, + "action-explore": action_explore, + "action-sail": action_sail, + "action-build": action_build, + "action-rest": action_rest, + "action-tourist": action_tourist, + "action-fish": action_fish, + "action-sell": action_sell, + "action-draw": action_draw, +}; diff --git a/viewer/assets/ocean.webp b/viewer/assets/ocean.webp index 734f74f..ddbbba1 100644 Binary files a/viewer/assets/ocean.webp and b/viewer/assets/ocean.webp differ diff --git a/viewer/board.js b/viewer/board.js new file mode 100644 index 0000000..d7793e7 --- /dev/null +++ b/viewer/board.js @@ -0,0 +1,99 @@ +import { CELLS, TILES, COLORS, DIRECTIONS } from "../engine/catalog.js"; +import { assets } from "./assets.js"; +import { esc, svgIcon } from "./art.js"; +export const center = (id) => { + const [q, r] = id.split(",").map(Number); + return { x: 355 + q * 162 - r * 81, y: 150 + r * 140.3 }; +}; +function hex(x, y, r = 94) { + return Array.from({ length: 6 }, (_, i) => { + const a = ((60 * i - 30) * Math.PI) / 180; + return `${x + Math.cos(a) * r},${y + Math.sin(a) * r}`; + }).join(" "); +} +const symbols = ["●", "◆", "▲", "■", "✦"]; +export function boardSvg( + s, + { selected, targets = [], hoverTile, player, colorBlind = false, t } = {}, +) { + const targetSet = new Set(targets); + const all = CELLS.map((c) => ({ ...c, ...center(c.id) })); + const visible = all.filter((c) => s.board[c.id] || targetSet.has(c.id)); + const x0 = Math.min(...visible.map((c) => c.x)) - 120, + x1 = Math.max(...visible.map((c) => c.x)) + 120, + y0 = Math.min(...visible.map((c) => c.y)) - 120, + y1 = Math.max(...visible.map((c) => c.y)) + 120; + const defs = all + .map( + (c) => + ``, + ) + .join(""); + let svg = `${defs}`; + for (const c of all) { + const tile = s.board[c.id], + legal = targetSet.has(c.id), + spec = tile ? TILES[tile.id] : null; + svg += ``; + svg += ``; + if (tile) { + svg += ``; + if (tile.submerged) { + svg += `${svgIcon("water", c.x - 25, c.y - 25, 50)}`; + } else if (tile.type === "sea") { + const res = [ + ...(spec.fish ? [["fish", tile.fish]] : []), + ...(spec.treasure ? [["explore", tile.treasure]] : []), + ]; + if (res.length) + svg += ``; + for (const [i, [kind, n]] of res.entries()) { + const x = c.x + 30 - (res.length * 45) / 2 + i * 45; + svg += `${svgIcon(kind, x - 4, c.y - 80, 27)}${n}`; + } + } else { + const goods = Object.entries(tile.goods).filter(([, n]) => n > 0); + let j = 0; + for (const [good, n] of goods) + for (let k = 0; k < n; k++, j++) + svg += svgIcon(good, c.x - 45 + j * 28, c.y + 48, 29); + const huts = tile.huts; + for (let i = 0; i < spec.huts; i++) { + const x = c.x - 40 + i * 32, + y = c.y - 29; + svg += + huts[i] !== undefined + ? svgIcon("build", x, y, 30, COLORS[huts[i]]) + : ``; + if (colorBlind && huts[i] !== undefined) + svg += `${symbols[huts[i]]}`; + } + svg += `${svgIcon("tourist", c.x - 42, c.y + 11, 24)}${tile.tourists}/${spec.tourists}${svgIcon("draw", c.x + 7, c.y + 13, 22)}${tile.drawings}`; + if (tile.water) + svg += `${svgIcon("water", c.x - 74, c.y - 20, 25)}${tile.water}`; + for (const edge of tile.dikes) { + const o = center(edge); + const dx = o.x - c.x, + dy = o.y - c.y; + const mx = c.x + dx * 0.48, + my = c.y + dy * 0.48, + l = Math.hypot(dx, dy); + svg += ``; + } + } + } else if (hoverTile && legal) + svg += ``; + if (!tile) + svg += `${legal ? "+" : "·"}`; + svg += ``; + const boats = s.players + .map((p, i) => ({ p, i })) + .filter(({ p }) => p.boat === c.id); + for (const [i, { p, i: pi }] of boats.entries()) { + const x = c.x + (i - (boats.length - 1) / 2) * 37, + y = c.y + (tile?.type === "sea" ? 11 : 0); + svg += `${svgIcon("sail", 0, 0, 48, p.color)}${colorBlind ? `${symbols[pi]}` : ""}${esc(p.name)}`; + } + } + return svg + ""; +} diff --git a/viewer/host-presentation.js b/viewer/host-presentation.js new file mode 100644 index 0000000..bb408b9 --- /dev/null +++ b/viewer/host-presentation.js @@ -0,0 +1,131 @@ +function installPlayerCards(root, commands) { + let active = null; + function show(event) { + const name = + event.target instanceof Element + ? event.target.closest("[data-bgs-player]") + : null; + if (!name || !root.contains(name) || name === active) return; + const index = Number(name.getAttribute("data-bgs-player")); + if (!Number.isInteger(index) || index < 0) return; + active = name; + commands.hoverPlayer(index, name.getBoundingClientRect()); + } + function hide(event) { + if (!active) return; + const related = event.relatedTarget; + if (related instanceof Node && active.contains(related)) return; + active = null; + commands.leavePlayer(); + } + root.addEventListener("mouseover", show); + root.addEventListener("focusin", show); + root.addEventListener("mouseout", hide); + root.addEventListener("focusout", hide); + return () => { + root.removeEventListener("mouseover", show); + root.removeEventListener("focusin", show); + root.removeEventListener("mouseout", hide); + root.removeEventListener("focusout", hide); + if (active) commands.leavePlayer(); + }; +} +function createBoardThumbnail(root) { + let preview; + function destroy() { + preview?.remove(); + preview = void 0; + } + async function render(source, size, background, omit) { + destroy(); + if (!source?.isConnected || !root.contains(source)) return null; + await document.fonts.ready; + preview = document.createElement("div"); + preview.className = "bgs-board-thumbnail"; + preview.setAttribute("aria-hidden", "true"); + preview.style.cssText = `position:fixed;inset:0 auto auto 0;width:${size.width}px;height:${size.height}px;z-index:2147483647;overflow:hidden;pointer-events:none;background:${background};`; + const freeze = document.createElement("style"); + freeze.textContent = + ".bgs-board-thumbnail *{animation:none!important;transition:none!important;caret-color:transparent!important}"; + preview.append(freeze); + let content; + if (source instanceof SVGElement) { + const svg = + source instanceof SVGSVGElement ? source : source.ownerSVGElement; + if (!svg) return null; + content = svg.cloneNode(false); + content.removeAttribute("id"); + const box = + source instanceof SVGSVGElement + ? source.viewBox.baseVal + : source.getBBox(); + if (!box.width || !box.height) return null; + const padding = + source === svg ? 0 : Math.max(box.width, box.height) * 0.02; + content.setAttribute( + "viewBox", + `${box.x - padding} ${box.y - padding} ${box.width + padding * 2} ${box.height + padding * 2}`, + ); + if (source === svg) { + for (const child of Array.from(source.childNodes)) + content.append(child.cloneNode(true)); + } else { + for (const defs of Array.from(svg.querySelectorAll("defs"))) + content.append(defs.cloneNode(true)); + const copy = source.cloneNode(true); + copy.removeAttribute("transform"); + content.append(copy); + } + content.setAttribute("preserveAspectRatio", "xMidYMid meet"); + content.style.cssText = + "display:block;position:static;width:100%;height:100%;max-width:none;max-height:none;min-width:0;margin:0;transform:none"; + } else { + content = source.cloneNode(true); + content.style.cssText = `display:flex;flex-direction:column;gap:14px;position:relative;width:${source.getBoundingClientRect().width}px;height:${source.getBoundingClientRect().height}px;max-width:none;margin:0;transform-origin:top left;`; + } + if (omit) + for (const element of Array.from(content.querySelectorAll(omit))) + element.remove(); + let parent = preview; + const ancestors = []; + for ( + let ancestor = source.parentElement; + ancestor && ancestor !== document.body; + ancestor = ancestor.parentElement + ) { + if (!(ancestor instanceof SVGElement)) { + ancestors.unshift(ancestor); + } + } + for (const ancestor of ancestors) { + const context = ancestor.cloneNode(false); + context.removeAttribute("id"); + context.style.cssText = + "display:contents!important;transform:none!important;filter:none!important;contain:none!important"; + parent.append(context); + parent = context; + } + parent.append(content); + document.body.append(preview); + if (!(content instanceof SVGSVGElement)) { + const box = content.getBoundingClientRect(); + const scale = Math.min( + 1, + size.width / box.width, + size.height / box.height, + ); + content.style.transform = `translate(${(size.width - box.width * scale) / 2}px, ${(size.height - box.height * scale) / 2}px) scale(${scale})`; + } + await Promise.all( + Array.from(preview.querySelectorAll("img")).map((img) => + img.decode().catch(() => {}), + ), + ); + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return preview; + } + return { render, destroy }; +} +export { createBoardThumbnail, installPlayerCards }; diff --git a/viewer/index.js b/viewer/index.js new file mode 100644 index 0000000..3f0e790 --- /dev/null +++ b/viewer/index.js @@ -0,0 +1,123 @@ +import { mountLesson } from "./tutorial-mount.js"; +import "./style.css"; +import { registerViewer } from "@boardgamers/protocol/viewer"; +import { ChatController } from "@boardgamers/protocol/chat"; +import { mountGame } from "./ui.js"; +import { + createBoardThumbnail, + installPlayerCards, +} from "./host-presentation.js"; +registerViewer( + "vanuatu", + (ctx) => { + const chat = new ChatController(); + let live, + replaying = false, + position = 1, + pending, + timeout; + const ui = mountGame(ctx.target, { + chat, + onOpenPlayer: ctx.openPlayer, + onOpenBoardgame: ctx.openBoardgame, + onPreference: ctx.updatePreference, + onMove: (m) => + new Promise((resolve, reject) => { + pending = { resolve, reject }; + timeout = setTimeout(() => { + pending = undefined; + reject( + Error( + "Waiting for the server. Please refresh if your move has not appeared.", + ), + ); + }, 15000); + ctx.move(m); + }), + }); + const thumbnail = createBoardThumbnail(ctx.target), + removeCards = installPlayerCards(ctx.target, ctx); + function info() { + if (live) + ctx.setReplayInfo({ + start: 1, + current: position, + end: live.historyLength, + }); + } + function seek(index) { + if (!live) return; + position = Math.max(1, Math.min(live.historyLength, index)); + ctx.fetchLog({ start: position - 1, end: position - 1 }); + info(); + } + return { + chat, + onState(state) { + live = state; + if (!replaying) { + position = state.historyLength; + ui.render(state); + ui.setEnabled(true); + } + info(); + if (pending) { + clearTimeout(timeout); + pending.resolve(); + pending = undefined; + } + }, + onPlayer(p) { + ui.setPlayer(p.index); + }, + onPreferences: (p) => ui.setPreferences(p), + onAvatars() {}, + onError(e) { + clearTimeout(timeout); + pending?.reject(e); + pending = undefined; + }, + onLog(log) { + if (!replaying) return; + const data = log.data; + if (data?.frames?.length && log.start === position - 1) { + ui.render({ ...data.frames[0], legal: [], historyLength: position }); + ui.setEnabled(false); + } + }, + onReplayStart() { + replaying = true; + ui.setEnabled(false); + seek(live?.historyLength ?? 1); + }, + onReplayTo(index) { + replaying = true; + seek(index); + }, + onReplayEnd() { + replaying = false; + ui.setEnabled(true); + if (live) { + position = live.historyLength; + ui.render(live); + info(); + } + ctx.fetchState(); + }, + onThumbnail: (size) => + thumbnail.render( + ctx.target.querySelector(".archipelago"), + size, + "#8bcbd4", + ), + destroy() { + clearTimeout(timeout); + pending?.resolve(); + removeCards(); + thumbnail.destroy(); + ui.destroy(); + }, + }; + }, + { tutorial: mountLesson }, +); diff --git a/viewer/labels.js b/viewer/labels.js new file mode 100644 index 0000000..da2d4a4 --- /dev/null +++ b/viewer/labels.js @@ -0,0 +1,142 @@ +const entries = { + sail: ["Sail", "Naviguer"], + fish: ["Fish", "Pêcher"], + sell: ["Sell fish", "Vendre"], + explore: ["Explore", "Explorer"], + build: ["Build", "Construire"], + buy: ["Export", "Exporter"], + draw: ["Draw", "Dessiner"], + tourist: ["Tourists", "Touristes"], + rest: ["Rest", "Se reposer"], + round: ["Round", "Tour"], + character: ["Choose a character", "Choisir un personnage"], + plan: ["Plan your actions", "Programmer les actions"], + actions: ["Choose an action", "Choisir une action"], + expand: ["Extend the archipelago", "Agrandir l’archipel"], + neutral: ["Place the neutral markers", "Placer les pions neutres"], + ended: ["Final scores", "Scores finaux"], + confirm: ["Confirm", "Confirmer"], + choose: ["Choose", "Choisir"], + cancel: ["Cancel", "Annuler"], + undo: ["Undo", "Annuler"], + waiting: ["Waiting for", "Au tour de"], + you: ["You", "Vous"], + spectator: ["Spectator", "Spectateur"], + journal: ["Journal", "Journal"], + chat: ["Chat", "Discussion"], + help: ["Rules & help", "Règles et aide"], + first: ["First player", "Premier joueur"], + both: ["Vatu + prosperity", "Vatu + prospérité"], + point: ["Prosperity", "Prospérité"], + coin: ["Vatu", "Vatu"], + kava: ["Kava", "Kava"], + copra: ["Copra", "Coprah"], + beef: ["Beef", "Bœuf"], + water: ["Rising Waters", "La Montée des eaux"], + ability: ["Use character", "Utiliser le personnage"], + treasure: ["Sell treasures", "Vendre des trésors"], + beg: ["Exchange prosperity", "Échanger de la prospérité"], + governor: ["Move markers", "Déplacer les pions"], + discard: ["Retrieve markers", "Reprendre les pions"], + restChoice: ["Choose a rest token", "Choisir un jeton Repos"], + bonus: ["Character bonus", "Bonus du personnage"], + cost: ["Cost", "Coût"], + income: ["Income", "Revenus"], + gain: ["Gain", "Gain"], + island: ["Island", "Île"], + sea: ["Ocean", "Océan"], + hut: ["Hut", "Cabane"], + dike: ["Dike", "Digue"], + market: ["Fish price", "Prix du poisson"], + demand: ["Foreign trade", "Commerce extérieur"], + next: ["Next islands", "Prochaines tuiles"], + stock: ["Available", "Disponible"], + board: ["Back to board", "Retour au plateau"], + full: ["Full screen", "Plein écran"], + fit: ["Fit board", "Ajuster le plateau"], + zoom: ["Zoom board", "Agrandir le plateau"], + colorBlind: ["Color symbols", "Symboles de couleur"], + sound: ["Game sounds", "Sons du jeu"], + private: ["Private beta", "Bêta privée"], + credit: ["Credits", "Crédits"], + rules: ["Simplified rules", "Règles simplifiées"], + original: ["Original rulebook", "Règles originales"], + twoPlayer: ["Two-player rules", "Règles à deux joueurs"], + source: ["Source code", "Code source"], + noMoves: ["No action available", "Aucune action disponible"], + waterLeft: [ + "Actions until the waters rise", + "Actions avant la montée des eaux", + ], + finished: ["Game finished", "Partie terminée"], + lost: ["The islands were submerged", "Les îles ont été submergées"], + won: ["Winner", "Vainqueur"], + markers: ["Markers", "Pions"], + skip: [ + "No legal effect: retrieve markers", + "Action impossible : reprendre les pions", + ], + demo: ["Local practice", "Entraînement local"], + newGame: ["New game", "Nouvelle partie"], + bots: ["Play with bots", "Jouer avec des bots"], + hotseat: ["Control every seat", "Contrôler tous les joueurs"], + step: ["Bot move", "Coup automatique"], + auto: ["Autoplay", "Jeu automatique"], + saved: ["Saved locally", "Sauvegardé localement"], + selected: ["Selected", "Sélectionné"], + pending: ["Sending…", "Envoi…"], + connected: ["Waiting for the game…", "Chargement de la partie…"], + replay: ["Replay", "Replay"], + wealth: ["Wealth", "Richesse"], + touristScore: ["Visitors × huts", "Touristes × cabanes"], + preferences: ["Preferences", "Préférences"], +}; +export function translator(lang) { + return (key) => entries[key]?.[lang === "fr" ? 1 : 0] ?? key; +} +export const characterHelp = { + navigator: [ + "Sail 1–3 spaces for free.", + "Naviguer de 1 à 3 cases gratuitement.", + ], + fisherman: [ + "Fishing also earns prosperity equal to the fish tile.", + "La pêche rapporte aussi autant de prospérité que la tuile Poisson.", + ], + vendor: [ + "Sell fish without being beside one of your huts.", + "Vendre du poisson sans être près d’une de vos cabanes.", + ], + diver: [ + "Diving also earns vatus equal to the treasure tile.", + "Explorer rapporte aussi autant de vatus que la tuile Trésor.", + ], + builder: [ + "A hut costs 1 vatu instead of 3.", + "Une cabane coûte 1 vatu au lieu de 3.", + ], + buyer: [ + "Export a second matching good from the reserve for free.", + "Exporter gratuitement un second cube identique de la réserve.", + ], + artist: [ + "A drawing earns 5 prosperity instead of 3.", + "Un dessin rapporte 5 prospérité au lieu de 3.", + ], + guide: [ + "Transporting a tourist earns 2 prosperity per drawing on that island.", + "Transporter un touriste rapporte 2 prospérité par dessin sur cette île.", + ], + beggar: [ + "Once per round, exchange up to 3 prosperity for the same number of vatus.", + "Une fois par tour, échanger jusqu’à 3 prospérité contre autant de vatus.", + ], + preacher: [ + "If you hold no majority, perform one planned action anyway.", + "Sans aucune majorité, effectuer tout de même une action programmée.", + ], + governor: [ + "Instead of an action, move your entire stack to another action.", + "Au lieu d’une action, déplacer toute une pile vers une autre action.", + ], +}; diff --git a/viewer/preview.js b/viewer/preview.js new file mode 100644 index 0000000..37f273b --- /dev/null +++ b/viewer/preview.js @@ -0,0 +1,142 @@ +import { mountLesson } from "./tutorial-mount.js"; +import "./style.css"; +import * as engine from "../engine/index.js"; +import { mountGame } from "./ui.js"; +const params = new URLSearchParams(location.search); +if (params.has("lesson")) { + const names = ["planning", "fishing", "islands"]; + const chapter = params.get("lesson"); + const next = names[names.indexOf(chapter) + 1]; + await mountLesson(document.querySelector("#game"), { + chapter, + nextChapter: next + ? { + title: next, + open: () => { + location.search = "?lesson=" + next; + }, + } + : undefined, + }); +} else { + const count = Math.max(2, Math.min(5, Number(params.get("players") ?? 3))); + let state, + hotseat = params.has("hotseat"), + timer; + const storageKey = "vanuatu-practice-v1"; + try { + if (!params.has("new")) + state = JSON.parse(localStorage.getItem(storageKey)); + } catch {} + if (!state?.version) + state = engine.init( + count, + params.has("water") ? ["rising-waters"] : [], + {}, + params.get("seed") ?? "island-breeze", + ); + state.players.forEach( + (p, i) => (p.name = ["You", "Maya", "Noa", "Leo", "Nina"][i]), + ); + const control = document.createElement("div"); + control.className = "preview-controls"; + control.innerHTML = + 'Local practice · private beta'; + document.body.prepend(control); + control.querySelector("[data-count]").value = state.players.length; + control.querySelector("[data-water]").checked = state.options.risingWaters; + control.querySelector("[data-hotseat]").checked = hotseat; + const ui = mountGame(document.querySelector("#game"), { + onMove: (m) => { + state = engine.move(state, m, hotseat ? state.actor : 0); + save(); + show(); + scheduleBots(); + }, + onPreference: (name, value) => { + preferences[name] = value; + localStorage.setItem("vanuatu-preferences", JSON.stringify(preferences)); + ui.setPreferences(preferences); + }, + }); + let preferences = {}; + try { + preferences = JSON.parse(localStorage.getItem("vanuatu-preferences")) ?? {}; + } catch {} + ui.setPreferences(preferences); + function save() { + try { + localStorage.setItem(storageKey, JSON.stringify(state)); + } catch {} + } + function show() { + const p = hotseat ? state.actor : 0; + ui.setPlayer(p); + ui.render(engine.stripSecret(state, p)); + } + function scheduleBots() { + clearTimeout(timer); + if (!hotseat && !state.finished && state.actor !== 0) + timer = setTimeout(() => { + state = engine.moveAI(state, state.actor); + save(); + show(); + scheduleBots(); + }, 450); + } + function bot() { + if (state.finished) return; + state = engine.moveAI(state, state.actor); + save(); + show(); + scheduleBots(); + } + control.querySelector("[data-new]").onclick = () => { + clearTimeout(timer); + state = engine.init( + Number(control.querySelector("[data-count]").value), + control.querySelector("[data-water]").checked ? ["rising-waters"] : [], + {}, + crypto.randomUUID(), + ); + state.players.forEach( + (p, i) => (p.name = ["You", "Maya", "Noa", "Leo", "Nina"][i]), + ); + save(); + show(); + scheduleBots(); + }; + control.querySelector("[data-hotseat]").onchange = (e) => { + hotseat = e.target.checked; + show(); + scheduleBots(); + }; + control.querySelector("[data-step]").onclick = bot; + let autoplay = false; + control.querySelector("[data-auto]").onclick = async (e) => { + autoplay = !autoplay; + e.target.textContent = autoplay ? "Stop" : "Autoplay"; + while (autoplay && !state.finished) { + clearTimeout(timer); + state = engine.moveAI(state, state.actor); + save(); + show(); + await new Promise((r) => setTimeout(r, 160)); + } + autoplay = false; + e.target.textContent = "Autoplay"; + }; + window.vanuatuDemo = { + get state() { + return state; + }, + setState(s) { + state = s; + show(); + }, + engine, + ui, + }; + show(); + scheduleBots(); +} diff --git a/viewer/rules.js b/viewer/rules.js new file mode 100644 index 0000000..89063c8 --- /dev/null +++ b/viewer/rules.js @@ -0,0 +1,82 @@ +import { icon, token } from "./art.js"; +export function rulesHtml(lang = "en") { + const fr = lang === "fr"; + const paragraphs = fr + ? [ + [ + "Vivre de l’archipel", + `En 8 tours, gagnez de la prospérité ${icon("point")} en commerçant, en accueillant des touristes et en créant des dessins de sable. ${token("coin", 10)} se convertissent immédiatement en ${token("point", 5)}.`, + ], + [ + "Programmer, puis agir", + `Choisissez un personnage, puis placez vos 5 pions en trois passages : 2, 2, 1. À votre tour, effectuez une action où vous avez le plus de pions. Les égalités se départagent depuis le premier joueur ${icon("first")}. Tous vos pions de cette action sont repris. Sans majorité, reprenez une pile sans effectuer l’action.`, + ], + [ + "Au bon endroit", + `Naviguez ${icon("sail")} de 1 à 3 cases d’océan pour autant de ${icon("coin")}. Pêchez ${icon("fish")} ou explorez ${icon("explore")} sur votre case : prenez la valeur encore présente, puis retirez un marqueur. Les autres actions concernent une île voisine.`, + ], + [ + "Faire du commerce", + `Vendez vos poissons près de l’une de vos cabanes ${icon("build")} : leur valeur × le prix du marché. Le prix diminue après chaque vente. Exportez ${icon("kava")} / ${icon("copra")} / ${icon("beef")} pour ${token("coin", "1 / 2 / 3")}, contre ${token("point", "1 / 3 / 5")} si un navire en demande. Compléter un navire rapporte ${token("point", 2)}.`, + ], + [ + "Développer les îles", + `Une cabane ${icon("build")} coûte ${token("coin", 3)}. Un dessin ${icon("draw")} rapporte ${token("point", 3)}. Transporter un touriste ${icon("tourist")} rapporte ${token("coin", 1)} par cabane sur cette île, quelle que soit sa couleur. Se reposer ${icon("rest")} permet de choisir un bonus secret, résolu en fin de tour.`, + ], + [ + "Personnages", + `Chaque personnage améliore une action, une fois par tour. Vous choisissez le nouveau personnage avant de rendre l’ancien : impossible de garder le même deux tours de suite. Les trésors ${icon("explore")} peuvent être vendus à tout moment pour leur valeur en ${icon("coin")}.`, + ], + [ + "Fin de partie", + `Après le 8e tour : poissons restants → autant de ${icon("coin")}, premier joueur → ${token("point", 3)}, chaque ${token("coin", 3)} → ${token("point", 1)}, trésors → deux fois leur valeur en ${icon("point")}, chaque cabane → ${token("point", 2)} par touriste sur son île. La plus grande prospérité l’emporte ; puis le plus de cabanes, puis de vatus.`, + ], + [ + "À deux joueurs", + `Placez d’abord 2, puis 3 pions neutres. Pour agir, il faut aussi dépasser leur nombre ; le personnage correspondant permet de les égaler. Les personnages disponibles changent chaque tour. Deux bateaux ne peuvent pas terminer leur déplacement sur la même case.`, + ], + [ + "La Montée des eaux", + `Aux tours pairs, le dé indique combien d’actions précèdent l’inondation. Chaque côte adjacente à un océan et sans digue ajoute 1 eau. Construisez une digue ${icon("dike")} pour ${token("coin", 1)} avec l’action Construire. À 5 eaux, l’île est submergée ; à 3 îles submergées, tout le monde perd. Chaque cabane sur une île avec 1 / 2 / 3 / 4 eaux perd 1 / 3 / 5 / 7 prospérité en fin de partie.`, + ], + ] + : [ + [ + "A living archipelago", + `Over 8 rounds, earn prosperity ${icon("point")} through trade, tourism and sand drawings. Every ${token("coin", 10)} immediately becomes ${token("point", 5)}.`, + ], + [ + "Plan, then act", + `Choose a character, then place your 5 markers in three passes: 2, 2, 1. On your turn, take an action where you have the most markers. Ties follow turn order from the first player ${icon("first")}. Retrieve all your markers from that action. Without a majority, retrieve one stack without performing its action.`, + ], + [ + "Be in the right place", + `Sail ${icon("sail")} 1–3 ocean spaces for that many ${icon("coin")}. Fish ${icon("fish")} or explore ${icon("explore")} on your space: take its remaining value, then remove one marker. Island actions need your boat beside the island.`, + ], + [ + "Trade", + `Sell fish beside one of your huts ${icon("build")}: fish values × the market price. The price falls after each sale. Export ${icon("kava")} / ${icon("copra")} / ${icon("beef")} for ${token("coin", "1 / 2 / 3")}, earning ${token("point", "1 / 3 / 5")} when a ship needs them. Completing a ship earns ${token("point", 2)}.`, + ], + [ + "Develop the islands", + `A hut ${icon("build")} costs ${token("coin", 3)}. A drawing ${icon("draw")} earns ${token("point", 3)}. Transporting a tourist ${icon("tourist")} earns ${token("coin", 1)} for every hut on that island, of any colour. Rest ${icon("rest")} lets you choose a secret bonus, resolved at the end of the round.`, + ], + [ + "Characters", + `Each character improves one action, once per round. Choose your next character before returning your old one; you cannot keep the same character for consecutive rounds. Treasures ${icon("explore")} may be sold at any time for their value in ${icon("coin")}.`, + ], + [ + "Final scoring", + `After round 8: remaining fish → their value in ${icon("coin")}; first player → ${token("point", 3)}; every ${token("coin", 3)} → ${token("point", 1)}; treasures → twice their value in ${icon("point")}; each hut → ${token("point", 2)} per tourist on its island. Most prosperity wins; ties favour more huts, then more vatus.`, + ], + [ + "Two players", + `Place 2, then 3 neutral markers before choosing characters. You must also beat the neutral stack to act; the matching character lets you tie it. Available characters change each round. Boats cannot end their movement on the same space.`, + ], + [ + "Rising Waters", + `On even rounds, the die gives the number of actions before flooding. Every adjacent ocean coast without a dike adds 1 water. Build a dike ${icon("dike")} for ${token("coin", 1)} with the Build action. At 5 waters an island sinks; if 3 islands sink, everyone loses. Each hut on an island with 1 / 2 / 3 / 4 waters loses 1 / 3 / 5 / 7 prosperity at game end.`, + ], + ]; + return `
    ${paragraphs.map(([h, p]) => `

    ${h}

    ${p}

    `).join("")}
    `; +} diff --git a/viewer/style.css b/viewer/style.css new file mode 100644 index 0000000..43461f0 --- /dev/null +++ b/viewer/style.css @@ -0,0 +1,1271 @@ +.vanuatu { + --ink: #244e53; + --muted: #718786; + --paper: #fcf8eb; + --gold: #b67738; + --line: #d3d4be; + color: var(--ink); + background: #f2f0e4; + font: + 14px/1.45 system-ui, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + sans-serif; + min-height: 100%; + isolation: isolate; + padding: 0 16px; + box-sizing: border-box; +} +.vanuatu * { + box-sizing: border-box; +} +.vanuatu button, +.vanuatu select, +.vanuatu input { + font: inherit; +} +.vanuatu button { + color: inherit; + cursor: pointer; + border: 1px solid var(--line); + background: var(--paper); + border-radius: 7px; + padding: 7px 11px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + line-height: 1.25; + transition: + background 0.12s, + box-shadow 0.12s; +} +.vanuatu button:hover:not(:disabled) { + background: #fffdfa; + box-shadow: 0 2px 7px #193e4520; +} +.vanuatu button:disabled { + cursor: default; + opacity: 0.4; +} +.vanuatu button:focus-visible, +.vanuatu [role="button"]:focus-visible { + outline: 3px solid #bb773c; + outline-offset: 3px; +} +.vanuatu .icon { + width: 23px; + height: 23px; + flex: none; + vertical-align: middle; +} +.vanuatu .token { + display: inline-flex; + align-items: center; + gap: 3px; + vertical-align: middle; + white-space: nowrap; +} +.vanuatu .token b { + font-weight: 650; + font-variant-numeric: tabular-nums; +} +.vanuatu .primary { + background: #245e62; + color: #fff9e8; + border-color: #245e62; + box-shadow: 0 2px 0 #173e3f; + padding: 9px 15px; +} +.vanuatu .primary:hover:not(:disabled) { + background: #327476; +} +.vanuatu .icon-button { + width: 37px; + height: 37px; + padding: 7px; + border: 0; + background: transparent; +} +.vanuatu .text-button { + background: transparent; + border: 0; + padding: 3px; + font-size: 12px; +} +.vanuatu a { + color: #276675; + text-underline-offset: 3px; +} +.vanuatu [hidden] { + display: none !important; +} +.vanuatu .game-header { + display: flex; + align-items: center; + gap: 24px; + max-width: 1500px; + margin: auto; + min-height: 77px; +} +.vanuatu .brand { + display: flex; + align-items: baseline; + gap: 13px; +} +.vanuatu .wordmark { + font: + bold 35px Georgia, + serif; + letter-spacing: -1.7px; + border: 0; + padding: 0; + background: none; + color: #26595c; +} +.vanuatu .brand > span { + font-size: 10px; + color: var(--muted); + white-space: nowrap; +} +.vanuatu .round-track { + display: flex; + align-items: center; + gap: 7px; + margin-left: auto; +} +.vanuatu .round-track span { + width: 23px; + height: 23px; + border-radius: 50%; + display: grid; + place-items: center; + color: #7d918b; + font-size: 11px; +} +.vanuatu .round-track .current { + background: #285c60; + color: #ffedce; + font-weight: 750; + box-shadow: 0 0 0 3px #285c6020; +} +.vanuatu .round-track .past { + background: #dedecf; +} +.vanuatu .header-tools { + display: flex; + gap: 3px; +} +.vanuatu .header-tools button { + position: relative; +} +.vanuatu .unread-badge { + position: absolute; + top: 0; + right: 0; + min-width: 15px; + height: 15px; + border-radius: 20px; + background: #c26138; + color: white; + font-size: 9px; + padding: 1px 3px; +} +.vanuatu .table { + display: grid; + grid-template-columns: 166px minmax(0, 1fr); + gap: 14px; + max-width: 1500px; + margin: auto; + align-items: stretch; +} +.vanuatu .action-dock { + display: flex; + flex-direction: column; + gap: 5px; + justify-content: center; + padding: 12px 0; +} +.vanuatu .action-dock > button { + position: relative; + display: grid; + grid-template-columns: 33px 1fr; + grid-template-rows: auto auto; + justify-items: start; + column-gap: 7px; + row-gap: 3px; + min-height: 54px; + border: 0; + border-bottom: 1px solid #d1d4c5; + border-radius: 4px; + background: #e9e9d9; + padding: 6px 10px; + box-shadow: inset 3px 0 #a2b6a4; +} +.vanuatu .action-dock .action-symbol { + grid-row: 1/3; + align-self: center; +} +.vanuatu .action-dock .action-symbol .icon { + height: 30px; + width: 30px; +} +.vanuatu .action-label { + font-size: 11px; + font-weight: 650; +} +.vanuatu .action-stacks { + min-height: 15px; + display: flex; + gap: 3px; + align-items: center; +} +.vanuatu .action-dock > button:disabled { + opacity: 0.66; +} +.vanuatu .action-dock .available { + background: #fcf8e9; + box-shadow: inset 3px 0 #ae793f; +} +.vanuatu .action-dock .chosen { + background: #f5d99f; + box-shadow: + inset 3px 0 #a16a28, + 0 0 0 1px #a16a28; +} +.vanuatu .marker-stack { + display: inline-flex; + justify-content: center; + align-items: center; + min-width: 20px; + height: 16px; + background: var(--player); + color: #fff; + border-radius: 8px; + font-size: 10px; + font-weight: 750; + text-shadow: 0 1px 2px #0007; + border: 1px solid #fff9; + box-shadow: 0 2px 0 color-mix(in srgb, var(--player), #000 20%); +} +.vanuatu .marker-stack.majority { + outline: 1px solid #72552a; + outline-offset: 1px; +} +.vanuatu .marker-stack.neutral { + --player: #4b4b43; +} +.vanuatu .draft-marker { + color: #8f5c20; + font-weight: 800; + font-size: 12px; +} +.vanuatu .sea-board { + position: relative; + border: 1px solid #84b7b9; + border-radius: 18px; + background: #80c7d2; + overflow: hidden; + box-shadow: 0 6px 18px #254c4715; + min-width: 0; +} +.vanuatu .sea-board:before { + content: ""; + position: absolute; + inset: 0; + background-image: var(--ocean); + background-size: 850px; + opacity: 0.75; + pointer-events: none; +} +.vanuatu .map-scroll { + position: relative; + width: 100%; + overflow: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + min-height: 490px; + height: min(69vh, 740px); + padding: 65px 10px 83px; +} +.vanuatu .archipelago { + display: block; + width: 100%; + height: 100%; + overflow: visible; + min-height: 345px; +} +.vanuatu .map-scroll.zoomed .archipelago { + width: 1450px; + height: 900px; + min-height: 900px; +} +.vanuatu .cell-surface { + fill: #eafcf915; + stroke: #e8fff959; + stroke-width: 1; + stroke-dasharray: 4 5; +} +.vanuatu .cell-ring { + fill: none; + stroke: none; + pointer-events: none; +} +.vanuatu .empty-label { + fill: #def6ed99; + font-size: 24px; + text-anchor: middle; + pointer-events: none; +} +.vanuatu .map-cell.legal { + cursor: pointer; +} +.vanuatu .map-cell.legal .cell-ring { + stroke: #fffbe0; + stroke-width: 4; + stroke-dasharray: 8 5; +} +.vanuatu .map-cell.legal:hover .cell-ring, +.vanuatu .map-cell.selected .cell-ring { + stroke: #9c692c; + stroke-width: 5; + stroke-dasharray: none; +} +.vanuatu .tile-ghost { + opacity: 0.25; +} +.vanuatu .resource-n { + font-size: 18px; + font-weight: 700; + fill: #345257; + text-anchor: middle; + paint-order: stroke; + stroke: #fffbe3; + stroke-width: 1px; +} +.vanuatu .color-symbol { + font-size: 15px; + font-weight: 700; + fill: #173d49; + text-anchor: middle; + paint-order: stroke; + stroke: #fffce8; + stroke-width: 2px; +} +.vanuatu .boat { + pointer-events: none; +} +.vanuatu .boat.own { + filter: drop-shadow(0 0 3px #fffbe3); +} +.vanuatu .sea-dashboard { + position: absolute; + top: 12px; + left: 18px; + right: 18px; + z-index: 2; + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + pointer-events: none; +} +.vanuatu .market-info { + display: flex; + flex-wrap: wrap; + gap: 13px; + background: #f6f4dfdb; + border: 1px solid #fff9; + padding: 7px 12px; + border-radius: 9px; + box-shadow: 0 2px 4px #38777518; + font-size: 12px; +} +.vanuatu .market-info > span { + display: flex; + align-items: center; + gap: 3px; +} +.vanuatu .demand-ships { + display: flex; + gap: 7px; +} +.vanuatu .demand-ship { + background: #faf1cfdf; + border: 1px solid #b7975c66; + border-radius: 5px 5px 17px 17px; + display: flex; + align-items: center; + padding: 4px 8px; + gap: 2px; +} +.vanuatu .demand-ship > small { + margin-right: 3px; + opacity: 0.6; + font-size: 9px; +} +.vanuatu .demand-ship > span { + position: relative; +} +.vanuatu .demand-ship .icon { + width: 21px; + height: 21px; +} +.vanuatu .demand-ship .filled > .icon:first-child { + opacity: 0.23; +} +.vanuatu .demand-ship .filled > .icon:last-child { + position: absolute; + inset: 0; + color: #356658; +} +.vanuatu .map-tools { + position: absolute; + left: 10px; + bottom: 85px; + z-index: 2; +} +.vanuatu .map-tools button { + background: #fff8dfcf; +} +.vanuatu .upcoming { + position: absolute; + right: 13px; + bottom: 87px; + display: flex; + gap: 0; + pointer-events: none; +} +.vanuatu .upcoming img { + width: 57px; + height: 57px; + object-fit: contain; + filter: drop-shadow(0 2px 2px #163d4a44); +} +.vanuatu .turn-tray { + position: absolute; + bottom: 0; + left: 0; + right: 0; + min-height: 73px; + max-height: 235px; + overflow: auto; + background: #fff9e8f5; + border-top: 1px solid #d5bd8a; + box-shadow: 0 -4px 18px #31555815; + display: flex; + align-items: center; + justify-content: center; + flex-wrap: wrap; + gap: 10px; + padding: 12px 18px; + z-index: 3; +} +.vanuatu .tray-title { + font-weight: 650; + font-size: 13px; + display: flex; + align-items: center; + gap: 8px; +} +.vanuatu .tray-title small { + font-weight: 400; + color: var(--muted); +} +.vanuatu .turn-dot { + width: 9px; + height: 9px; + border-radius: 50%; +} +.vanuatu .draft-slots { + display: flex; + gap: 6px; +} +.vanuatu .draft-slot { + display: grid; + place-items: center; + width: 35px; + height: 35px; + border: 1px dashed #c7b180; + border-radius: 7px; + background: #f5e8c5; + color: #beae84; +} +.vanuatu .draft-slot .icon { + height: 26px; + width: 26px; +} +.vanuatu .move-options { + display: flex; + flex-wrap: wrap; + gap: 7px; + align-items: center; +} +.vanuatu .move-option { + font-size: 12px; +} +.vanuatu .move-option .token { + gap: 2px; +} +.vanuatu .move-option .icon { + height: 24px; + width: 24px; +} +.vanuatu .bonus-switch { + display: flex; + align-items: center; + gap: 5px; + font-size: 11px; +} +.vanuatu input[type="checkbox"] { + accent-color: #29666a; +} +.vanuatu .pick-hint { + font-size: 12px; + color: #7b785f; +} +.vanuatu .character-tray { + display: block; + text-align: left; + padding: 10px 15px; +} +.vanuatu .character-tray .tray-title { + margin-bottom: 7px; +} +.vanuatu .character-choices { + display: flex; + overflow: auto; + gap: 8px; + padding-bottom: 4px; +} +.vanuatu .character-choice { + display: grid; + grid-template-columns: 43px 1fr; + grid-template-rows: auto auto; + column-gap: 8px; + row-gap: 3px; + flex: 0 0 178px; + min-height: 87px; + text-align: left; + align-items: start; + padding: 7px; + background: #fcf7e3; +} +.vanuatu .character-choice img { + width: 43px; + height: 60px; + object-fit: cover; + border-radius: 50% 50% 6px 6px; + grid-row: 1/3; + align-self: center; +} +.vanuatu .character-choice strong { + font-size: 12px; +} +.vanuatu .character-choice span { + font-size: 10px; + color: #778078; + line-height: 1.35; +} +.vanuatu .tile-choices { + display: flex; + gap: 4px; +} +.vanuatu .tile-choices button { + padding: 0; + border: 2px solid transparent; + background: none; +} +.vanuatu .tile-choices button[aria-pressed="true"] { + border-color: #b17734; + background: #f8e1ad; +} +.vanuatu .tile-choices img { + width: 57px; + height: 57px; + object-fit: contain; +} +.vanuatu .players { + max-width: 1500px; + margin: 15px auto 0; + display: flex; + gap: 11px; + align-items: stretch; +} +.vanuatu .player-card { + position: relative; + flex: 1; + min-width: 0; + background: #f9f6e9; + border: 1px solid #d5d8c5; + border-radius: 9px; + padding: 10px 12px 8px; + border-top: 3px solid var(--player); +} +.vanuatu .player-card.active { + box-shadow: 0 0 0 2px var(--player); +} +.vanuatu .player-name { + display: flex; + align-items: center; + gap: 5px; +} +.vanuatu .profile { + border: 0; + background: none; + font-size: 12px; + font-weight: 650; + padding: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + display: block; + max-width: 140px; +} +.vanuatu .score { + margin-left: auto; + font-size: 17px; +} +.vanuatu .score .icon { + height: 24px; + width: 24px; +} +.vanuatu .player-supplies { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 9px; + margin-top: 7px; + font-size: 12px; +} +.vanuatu .player-supplies .icon { + width: 21px; + height: 21px; +} +.vanuatu .hand { + display: flex; + gap: 2px; +} +.vanuatu .character-owned { + display: flex; + width: 100%; + margin-top: 8px; + gap: 6px; + background: #ededdc; + padding: 3px 8px 3px 3px; + border: 0; + border-radius: 20px; + font-size: 10px; + justify-content: flex-start; +} +.vanuatu .character-owned img { + width: 25px; + height: 25px; + object-fit: cover; + object-position: 50% 20%; + border-radius: 50%; +} +.vanuatu .character-owned > span { + flex: 1; + text-align: left; +} +.vanuatu .character-owned > .icon { + height: 20px; + width: 20px; +} +.vanuatu .character-owned.used { + opacity: 0.55; +} +.vanuatu .free-actions { + display: flex; + gap: 5px; + margin-top: 4px; +} +.vanuatu .free-actions:empty { + display: none; +} +.vanuatu .free-actions button { + padding: 2px 6px; + background: transparent; +} +.vanuatu .free-actions .icon { + height: 18px; + width: 18px; +} +.vanuatu .play-footer { + display: flex; + justify-content: space-between; + align-items: center; + max-width: 1500px; + margin: 10px auto 17px; + color: #839083; + font-size: 10px; +} +.vanuatu .play-footer .icon { + height: 18px; + width: 18px; +} +.vanuatu .help-dialog { + border: 1px solid #ccbc94; + border-radius: 14px; + padding: 27px 30px; + max-width: min(770px, calc(100vw - 24px)); + max-height: 87dvh; + overflow: auto; + color: var(--ink); + background: var(--paper); + box-shadow: 0 15px 70px #173c4660; +} +.vanuatu .help-dialog::backdrop { + background: #193d467d; + backdrop-filter: blur(3px); +} +.vanuatu .dialog-close { + position: sticky; + top: -17px; + float: right; + background: var(--paper); + z-index: 2; +} +.vanuatu .help-dialog h2 { + font-family: Georgia, serif; + font-size: 25px; + margin-top: 0; +} +.vanuatu .help-dialog h3 { + font-size: 14px; + margin-bottom: 5px; +} +.vanuatu .help-dialog p { + margin: 5px 0 15px; + font-size: 13px; + line-height: 1.65; +} +.vanuatu .rules .icon { + width: 21px; + height: 21px; +} +.vanuatu .preferences { + display: flex; + flex-wrap: wrap; + gap: 15px; + font-size: 12px; + padding: 0 0 15px; + border-bottom: 1px solid var(--line); +} +.vanuatu select { + background: #fff9e8; + border: 1px solid var(--line); + color: var(--ink); + border-radius: 6px; + padding: 4px; +} +.vanuatu .character-detail { + display: flex; + align-items: center; + gap: 23px; +} +.vanuatu .character-detail img { + width: 125px; + height: 170px; + object-fit: cover; + border-radius: 55% 55% 15px 15px; +} +.vanuatu .character-detail p { + max-width: 320px; +} +.vanuatu .island-detail { + display: flex; + gap: 20px; + align-items: center; +} +.vanuatu .island-detail img { + width: 180px; + max-width: 45%; +} +.vanuatu .final-scores > div { + display: flex; + gap: 15px; + align-items: center; + border-left: 4px solid var(--player); + padding: 10px; + margin: 8px 0; + background: #ececd9; +} +.vanuatu .final-scores small { + font-size: 10px; +} +.vanuatu .feedback { + position: fixed; + top: 15px; + left: 50%; + transform: translateX(-50%); + max-width: 90vw; + padding: 13px; + background: #fff4e3; + border: 1px solid #b66e45; + color: #87472f; + border-radius: 8px; + z-index: 100; +} +.vanuatu .activity { + max-width: 1500px; + margin: 0 auto 20px; + border: 1px solid #d4d8c5; + border-radius: 11px; + background: #faf7ec; + overflow: hidden; +} +.vanuatu .activity > header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 15px; + border-bottom: 1px solid var(--line); +} +.vanuatu .activity [role="tablist"] { + display: flex; + gap: 15px; +} +.vanuatu .activity [role="tab"] { + border: 0; + background: none; + padding: 6px 1px; + font-size: 12px; + border-radius: 0; + border-bottom: 2px solid transparent; +} +.vanuatu .activity [aria-selected="true"] { + border-bottom-color: #377a78; +} +.vanuatu .activity [role="tab"] .icon { + height: 20px; + width: 20px; +} +.vanuatu .event-list { + margin: 0; + padding: 12px 20px; + height: 230px; + overflow: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + list-style: none; +} +.vanuatu .event-list li { + display: flex; + align-items: center; + gap: 5px; + min-height: 32px; + font-size: 12px; + border-bottom: 1px solid #dce0cc60; + flex-wrap: wrap; +} +.vanuatu .event-list li > small:first-child { + min-width: 18px; + color: #9b9a7e; + font-size: 10px; +} +.vanuatu .event-list .icon { + height: 23px; + width: 23px; +} +.vanuatu .chat-panel { + --chat-background: #faf7ec; + --chat-color: #244e53; + --chat-border: #d4d8c5; + padding: 0 15px 10px; +} +.vanuatu .chat-panel details { + border: 0; + box-shadow: none; + background: none; + margin: 0; + max-width: none; + width: 100%; + color: var(--ink); +} +.vanuatu .chat-panel summary { + display: none; +} +.vanuatu .chat-panel .chat-messages { + max-height: 300px; + min-height: 180px; + overscroll-behavior: contain; +} +.vanuatu .chat-panel input { + background: #fffdf5; + color: var(--ink); + border-color: var(--line); +} +.vanuatu .chat-shortcut { + position: fixed; + top: 100px; + left: 8px; + z-index: 20; + background: #fff6db; + border: 2px solid #b98041; + box-shadow: 0 3px 12px #173d4933; +} +.vanuatu .unread { + font-size: 10px; + border-radius: 20px; + background: #b7773b; + color: white; + padding: 2px 5px; +} +.vanuatu:fullscreen { + overflow: auto; +} +.vanuatu .loading { + padding: 100px; + text-align: center; +} +.preview-controls { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + padding: 7px; + background: #dfe7de; + font: 12px system-ui; + color: #355c5d; +} +.preview-controls button, +.preview-controls select { + font: inherit; + background: #f6f5e8; + color: inherit; + border: 1px solid #abbfb4; + border-radius: 4px; + padding: 4px 8px; +} +body { + margin: 0; +} +@media (min-width: 1550px) { + .vanuatu .map-scroll { + height: min(73vh, 800px); + } +} +@media (max-width: 1050px) { + .vanuatu .brand > span { + display: none; + } + .vanuatu .table { + grid-template-columns: 127px minmax(0, 1fr); + gap: 10px; + } + .vanuatu .action-dock > button { + padding: 5px 7px; + grid-template-columns: 26px 1fr; + } + .vanuatu .action-dock .action-symbol .icon { + width: 26px; + height: 26px; + } + .vanuatu .marker-stack { + min-width: 16px; + font-size: 9px; + } + .vanuatu .sea-dashboard { + left: 10px; + right: 10px; + } + .vanuatu .demand-ship { + padding: 4px; + } + .vanuatu .demand-ship > .icon { + display: none; + } + .vanuatu .players { + gap: 8px; + overflow: auto; + padding: 2px 2px 5px; + } + .vanuatu .player-card { + min-width: 190px; + } + .vanuatu .map-scroll { + height: 65vh; + min-height: 520px; + padding-top: 77px; + } + .vanuatu .market-info { + gap: 6px; + padding: 5px 7px; + } + .vanuatu .turn-tray { + gap: 8px; + padding: 10px; + } + .vanuatu .character-choice { + flex-basis: 167px; + } +} +@media (max-width: 700px) { + .vanuatu { + padding: 0 8px; + } + .vanuatu .game-header { + min-height: 65px; + gap: 8px; + flex-wrap: wrap; + padding: 8px 3px; + } + .vanuatu .wordmark { + font-size: 29px; + } + .vanuatu .header-tools { + margin-left: auto; + } + .vanuatu .header-tools .icon-button { + width: 32px; + height: 32px; + padding: 6px; + } + .vanuatu .round-track { + order: 3; + justify-content: center; + flex-basis: 100%; + gap: 15px; + } + .vanuatu .round-track span { + height: 18px; + width: 18px; + font-size: 10px; + } + .vanuatu .table { + display: flex; + flex-direction: column; + gap: 8px; + } + .vanuatu .action-dock { + flex-direction: row; + justify-content: stretch; + gap: 4px; + padding: 0; + overflow: auto; + scrollbar-width: thin; + order: 0; + } + .vanuatu .action-dock > button { + flex: 1 0 58px; + display: flex; + align-items: center; + flex-direction: column; + justify-content: center; + min-height: 74px; + padding: 4px; + box-shadow: inset 0 3px #a2b6a4; + } + .vanuatu .action-dock .available { + box-shadow: inset 0 3px #ae793f; + } + .vanuatu .action-dock .chosen { + box-shadow: + inset 0 3px #a16a28, + 0 0 0 1px #a16a28; + } + .vanuatu .action-label { + font-size: 9px; + white-space: nowrap; + } + .vanuatu .action-stacks { + gap: 2px; + min-height: 14px; + max-width: 60px; + flex-wrap: wrap; + } + .vanuatu .marker-stack { + min-width: 13px; + height: 13px; + font-size: 8px; + } + .vanuatu .sea-board { + border-radius: 12px; + } + .vanuatu .map-scroll { + height: 57vh; + min-height: 430px; + padding: 80px 0 104px; + } + .vanuatu .archipelago { + min-height: 245px; + } + .vanuatu .sea-dashboard { + top: 8px; + flex-wrap: wrap; + justify-content: center; + gap: 5px; + } + .vanuatu .market-info { + font-size: 10px; + gap: 12px; + padding: 3px 9px; + background: #fff7dbb5; + } + .vanuatu .market-info .icon { + width: 19px; + height: 19px; + } + .vanuatu .demand-ships { + gap: 4px; + } + .vanuatu .demand-ship { + padding: 3px 5px; + } + .vanuatu .demand-ship .icon { + width: 17px; + height: 17px; + } + .vanuatu .turn-tray { + min-height: 95px; + max-height: 195px; + gap: 7px; + padding: 8px; + align-content: center; + } + .vanuatu .tray-title { + font-size: 12px; + } + .vanuatu .character-tray .tray-title { + margin-bottom: 5px; + } + .vanuatu .character-choice { + min-height: 78px; + flex-basis: 164px; + } + .vanuatu .character-choice img { + height: 54px; + width: 39px; + } + .vanuatu .map-tools { + bottom: 107px; + left: 6px; + } + .vanuatu .upcoming { + bottom: 106px; + right: 7px; + } + .vanuatu .upcoming img { + width: 37px; + height: 37px; + } + .vanuatu .players { + margin-top: 10px; + gap: 8px; + scroll-snap-type: x proximity; + } + .vanuatu .player-card { + flex: 0 0 215px; + scroll-snap-align: start; + } + .vanuatu .play-footer { + margin: 6px auto 12px; + } + .vanuatu .play-footer > span:first-child { + font-size: 9px; + } + .vanuatu .activity { + border-radius: 8px; + } + .vanuatu .activity > header { + padding: 6px 10px; + } + .vanuatu .event-list { + padding: 9px 12px; + height: 200px; + } + .vanuatu .help-dialog { + padding: 20px 17px; + } + .vanuatu .help-dialog h2 { + font-size: 22px; + } + .vanuatu .character-detail { + gap: 15px; + } + .vanuatu .character-detail img { + width: 85px; + height: 120px; + } + .vanuatu .island-detail { + gap: 9px; + } + .vanuatu .bonus-switch { + font-size: 10px; + } + .vanuatu .move-option { + font-size: 11px; + padding: 7px 9px; + } + .vanuatu .move-option .icon { + width: 21px; + height: 21px; + } + .preview-controls { + flex-wrap: wrap; + gap: 5px; + font-size: 10px; + } +} +@media (prefers-reduced-motion: reduce) { + .vanuatu * { + transition: none !important; + scroll-behavior: auto !important; + } +} +.vanuatu .sea-board:before { + opacity: 0.21; + background-size: 520px; +} +.vanuatu .archipelago { + overflow: hidden; +} +.vanuatu .map-scroll { + padding-bottom: 145px; +} +.vanuatu .sea-board:has(.character-tray) .map-scroll { + padding-bottom: 158px; +} +.vanuatu .map-cell image { + pointer-events: none; +} +.vanuatu .map-cell:not(.legal) .cell-surface { + stroke: #e2fff830; +} +@media (max-width: 700px) { + .vanuatu .map-scroll { + padding-bottom: 125px; + } + .vanuatu .sea-board:has(.character-tray) .map-scroll { + padding-bottom: 166px; + } + .vanuatu .archipelago { + min-height: 200px; + } + .vanuatu .character-choice { + min-height: 84px; + } +} +.vanuatu-tutorial { + padding: 12px 16px 0; + background: #f2f0e4; + color: #244e53; + font: 14px/1.5 system-ui; +} +.vanuatu-tutorial .bgs-tutorial-guide { + background: #fcf8eb !important; + border-color: #c9d3b6 !important; + color: #244e53 !important; + border-radius: 9px !important; +} +.vanuatu-tutorial button { + background: #edf0de !important; + color: #244e53 !important; + border-color: #cad2b8 !important; +} +.vanuatu-tutorial .bgs-tutorial-body { + font-size: 13px; +} diff --git a/viewer/tutorial-mount.js b/viewer/tutorial-mount.js new file mode 100644 index 0000000..08e001c --- /dev/null +++ b/viewer/tutorial-mount.js @@ -0,0 +1,50 @@ +import { createTutorial } from "@boardgamers/protocol/tutorial"; +import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom"; +import { stripSecret } from "../engine/index.js"; +import { chapters } from "./tutorials.js"; +import { mountGame } from "./ui.js"; +export async function mountLesson(target, options) { + const config = chapters[options.chapter]; + if (!config) throw Error("Unknown chapter"); + let storage; + try { + storage = window.localStorage; + } catch {} + const tutorial = await createTutorial({ + ...config, + storage, + onProgress: options.onProgress, + }); + const guide = document.createElement("div"); + guide.className = "vanuatu-tutorial"; + target.append(guide); + const ui = mountGame(target, { + language: "en", + onMove: async (m) => { + const accepted = await tutorial.play(m); + if (!accepted) + throw Error( + tutorial.snapshot.error || + tutorial.snapshot.feedback || + "Try the action described in this step.", + ); + }, + }); + ui.setPlayer(0); + const off = tutorial.subscribe((snapshot) => { + ui.render(stripSecret(snapshot.state, 0)); + ui.setEnabled( + !snapshot.busy && !snapshot.completed && !snapshot.canContinue, + ); + }); + const unmount = mountTutorialGuide(guide, tutorial, { + nextChapter: options.nextChapter, + }); + return () => { + off(); + unmount(); + tutorial.destroy(); + ui.destroy(); + guide.remove(); + }; +} diff --git a/viewer/tutorials.js b/viewer/tutorials.js new file mode 100644 index 0000000..73c1a4b --- /dev/null +++ b/viewer/tutorials.js @@ -0,0 +1,180 @@ +import * as E from "../engine/index.js"; +export const chapterMetadata = [ + { + id: "planning", + version: 1, + title: "Plan your day", + description: "Place five markers and understand action majorities.", + }, + { + id: "fishing", + version: 1, + title: "From sea to market", + description: "Sail, fish and sell your catch beside your hut.", + }, + { + id: "islands", + version: 1, + title: "An island economy", + description: "Build a hut, draw in the sand and welcome a tourist.", + }, +]; +function prepared(phase = "actions") { + const s = E.init(3, [], {}, "vanuatu-lesson"); + s.actor = 0; + s.first = 0; + s.phase = phase; + s.players.forEach((p, i) => { + p.name = ["You", "Maya", "Noa"][i]; + p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0])); + p.character = null; + p.boat = "1,1"; + }); + s.board = { + "0,0": E.tileState("efate"), + "1,0": E.tileState("startFish"), + "0,1": E.tileState("startWreck"), + "1,1": E.tileState("startBoat"), + }; + s.tourists = 2; + return s; +} +function play(s, m) { + let next = E.move(s, m, 0), + n = 0; + while (!next.finished && next.actor !== 0 && n++ < 100) + next = E.moveAI(next, next.actor); + return next; +} +const planCount = (s) => + Object.values(s.players[0].markers).reduce((a, b) => a + b, 0); +const only = (action) => (s, m) => + m.action === action ? undefined : `Choose ${action} for this step.`; +export const chapters = { + planning: { + game: "vanuatu", + id: "planning", + version: 1, + initialState: () => { + const s = prepared("plan"); + s.characters = []; + s.options.characters = false; + return s; + }, + move: play, + steps: [ + { + id: "first-two", + title: "Plan two actions", + text: "Place your first two markers. Sailing opens up fishing and island actions; extra markers help win a majority.", + complete: (s) => planCount(s) >= 2, + validateMove: (s, m) => + m.type === "plan" ? undefined : "Place the two markers first.", + }, + { + id: "next-two", + title: "Two more markers", + text: "The others have placed their markers. Reinforce an action or plan something new. An action can be performed once, however many markers you place there.", + complete: (s) => planCount(s) >= 4, + }, + { + id: "last", + title: "One last marker", + text: "Place your fifth marker. During the action phase, ties are broken in order from the first player.", + complete: (s) => s.phase === "actions", + }, + ], + completion: { + title: "Your plan is ready", + text: "Choose an action where you have the most markers, then retrieve your whole stack. Without a majority, retrieve one stack without acting.", + }, + }, + fishing: { + game: "vanuatu", + id: "fishing", + version: 1, + initialState: () => { + const s = prepared(); + s.board["0,0"].huts = [0]; + s.players[0].hutsLeft = 7; + s.players[0].markers.sail = 1; + s.players[0].markers.fish = 1; + s.players[0].markers.sell = 1; + return s; + }, + move: play, + steps: [ + { + id: "sail", + title: "Find a fishing ground", + text: "Choose Sail and move onto the ocean with 2 fish. Each space costs 1 vatu.", + complete: (s) => s.players[0].boat === "1,0", + validateMove: (s, m) => + m.action === "sail" && m.path.at(-1) === "1,0" + ? undefined + : "Sail to the ocean with 2 fish.", + }, + { + id: "fish", + title: "Catch the fish", + text: "Choose Fish. The catch has value 2; the fishing ground then falls to 1.", + complete: (s) => s.players[0].fish.includes(2), + validateMove: only("fish"), + }, + { + id: "sell", + title: "Sell your catch", + text: "Your boat is beside your orange hut. Sell the catch: 2 fish × a market price of 3 = 6 vatus.", + complete: (s) => s._history.some((h) => h.move.action === "sell"), + validateMove: only("sell"), + }, + ], + completion: { + title: "Trade keeps you moving", + text: "The fish market falls after a sale and resets next round. Every 10 vatus automatically becomes 5 prosperity.", + }, + }, + islands: { + game: "vanuatu", + id: "islands", + version: 1, + initialState: () => { + const s = prepared(); + s.players[0].character = "builder"; + s.players[0].boat = "1,0"; + for (const a of ["build", "draw", "tourist"]) s.players[0].markers[a] = 1; + return s; + }, + move: play, + steps: [ + { + id: "hut", + title: "Build a beach hut", + text: "Build beside your boat. Use the Builder: your hut costs only 1 vatu instead of 3.", + complete: (s) => s.board["0,0"].huts.includes(0), + validateMove: (s, m) => + m.action === "build" && m.bonus + ? undefined + : "Build a hut with the Builder bonus enabled.", + }, + { + id: "drawing", + title: "Draw in the sand", + text: "A sand drawing earns 3 prosperity. It stays on the island and may help a future Guide.", + complete: (s) => s.board["0,0"].drawings > 0, + validateMove: only("draw"), + }, + { + id: "tourist", + title: "Welcome a visitor", + text: "Transport a tourist to the island. You earn 1 vatu per hut there. At game end, each of your huts earns 2 prosperity per tourist.", + complete: (s) => s.board["0,0"].tourists > 0, + validateMove: only("tourist"), + }, + ], + completion: { + title: "Ready to sail", + text: "Prosperity comes from trade, drawings, characters and endgame scoring. Keep enough vatus to fund the actions you plan.", + }, + }, +}; diff --git a/viewer/ui.js b/viewer/ui.js new file mode 100644 index 0000000..a488a4d --- /dev/null +++ b/viewer/ui.js @@ -0,0 +1,587 @@ +import { + ACTIONS, + CHARACTERS, + TILES, + PRICES, + VALUES, +} from "../engine/catalog.js"; +import { assets } from "./assets.js"; +import { icon, token, esc } from "./art.js"; +import { boardSvg, center } from "./board.js"; +import { translator, characterHelp } from "./labels.js"; +import { mountActivity } from "./activity.js"; +import { rulesHtml } from "./rules.js"; +const total = (a) => a.reduce((a, b) => a + b, 0); +const unique = (a) => [...new Set(a)]; +function coastArrow(cell, edge) { + const a = center(cell), + b = center(edge), + angle = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; + return ``; +} +const symbols = ["●", "◆", "▲", "■", "✦"]; +export function mountGame(target, options = {}) { + const root = document.createElement("div"); + root.className = "vanuatu"; + root.innerHTML = + '
    '; + target.append(root); + const play = root.querySelector(".play"), + dialog = root.querySelector("dialog"), + feedback = root.querySelector(".feedback"); + let s, + player, + enabled = true, + analysis = false, + pending = false, + selected = null, + action = null, + draft = [], + tile = null, + bonus = true, + zoom = false, + lang = + options.language ?? (navigator.language.startsWith("fr") ? "fr" : "en"), + colorBlind = false, + sound = false, + revision, + focusReturn; + let t = translator(lang); + const events = new AbortController(); + const listener = { signal: events.signal }; + const activity = mountActivity(root.querySelector(".activity-root"), { + chat: options.chat, + openPlayer: options.onOpenPlayer, + onBack: () => play.scrollIntoView({ block: "start" }), + language: lang, + }); + activity.setLanguage(lang); + const legal = () => (enabled && !pending ? (s?.legal ?? []) : []); + const working = () => + legal().filter((m) => !["treasure", "beg"].includes(m.type)); + const actMoves = () => + working().filter((m) => m.type === "act" && m.action === action); + const actualTargets = () => + action === "sail" + ? unique(actMoves().map((m) => m.path.at(-1))) + : unique( + actMoves() + .map((m) => m.cell) + .filter(Boolean), + ); + const own = () => s?.players[player]; + const charName = (c) => + esc(CHARACTERS[c]?.[lang === "fr" ? "fr" : "name"] ?? c); + const charHelp = (c) => esc(characterHelp[c]?.[lang === "fr" ? 1 : 0] ?? ""); + function btn(content, attr = "", className = "") { + return ``; + } + const titled = (name, content, attr = "", cls = "") => + btn(content, `title="${esc(name)}" aria-label="${esc(name)}" ${attr}`, cls); + function actionDetail(m) { + if (m.type === "place") return `${t("choose")} ${icon("check")}`; + if (m.type === "character") return charName(m.character); + if (m.type === "plan" || m.type === "neutral") + return m.actions.map((a) => icon(a)).join(""); + if (m.type === "discard") + return `${icon("undo")} ${t("discard")} ${icon(m.action)}`; + if (m.type === "rest") return restContent(m.token); + if (m.type === "governor") return `${icon(m.from)} → ${icon(m.to)}`; + if (m.type === "treasure") + return `${token("explore", total(m.values))} → ${token("coin", total(m.values))}`; + if (m.type === "beg") + return `${token("point", m.amount)} → ${token("coin", m.amount)}`; + if (m.action === "sail") + return `${token("sail", m.path.length)} · ${token("coin", m.bonus ? 0 : m.path.length)}`; + if (m.action === "fish") + return `${token("fish", s.board[own().boat].fish)}${m.bonus ? " + " + token("point", s.board[own().boat].fish) : ""}`; + if (m.action === "explore") + return `${token("explore", s.board[own().boat].treasure)}${m.bonus ? " + " + token("coin", s.board[own().boat].treasure) : ""}`; + if (m.action === "sell") + return `${m.fish.map((n) => token("fish", n)).join("")} → ${token("coin", total(m.fish) * s.market)}`; + if (m.action === "build") + return `${m.hut ? token("build", 1) : ""}${m.dike ? token("dike", 1) : ""} · ${token("coin", (m.hut ? (m.bonus ? 1 : 3) : 0) + (m.dike ? 1 : 0))}${m.dike ? ` ${coastArrow(m.cell, m.dike)}` : ""}`; + if (m.action === "buy") { + let gain = 0; + const ships = s.demands.map((d) => ({ ...d, filled: [...d.filled] })); + for (let n = 0; n < (m.bonus ? 2 : 1); n++) { + const d = ships.find((d) => + d.goods.some((g, i) => g === m.good && !d.filled[i]), + ); + if (!d) continue; + d.filled[d.goods.findIndex((g, i) => g === m.good && !d.filled[i])] = + true; + gain += VALUES[m.good] + (d.filled.every(Boolean) ? 2 : 0); + } + return `${token(m.good, m.bonus ? 2 : 1)} · ${token("coin", PRICES[m.good])} → ${token("point", gain)}`; + } + if (m.action === "draw") + return `${icon("draw")} → ${token("point", m.bonus ? 5 : 3)}`; + if (m.action === "tourist") + return `${icon("tourist")} → ${token("coin", s.board[m.cell].huts.length)}${m.bonus ? " + " + token("point", s.board[m.cell].drawings * 2) : ""}`; + return `${icon(m.action)} ${t(m.action)}`; + } + function moveButton(m, primary = false) { + const idx = (s.legal ?? []).indexOf(m); + return btn( + actionDetail(m), + `data-move="${idx}" ${pending ? "disabled" : ""}`, + primary ? "primary move-option" : "move-option", + ); + } + function restContent(key) { + return key === "first" + ? icon("first") + : key === "both" + ? `${token("coin", 1)} + ${token("point", 1)}` + : token(key, 1); + } + function playerCard(p, i) { + const c = CHARACTERS[p.character]; + return `
    ${btn(`${colorBlind ? symbols[i] + " " : ""}${esc(p.name)}`, `data-bgs-player="${i}"`, "profile")} ${s.first === i ? icon("first", t("first")) : ""}${token("point", p.score)}
    ${token("coin", p.money)}${p.fish.length ? p.fish.map((n) => token("fish", n)).join("") : token("fish", 0)}${p.treasures.length ? p.treasures.map((n) => token("explore", n)).join("") : token("explore", 0)}${token("build", p.hutsLeft)}
    ${c ? `` : ""}${i === player ? `
    ${legal().some((m) => m.type === "treasure") ? btn(`${icon("explore")} → ${icon("coin")}`, `data-free="treasure" title="${t("treasure")}"`) : ""}${legal().some((m) => m.type === "beg") ? btn(`${icon("point")} → ${icon("coin")}`, `data-free="beg" title="${t("beg")}"`) : ""}
    ` : ""}
    `; + } + function dock() { + const planning = ["plan", "neutral"].includes(s.phase) && working().length; + return ``; + } + function tray() { + const moves = working(); + if (s.finished) + return `
    ${s.lost ? t("lost") : t("finished")}${btn(`${icon("point")} ${t("ended")}`, "data-scores", "primary")}
    `; + if (!moves.length) + return `
    ${pending ? t("pending") : `${t("waiting")} ${esc(s.players[s.actor]?.name ?? "")}`}
    `; + if (s.phase === "character") + return `
    ${t("character")}
    ${moves + .filter((m) => m.type === "character") + .map((m) => { + const c = CHARACTERS[m.character]; + return btn( + `${charName(m.character)}${charHelp(m.character)}`, + `data-character-choice="${m.character}"`, + "character-choice", + ); + }) + .join("")}
    `; + if (["plan", "neutral"].includes(s.phase)) { + const prefix = (m) => + m.actions?.slice(0, draft.length).every((x, i) => x === draft[i]); + const complete = moves.find( + (m) => prefix(m) && m.actions.length === draft.length, + ); + const count = moves[0]?.actions?.length ?? 0; + return `
    ${t(s.phase)} ${draft.length}/${count}
    ${Array.from({ length: count }, (_, i) => `${draft[i] ? icon(draft[i]) : icon("marker")}`).join("")}
    ${titled(t("undo"), icon("undo"), `data-undo ${draft.length ? "" : "disabled"}`, "icon-button")}${complete ? btn(`${icon("check")} ${t("confirm")}`, `data-move="${s.legal.indexOf(complete)}"`, "primary") : ""}
    `; + } + if (s.phase === "expand") { + const tileChoices = unique( + moves.filter((m) => m.type === "place").map((m) => m.tile), + ); + if (!tileChoices.includes(tile)) tile = tileChoices[0]; + const m = moves.find( + (m) => m.type === "place" && m.tile === tile && m.cell === selected, + ); + return `
    ${t("expand")}
    ${tileChoices.map((id) => btn(`${TILES[id].type === `, `data-tile="${id}" aria-pressed="${tile === id}"`)).join("")}
    ${m ? moveButton(m, true) : ""}
    `; + } + if (s.phase === "rest") + return `
    ${t("restChoice")}${moves + .filter((m) => m.type === "rest") + .map((m) => moveButton(m, true)) + .join("")}
    `; + let opts = actMoves().sort( + (a, b) => (a.path?.length ?? 0) - (b.path?.length ?? 0), + ); + const selectedAction = !!action; + const hasBonus = opts.some((m) => m.bonus), + hasNormal = opts.some((m) => !m.bonus); + opts = opts.filter((m) => !hasBonus || !hasNormal || m.bonus === bonus); + const targets = actualTargets(); + if (targets.length) + opts = opts.filter((m) => (m.cell ?? m.path?.at(-1)) === selected); + const discard = moves.find( + (m) => m.type === "discard" && m.action === action, + ); + const governor = moves.some((m) => m.type === "governor"); + const pickText = + targets.length && !selected + ? `${icon("sail")} ${lang === "fr" ? "Choisir une case" : "Choose a space"}` + : ""; + return `
    ${selectedAction ? `${icon(action)} ${t(action)}` : t("actions")}
    ${hasBonus && hasNormal ? `` : ""}${pickText}
    ${opts.map((m) => moveButton(m, true)).join("")}${discard ? moveButton(discard) : ""}
    ${governor ? btn(`${icon("marker")} ↔`, `data-governor title="${t("governor")}"`) : ""}${selectedAction ? titled(t("cancel"), icon("close"), "data-cancel", "icon-button") : ""}
    `; + } + function render() { + if (!s) { + play.innerHTML = `

    ${t("connected")}

    `; + return; + } + const focus = play.contains(document.activeElement) + ? document.activeElement?.getAttribute("data-action") + : null; + const scroll = play.querySelector(".map-scroll"); + const sx = scroll?.scrollLeft ?? 0, + sy = scroll?.scrollTop ?? 0; + const trayHtml = tray(); + const targets = + s.phase === "expand" + ? working() + .filter((m) => m.type === "place" && m.tile === tile) + .map((m) => m.cell) + : actualTargets(); + play.innerHTML = `
    ${btn("Vanuatu", "data-boardgame", "wordmark")}Alain Epron · Quined Games
    ${Array.from({ length: 8 }, (_, i) => `${i + 1}`).join("")}
    +
    ${dock()}
    ${icon("fish")} = ${token("coin", s.market)}${token("tourist", s.tourists)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown)}` : ""}
    ${s.demands.map((d, i) => `
    ${i + 1}${d.goods.map((g, j) => `${icon(g)}${d.filled[j] ? icon("check") : ""}`).join("")}${icon("buy")}
    `).join("")}
    ${boardSvg(s, { player, colorBlind, selected, targets, hoverTile: s.phase === "expand" ? tile : null, t })}
    ${titled(zoom ? t("fit") : t("zoom"), icon(zoom ? "eye" : "zoom"), "data-zoom", "icon-button")}
    ${s.upcoming.length && s.phase !== "expand" ? `
    ${s.upcoming.map((id) => `${t(TILES[id].type === `).join("")}
    ` : ""}${trayHtml}
    ${s.players.map(playerCard).join("")}
    ${t("private")}${token("coin", 10)} → ${token("point", 5)}${btn(t("help"), "data-help", "text-button")}
    `; + const newScroll = play.querySelector(".map-scroll"); + if (newScroll) { + newScroll.scrollLeft = sx; + newScroll.scrollTop = sy; + } + if (focus) + play + .querySelector(`[data-action="${focus}"]`) + ?.focus({ preventScroll: true }); + activity.update(s, analysis); + updateUnread(); + } + function updateUnread() { + const n = options.chat?.snapshot.unreadIds.length ?? 0; + const badge = play.querySelector(".unread-badge"); + if (badge) { + badge.textContent = n; + badge.hidden = !n; + } + activity.setUnread(n); + } + const offChat = options.chat?.subscribe(updateUnread); + function showDialog(html) { + focusReturn = document.activeElement; + dialog.innerHTML = `${html}`; + if (!dialog.open) dialog.showModal(); + } + function closeDialog() { + dialog.close(); + focusReturn?.isConnected && focusReturn.focus({ preventScroll: true }); + } + async function send(m) { + if (!m || pending || !enabled) return; + pending = true; + feedback.hidden = true; + render(); + try { + await options.onMove?.(m); + if (sound) { + try { + const context = new AudioContext(); + const oscillator = context.createOscillator(), + gain = context.createGain(); + gain.gain.setValueAtTime(0.025, context.currentTime); + gain.gain.exponentialRampToValueAtTime( + 0.001, + context.currentTime + 0.13, + ); + oscillator.frequency.value = 540; + oscillator.connect(gain).connect(context.destination); + oscillator.start(); + oscillator.stop(context.currentTime + 0.13); + oscillator.onended = () => context.close(); + } catch {} + } + selected = null; + action = null; + draft = []; + closeDialog(); + } catch (e) { + feedback.textContent = e?.message ?? String(e); + feedback.hidden = false; + } finally { + pending = false; + render(); + } + } + function cellClick(id) { + if (s.phase === "expand") { + if (working().some((m) => m.cell === id && m.tile === tile)) + selected = id; + } else if (actualTargets().includes(id)) selected = id; + else { + const b = s.board[id]; + if (b?.type === "island") + showDialog( + `

    ${t("island")}

    ${token("build", `${b.huts.length}/${TILES[b.id].huts}`)} ${token("tourist", `${b.tourists}/${TILES[b.id].tourists}`)} ${token("draw", `${b.drawings}/${TILES[b.id].drawings}`)}

    ${Object.entries( + b.goods, + ) + .map(([g, n]) => token(g, n)) + .join("")}

    `, + ); + } + render(); + } + root.addEventListener( + "click", + (e) => { + const button = e.target.closest("button"); + const cell = e.target.closest("[data-cell]"); + if (cell) { + cellClick(cell.dataset.cell); + return; + } + if (!button || button.disabled) return; + const d = button.dataset; + if ("move" in d) { + send(s.legal[Number(d.move)]); + return; + } + if ("bgsPlayer" in d) { + options.onOpenPlayer?.(Number(d.bgsPlayer)); + return; + } + if ("boardgame" in d) { + options.onOpenBoardgame?.(); + return; + } + if ("close" in d) { + closeDialog(); + return; + } + if ("action" in d) { + if (["plan", "neutral"].includes(s.phase)) { + draft.push(d.action); + if (s.phase === "neutral") + draft.sort((a, b) => ACTIONS.indexOf(a) - ACTIONS.indexOf(b)); + } else { + action = d.action; + selected = null; + const targets = actualTargets(); + if (targets.length === 1) selected = targets[0]; + } + render(); + return; + } + if ("undo" in d) { + draft.pop(); + render(); + return; + } + if ("tile" in d) { + tile = d.tile; + selected = null; + render(); + return; + } + if ("cancel" in d) { + action = null; + selected = null; + render(); + return; + } + if ("zoom" in d) { + zoom = !zoom; + render(); + return; + } + if ("characterChoice" in d) { + const m = s.legal.find( + (m) => m.type === "character" && m.character === d.characterChoice, + ); + showDialog( + `

    ${charName(m.character)}

    ${charHelp(m.character)}

    ${moveButton(m, true)}
    `, + ); + return; + } + if ("character" in d) { + showDialog( + `

    ${charName(d.character)}

    ${charHelp(d.character)}

    ${lang === "fr" ? "Une fois par tour." : "Once per round."}
    `, + ); + return; + } + if ("free" in d) { + showDialog( + `

    ${t(d.free)}

    ${legal() + .filter((m) => m.type === d.free) + .map((m) => moveButton(m, true)) + .join("")}
    `, + ); + return; + } + if ("governor" in d) { + showDialog( + `

    ${t("governor")}

    ${working() + .filter((m) => m.type === "governor") + .map((m) => moveButton(m, true)) + .join("")}
    `, + ); + return; + } + if ("activity" in d) { + activity.open(d.activity); + return; + } + if ("fullscreen" in d) { + if (document.fullscreenElement) document.exitFullscreen?.(); + else root.requestFullscreen?.().catch(() => {}); + return; + } + if ("help" in d) { + showDialog( + `

    ${t("help")}

    ${rulesHtml(lang)}

    ${t("credit")}

    Alain Epron · Quined Games
    Art: Konstantin Vohwinkel · Rafaël Theunis

    ${t("source")}

    `, + ); + return; + } + if ("scores" in d) { + showDialog( + `

    ${t("ended")}

    ${[...s.players] + .map((p, i) => ({ ...p, i })) + .sort((a, b) => b.score - a.score) + .map( + (p) => + `
    ${esc(p.name)}${token("point", p.score)}${ + p.final + ? `${Object.entries(p.final) + .filter(([, v]) => v !== 0) + .map(([k, v]) => + token( + { + wealth: "coin", + treasure: "explore", + tourists: "tourist", + first: "first", + water: "water", + }[k], + v, + ), + ) + .join(" · ")}` + : "" + }
    `, + ) + .join("")}
    `, + ); + } + }, + listener, + ); + root.addEventListener( + "change", + (e) => { + if (e.target.matches("[data-bonus]")) { + bonus = e.target.checked; + render(); + } + if (e.target.matches("[data-pref]")) { + const key = e.target.dataset.pref, + value = e.target.checked; + if (key === "colorBlind") colorBlind = value; + if (key === "sound") sound = value; + options.onPreference?.(key, value); + render(); + } + if (e.target.matches("[data-language]")) { + lang = e.target.value; + t = translator(lang); + closeDialog(); + activity.setLanguage(lang); + render(); + } + }, + listener, + ); + root.addEventListener( + "keydown", + (e) => { + const cell = e.target.closest("[data-cell]"); + if (cell && ["Enter", " "].includes(e.key)) { + e.preventDefault(); + cellClick(cell.dataset.cell); + } + }, + listener, + ); + dialog.addEventListener( + "click", + (e) => { + if (e.target === dialog && e.offsetX >= 0 && e.offsetY >= 0) { + const r = dialog.getBoundingClientRect(); + if ( + e.clientX < r.left || + e.clientX > r.right || + e.clientY < r.top || + e.clientY > r.bottom + ) + closeDialog(); + } + }, + listener, + ); + return { + root, + render(state) { + const next = `${state.historyLength ?? state.round + ":" + state.phase}:${player}`; + if (next !== revision) { + selected = null; + action = null; + draft = []; + revision = next; + } + s = state; + render(); + }, + setPlayer(p) { + if (player !== p) { + player = p; + draft = []; + action = null; + selected = null; + } + render(); + }, + setEnabled(v) { + enabled = v; + render(); + }, + setPreferences(p) { + analysis = p.analysis === true; + colorBlind = p.colorBlind === true; + sound = p.sound === true; + if (["en", "fr"].includes(p.language)) { + lang = p.language; + t = translator(lang); + } + render(); + }, + destroy() { + events.abort(); + offChat?.(); + activity.destroy(); + root.remove(); + }, + }; +}