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 = `${p}
${fr ? "Règles originales" : "Original rulebook"} ↗ · ${fr ? "Règles à deux" : "Two-player rules"} ↗
`; +} 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 `${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 = `${Object.entries( + b.goods, + ) + .map(([g, n]) => token(g, n)) + .join("")}
${charHelp(m.character)}
${moveButton(m, true)}${charHelp(d.character)}
${lang === "fr" ? "Une fois par tour." : "Once per round."}Alain Epron · Quined Games
Art: Konstantin Vohwinkel · Rafaël Theunis