diff --git a/engine/index.js b/engine/index.js index a3371f2..d466d69 100644 --- a/engine/index.js +++ b/engine/index.js @@ -1,3 +1,4 @@ +import { markerBlockers } from "./marker-blockers.js"; import { sha256 } from "@noble/hashes/sha2.js"; import { ACTIONS, @@ -821,7 +822,16 @@ function finish(s) { } function execute(s, m, p) { const a = s.players[p]; - say(s, m.type === "act" ? "action" : m.type, { p, ...m }); + say(s, m.type === "act" ? "action" : m.type, { + p, + ...m, + ...(m.type === "discard" + ? { + blockers: markerBlockers(s, p, m.action), + markers: a.markers[m.action], + } + : {}), + }); switch (m.type) { case "treasure": takeFrom(a.treasures, m.values); @@ -1051,6 +1061,43 @@ function chooseAI(s, p) { const moves = availableMoves(s, p); check(moves.length, "No legal bot move"); const a = s.players[p]; + function planValue(actions) { + const markers = { ...a.markers }; + for (const action of actions) markers[action]++; + const planned = { + ...s, + players: s.players.map((player, q) => + q === p ? { ...player, markers } : player, + ), + }; + return ACTIONS.reduce((total, action) => { + if (!markers[action]) return total; + const useful = + { + fish: a.fish.length ? 2 : 5, + sell: a.fish.length ? 6 : 3, + explore: 6, + build: a.hutsLeft > 5 ? 6 : 3, + buy: 5, + draw: 5, + tourist: 4, + sail: 3, + rest: 1, + }[action] + (CHARACTERS[a.character]?.action === action ? 2 : 0); + // Value each action once, including both markers in this placement. + // Existing majorities gain nothing from extra markers. A blocked stack + // may become available later, but neutral markers never leave the board. + const neutralBlocked = markerBlockers(planned, p, action).some( + (blocker) => blocker.neutral, + ); + const availability = majority(planned, p, action) + ? 1 + : neutralBlocked + ? 0 + : 0.4; + return total + useful * availability; + }, 0); + } function value(m) { if (m.type === "treasure") return a.money < 3 ? sum(m.values) * 0.5 - 1 : -30; @@ -1087,36 +1134,7 @@ function chooseAI(s, p) { ? 3 : 0) ); - if (m.type === "plan") { - return m.actions.reduce( - (v, action, i) => - v + - value({ type: "plan-single", action }) - - (i && action === m.actions[0] ? 0.1 : 0), - 0, - ); - } - if (m.type === "plan-single") { - const n = a.markers[m.action]; - const need = - Math.max(0, ...s.players.map((x) => x.markers[m.action])) + 1; - const useful = { - fish: a.fish.length ? 2 : 5, - sell: a.fish.length ? 6 : 3, - explore: 6, - build: a.hutsLeft > 5 ? 6 : 3, - buy: 5, - draw: 5, - tourist: 4, - sail: 3, - rest: 1, - }[m.action]; - return ( - useful - - (n >= need ? 8 : n ? 0 : 1) + - (CHARACTERS[a.character]?.action === m.action ? 2 : 0) - ); - } + if (m.type === "plan") return planValue(m.actions); if (m.type === "discard") return -15; if (m.type === "governor") return -10; if (m.type === "rest") diff --git a/engine/marker-blockers.js b/engine/marker-blockers.js new file mode 100644 index 0000000..9a47fc1 --- /dev/null +++ b/engine/marker-blockers.js @@ -0,0 +1,21 @@ +import { CHARACTERS } from "./catalog.js"; +export function markerBlockers(s, p, action) { + const count = s.players[p].markers[action]; + if (!count) return []; + const rank = (q) => (q - s.first + s.players.length) % s.players.length; + const blockers = s.players.flatMap((player, q) => { + const n = player.markers[action]; + return q !== p && (n > count || (n === count && rank(q) < rank(p))) + ? [{ p: q, count: n, tied: n === count }] + : []; + }); + if (s.players.length === 2) { + const n = s.neutral[action]; + const tieAllowed = + CHARACTERS[s.players[p].character]?.action === action || + s.players[p].governorAction === action; + if (n > count || (n === count && !tieAllowed)) + blockers.push({ count: n, neutral: true, tied: n === count }); + } + return blockers; +} diff --git a/package.json b/package.json index 7506ae3..97b4e67 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/vanuatu", - "version": "0.1.2", + "version": "0.1.4", "private": true, "type": "module", "main": "dist/engine.js", @@ -14,7 +14,7 @@ "test:browser": "node test/browser.mjs", "check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser", "test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs", - "test:tutorial:browser": "node test/tutorial-browser.mjs" + "test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs" }, "dependencies": { "@boardgamers/protocol": "0.6.1", diff --git a/test/ai.test.js b/test/ai.test.js new file mode 100644 index 0000000..78a6b83 --- /dev/null +++ b/test/ai.test.js @@ -0,0 +1,84 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as E from "../engine/index.js"; + +function planning(players = 3) { + const s = E.init(players, [], {}, "bot-planning"); + s.actor = 0; + s.first = 0; + s.phase = "plan"; + s.planningPass = 0; + s.board = { + "0,0": E.tileState("efate"), + "1,0": E.tileState("startWreck"), + "0,1": E.tileState("startFish"), + "1,1": E.tileState("startBoat"), + }; + s.tourists = 2; + for (const player of s.players) { + player.boat = "1,0"; + player.character = null; + } + return s; +} + +test("a two-marker bot placement opens two useful actions instead of overstacking", () => { + const s = planning(); + s.players[0].character = "builder"; + const next = E.moveAI(s, 0); + const { actions } = next._history[0].move; + assert.equal(new Set(actions).size, 2); + assert.ok(actions.includes("build")); + assert.equal( + Object.values(s.players[0].markers).reduce((a, b) => a + b), + 0, + ); +}); + +function contested(players = 3) { + const s = planning(players); + s.planningPass = 2; + s.players[0].character = "fisherman"; + s.players[0].money = 0; + Object.assign(s.players[0].markers, { fish: 1, draw: 1, sail: 2 }); + s.board["1,0"].treasure = 0; + s.board["0,0"].goods = {}; + s.board["0,0"].huts = []; + s.tourists = 0; + return s; +} + +test("the bot reinforces a tied fishing stack only when turn order requires it", () => { + for (const first of [0, 1]) { + const s = contested(); + s.first = first; + s.players[1].markers.fish = 1; + const next = E.moveAI(s, 0); + assert.deepEqual(next._history[0].move.actions, [ + first === 1 ? "fish" : "rest", + ]); + } +}); + +test("the bot accounts for persistent neutral stacks and matching character ties", () => { + for (const character of ["fisherman", null]) { + const s = contested(2); + s.players[0].character = character; + s.neutral.fish = 2; + const next = E.moveAI(s, 0); + assert.deepEqual(next._history[0].move.actions, [ + character ? "fish" : "rest", + ]); + } +}); + +test("bots complete games with 2–5 players, including Rising Waters", () => { + for (const count of [2, 3, 4, 5]) + for (const expansions of [[], ["rising-waters"]]) { + let s = E.init(count, expansions, {}, "bot-full-game"); + let turns = 0; + while (!s.finished && turns++ < 1000) s = E.moveAI(s, s.actor); + assert.equal(s.finished, true, `${count} players / ${expansions}`); + assert.ok(s.players.every((p) => Number.isFinite(p.score))); + } +}); diff --git a/test/browser.mjs b/test/browser.mjs index f082f82..7c85071 100644 --- a/test/browser.mjs +++ b/test/browser.mjs @@ -44,6 +44,97 @@ const page = await browser.newPage({ page.on("pageerror", (e) => errors.push(e.message)); await page.goto(base + "/?new&hotseat"); await page.waitForSelector("[data-character-choice]"); +// Every supported locale must render translated action tooltips, not English fallbacks. +const tooltipSource = "Sail 1–3 ocean spaces, paying 1 vatu per space."; +for (const locale of [ + "en", + "fr", + "de", + "da", + "el", + "hi", + "it", + "ko", + "nl", + "pl", + "pt-BR", + "ro", + "ru", + "vi", + "zh-TW", +]) { + const catalog = JSON.parse( + await readFile( + new URL(`../viewer/localization/${locale}.json`, import.meta.url), + "utf8", + ), + ); + await page.goto(`${base}/?new&hotseat&locale=${locale}`); + await page.waitForFunction( + (expected) => + document.querySelector('[data-action="sail"]')?.title === expected, + catalog[tooltipSource], + ); + const titles = await page + .locator(".action-dock [data-action]") + .evaluateAll((buttons) => buttons.map((button) => button.title)); + assert.equal(titles.length, 9); + for (const title of titles) { + assert.ok( + Object.values(catalog).includes(title), + `${locale}: tooltip must come from its catalogue`, + ); + if (locale !== "en") + assert.ok( + !Object.hasOwn(catalog, title), + `${locale}: English tooltip fallback`, + ); + } +} +await page.goto(base + "/?new&hotseat"); +await page.waitForSelector("[data-character-choice]"); +// Action descriptions remain available even before an action can be selected. +for (const action of E.ACTIONS) { + assert.ok( + (await page.locator(`[data-action="${action}"]`).getAttribute("title")) + .length > 30, + ); +} +// A swipe over the board must continue scrolling the mobile page at its boundary. +await page.setViewportSize({ width: 390, height: 600 }); +await page.evaluate(() => scrollTo(0, 0)); +const boardScroll = page.locator(".map-scroll"); +await boardScroll.scrollIntoViewIfNeeded(); +await boardScroll.evaluate((el) => { + el.scrollTop = el.scrollHeight; +}); +const boardRect = await boardScroll.boundingBox(); +const beforeSwipe = await page.evaluate(() => scrollY); +const cdp = await page.context().newCDPSession(page); +await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true }); +const touchX = Math.round(boardRect.x + boardRect.width / 2); +const touchY = Math.round( + Math.max(150, Math.min(350, boardRect.y + boardRect.height / 2)), +); +await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: [{ x: touchX, y: touchY }], +}); +for (let dy = 20; dy <= 140; dy += 20) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: touchX, y: touchY - dy }], + }); + await page.waitForTimeout(30); +} +await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], +}); +await page.waitForFunction((before) => scrollY > before + 20, beforeSwipe); +await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }); +await cdp.detach(); +await page.evaluate(() => scrollTo(0, 0)); // The overview remains reachable above the taller character-selection tray. for (const width of [390, 1440]) { await page.setViewportSize({ width, height: 1000 }); @@ -218,7 +309,13 @@ for (const width of [1440, 390]) { assert.ok( await page .locator(".board-highlights") - .evaluate((el) => el === el.parentElement.lastElementChild), + .evaluate((el) => + [...el.parentElement.querySelectorAll(".map-cell")].every( + (cell) => + cell.compareDocumentPosition(el) & + Node.DOCUMENT_POSITION_FOLLOWING, + ), + ), ); assert.equal( await page.locator(".turn-tray .primary[data-move]").count(), @@ -260,9 +357,16 @@ for (const width of [1440, 390]) { /Not enough vatus/, ); assert.match( - await page.locator(".turn-tray [data-move]").innerText(), + await page.locator(".turn-tray [data-move]").getAttribute("aria-label"), /Retrieve without acting/, ); + await page.locator(".turn-tray .retrieve-warning").click(); + assert.equal( + await page.locator("dialog[open] [data-confirmed-retrieval]").count(), + 1, + ); + assert.match(await page.locator("dialog p").innerText(), /another action/); + await page.locator("dialog [data-close]").last().click(); await page.screenshot({ path: `.local/qa/unaffordable-build-${width}.png`, fullPage: true, @@ -422,9 +526,11 @@ for (const width of [1440, 390]) { await page.evaluate(() => JSON.stringify(window.vanuatuDemo.state)), position, ); - await page.locator("[data-help]").first().click(); - await page.locator('[data-pref="colorBlind"]').check(); - await page.locator("[data-close]").click(); + if ( + (await page.locator("[data-color-blind]").getAttribute("aria-pressed")) !== + "true" + ) + await page.locator("[data-color-blind]").click(); assert.ok(await page.locator(".color-symbol").count()); assert.deepEqual( await page.locator('[data-cell="0,0"] .resource-symbol').allTextContents(), @@ -526,7 +632,11 @@ assert.equal( 0, ); await page.locator("[data-help]").first().click(); -assert.equal(await page.locator('[data-pref="colorBlind"]').isChecked(), true); +assert.equal(await page.locator('[data-pref="colorBlind"]').count(), 0); +assert.equal( + await page.locator("[data-color-blind]").getAttribute("aria-pressed"), + "true", +); await page.evaluate(() => emitter.receive("preferences", { analysis: true, @@ -534,10 +644,15 @@ await page.evaluate(() => sound: true, }), ); -assert.equal(await page.locator('[data-pref="colorBlind"]').isChecked(), false); +assert.equal( + await page.locator("[data-color-blind]").getAttribute("aria-pressed"), + "false", +); assert.equal(await page.locator('[data-pref="sound"]').isChecked(), true); assert.equal(await page.locator(".resource-symbol").count(), 0); -await page.locator('[data-pref="colorBlind"]').check(); +await page.locator("[data-close]").click(); +await page.locator("[data-color-blind]").click(); +await page.locator("[data-help]").first().click(); await page.locator('[data-pref="sound"]').uncheck(); assert.deepEqual( await page.evaluate(() => diff --git a/test/marker-blockers.test.js b/test/marker-blockers.test.js new file mode 100644 index 0000000..797932d --- /dev/null +++ b/test/marker-blockers.test.js @@ -0,0 +1,73 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as E from "../engine/index.js"; +import { markerBlockers } from "../engine/marker-blockers.js"; +import { CHARACTERS } from "../engine/catalog.js"; +test("blocker explanations agree with majority including neutral and character ties", () => { + for (const n of [2, 3, 5]) { + const s = E.init(n, [], {}, "blockers"); + for (let first = 0; first < n; first++) + for (const character of [null, ...Object.keys(CHARACTERS)]) { + s.first = first; + s.players[0].character = character; + for (const action of E.ACTIONS) + for (const ours of [1, 2, 3]) + for (const theirs of [0, 1, 2, 3]) { + s.players.forEach( + (p, i) => (p.markers[action] = i === 0 ? ours : theirs), + ); + s.neutral[action] = theirs; + assert.equal( + markerBlockers(s, 0, action).length === 0, + E.majority(s, 0, action), + ); + } + } + } +}); +test("discard log preserves blockers and counts before markers disappear", () => { + const s = E.init(3, [], {}, "log"); + s.phase = "actions"; + s.first = 0; + s.actor = 1; + s.players.forEach((p) => { + p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0])); + p.character = null; + }); + s.players[0].markers.fish = 2; + s.players[1].markers.fish = 1; + s.players[1].markers.sail = 1; + s.players[2].markers.sail = 2; + const next = E.move(s, { type: "discard", action: "fish" }, 1); + const event = next.events.findLast( + (e) => e.type === "discard" && e.p === 1 && e.action === "fish", + ); + assert.equal(event.markers, 1); + assert.deepEqual(event.blockers, [{ p: 0, count: 2, tied: false }]); + assert.equal(next.players[1].markers.fish, 0); +}); + +test("entering a fully blocked turn preserves the choice between stacks", () => { + const s = E.init(3, [], {}, "blocked-choice"); + s.phase = "actions"; + s.first = 0; + s.actor = 0; + s.players.forEach((p) => { + p.markers = Object.fromEntries(E.ACTIONS.map((a) => [a, 0])); + p.character = null; + p.score = 0; + p.treasures = []; + }); + Object.assign(s.players[0].markers, { build: 1, fish: 2, sail: 2 }); + s.players[0].money = 0; + Object.assign(s.players[1].markers, { fish: 1, sail: 1 }); + s.players[2].markers.rest = 1; + const next = E.move(s, { type: "discard", action: "build" }, 0); + assert.equal(next.actor, 1); + assert.equal(next.players[1].markers.fish, 1); + assert.equal(next.players[1].markers.sail, 1); + assert.deepEqual(E.availableMoves(next, 1), [ + { type: "discard", action: "sail" }, + { type: "discard", action: "fish" }, + ]); +}); diff --git a/test/tutorial-browser.mjs b/test/tutorial-browser.mjs index 182b6da..7f364b4 100644 --- a/test/tutorial-browser.mjs +++ b/test/tutorial-browser.mjs @@ -50,7 +50,7 @@ try { }, }); }); - await page.waitForFunction(() => window.progress?.total === 9); + await page.waitForFunction(() => window.progress?.total === 10); const seen = new Set(); for (let i = 0; i < 70; i++) { const progress = await page.evaluate(() => window.progress); @@ -60,6 +60,10 @@ try { '.bgs-tutorial-playback button[title="Continue"]', ); if ((await next.count()) && (await next.isEnabled())) await next.click(); + else if (await page.locator("dialog[open] [data-move]").count()) + await page.locator("dialog[open] [data-move]").first().click(); + else if (await page.locator(".character-choice").count()) + await page.locator(".character-choice").first().click(); else { const move = page .locator(".turn-tray [data-move]:not(:disabled)") @@ -76,7 +80,7 @@ try { await page.waitForTimeout(40); } assert.equal(await page.evaluate(() => window.progress.completed), true); - assert.equal(seen.size, 10); + assert.equal(seen.size, 11); assert.equal( await page.evaluate( () => document.documentElement.scrollWidth <= innerWidth, @@ -168,6 +172,8 @@ try { await launch(); assert.equal(await page.locator(".fish-price b").innerText(), "3"); for (const action of ["sail", "fish", "sell"]) { + const next = page.locator(".bgs-tutorial-playback button").nth(3); + if (await next.isEnabled()) await next.click(); await page.locator(`[data-action="${action}"]`).click(); if (action === "sail") await page.locator('.map-cell[data-cell="1,0"]').click(); @@ -216,6 +222,11 @@ try { removeItem: (key) => saved.delete(key), }, }); + await lesson.play( + availableMoves(lesson.snapshot.state, 0).find( + (m) => m.type === "character" && m.character === "builder", + ), + ); await lesson.continue(); for (const actions of [["sail", "buy"], ["fish", "draw"], ["build"]]) { const move = availableMoves(lesson.snapshot.state, 0).find( @@ -275,7 +286,7 @@ try { ); await page.close(); console.log( - "Nine tutorial steps, completion controls, mobile/desktop layout, French/Dutch locale forwarding, fishing price and restored progress, and white-resource export passed.", + "Ten planning steps, completion controls, mobile/desktop layout, French/Dutch locale forwarding, fishing price and restored progress, and white-resource export passed.", ); } finally { await browser.close(); diff --git a/test/tutorial-walkthrough-browser.mjs b/test/tutorial-walkthrough-browser.mjs new file mode 100644 index 0000000..b823d32 --- /dev/null +++ b/test/tutorial-walkthrough-browser.mjs @@ -0,0 +1,125 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFile, mkdir } from "node:fs/promises"; +import { chromium } from "playwright"; +import { createTutorial } from "@boardgamers/protocol/tutorial"; +import { chapters, chapterMetadata } from "../viewer/tutorials.js"; +import { availableMoves, stripSecret } from "../engine/index.js"; +const server = createServer(async (req, res) => { + try { + if (req.url === "/") { + res.setHeader("Content-Type", "text/html"); + res.end( + '
', + ); + } else { + res.setHeader( + "Content-Type", + req.url.endsWith(".css") ? "text/css" : "text/javascript", + ); + res.end(await readFile(new URL("../dist" + req.url, import.meta.url))); + } + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((r) => server.listen(0, "127.0.0.1", r)); +const browser = await chromium.launch(); +await mkdir(".local/qa", { recursive: true }); +try { + for (const width of [390, 1440]) + for (const { id } of chapterMetadata) { + const chapter = chapters[id]; + const lesson = await createTutorial(chapter); + const p = await browser.newPage({ viewport: { width, height: 1000 } }); + p.setDefaultTimeout(5000); + const errors = []; + p.on("pageerror", (e) => errors.push(e.message)); + await p.goto(`http://127.0.0.1:${server.address().port}/`); + await p.evaluate(async (id) => { + window.progress = null; + await window.vanuatu.launchTutorial("#game", { + chapter: id, + locale: "en", + onProgress: (v) => (window.progress = v), + }); + }, id); + let guard = 0; + while (!lesson.snapshot.completed && guard++ < 45) { + const snap = lesson.snapshot; + await p.waitForFunction( + (step) => window.progress?.step === step, + snap.step, + ); + if (snap.canContinue) { + await p + .locator('.bgs-tutorial-playback button[title="Continue"]') + .click(); + await lesson.continue(); + continue; + } + const step = chapter.steps[snap.step]; + const m = availableMoves(snap.state, 0) + .sort((a, b) => (a.path?.length ?? 0) - (b.path?.length ?? 0)) + .find((m) => !step.validateMove?.(snap.state, m)); + assert.ok(m, `${id}/${step.id}`); + const idx = stripSecret(snap.state, 0).legal.findIndex( + (a) => JSON.stringify(a) === JSON.stringify(m), + ); + if (m.type === "character") + await p.locator(`[data-character-choice="${m.character}"]`).click(); + else if (m.type === "plan") + for (const action of m.actions) + await p.locator(`[data-action="${action}"]`).click(); + else if (m.type === "place") { + await p.locator(`[data-tile="${m.tile}"]`).click(); + await p.locator(`.map-cell[data-cell="${m.cell}"]`).click(); + } else if (["act", "discard"].includes(m.type)) { + await p.locator(`[data-action="${m.action}"]`).click(); + const toggle = p.locator("[data-bonus]"); + if (await toggle.count()) await toggle.setChecked(!!m.bonus); + const cell = m.cell ?? m.path?.at(-1); + if (cell) await p.locator(`.map-cell[data-cell="${cell}"]`).click(); + } else if (m.type === "treasure") + await p.locator('[data-free="treasure"]').click(); + else if (m.type === "governor") + await p.locator("[data-governor]").click(); + const root = (await p.locator("dialog[open]").count()) + ? "dialog[open]" + : ".turn-tray"; + await p.locator(`${root} [data-move="${idx}"]`).click(); + if (await p.locator("[data-confirmed-retrieval]").count()) + await p.locator("[data-confirmed-retrieval]").click(); + assert.equal(await lesson.play(m), true, `${id}/${step.id}`); + } + assert.ok(lesson.snapshot.completed, id); + await p.waitForFunction(() => window.progress?.completed); + assert.deepEqual(errors, [], id); + assert.ok( + await p.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + `${id}: overflow`, + ); + await p.screenshot({ path: `.local/qa/lesson-${id}-${width}.png` }); + await p.reload(); + await p.evaluate(async (id) => { + window.progress = null; + await window.vanuatu.launchTutorial("#game", { + chapter: id, + locale: "en", + onProgress: (v) => (window.progress = v), + }); + }, id); + await p.waitForFunction(() => window.progress?.completed); + lesson.destroy(); + await p.close(); + console.log( + `${width}: ${id} completed and restored (${chapter.steps.length} steps)`, + ); + } +} finally { + await browser.close(); + server.close(); +} diff --git a/test/tutorial.test.js b/test/tutorial.test.js index 4ac2529..b449f71 100644 --- a/test/tutorial.test.js +++ b/test/tutorial.test.js @@ -2,7 +2,55 @@ 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, move } from "../engine/index.js"; +import { availableMoves, majority, move } from "../engine/index.js"; + +test("planning opponents spread their markers and release a blocked fishing action", () => { + const chapter = chapters.planning; + for (const choice of availableMoves(chapter.initialState(), 0)) { + let state = chapter.move(chapter.initialState(), choice); + for (const actions of [["sail", "fish"], ["draw", "rest"], ["tourist"]]) + state = chapter.move(state, { type: "plan", actions }); + assert.equal(state.phase, "actions"); + for (const opponent of state.players.slice(1)) { + const stacks = Object.values(opponent.markers).filter(Boolean); + assert.equal( + stacks.reduce((a, b) => a + b, 0), + 5, + ); + assert.ok( + stacks.length >= 3, + `${choice.character}: ${opponent.name} spreads markers`, + ); + assert.equal(Math.max(...stacks), 2); + } + assert.equal(state.players[1].markers.fish, 2); + assert.equal(majority(state, 0, "fish"), false); + state = chapter.move( + state, + availableMoves(state, 0).find( + (m) => + m.action === "sail" && m.path.length === 1 && m.path[0] === "1,0", + ), + ); + assert.equal(state.players[1].markers.fish, 0); + assert.equal(majority(state, 0, "fish"), true); + const fish = availableMoves(state, 0).find((m) => m.action === "fish"); + assert.ok(fish, `${choice.character}: the player can fish after Maya`); + state = chapter.move(state, fish); + assert.deepEqual(state.players[0].fish, [1]); + let turns = 0; + while (state.round === 1 && turns++ < 15) { + const legal = availableMoves(state, 0); + const next = + legal.find((m) => m.type === "act") ?? + legal.find((m) => m.type === "rest" || m.type === "discard"); + assert.ok(next, `${choice.character}: the round can continue`); + state = chapter.move(state, next); + } + assert.equal(state.round, 2, `${choice.character}: the round finishes`); + } +}); + for (const [id, chapter] of Object.entries(chapters)) test(`tutorial ${id} is completable with real engine moves`, async () => { const lesson = await createTutorial(chapter); @@ -36,6 +84,7 @@ test("the fishing lesson shows the sale's lower price before the next round rese }; const lesson = await createTutorial(options); for (const action of ["sail", "fish", "sell"]) { + while (lesson.snapshot.canContinue) await lesson.continue(); const state = lesson.snapshot.state; const selected = availableMoves(state, 0).find( (m) => @@ -68,3 +117,71 @@ test("the fishing lesson shows the sale's lower price before the next round rese assert.equal(resumed.snapshot.state.round, 1); resumed.destroy(); }); + +test("water lesson demonstrates combined construction, the countdown and an island sinking", async () => { + const lesson = await createTutorial(chapters["rising-waters"]); + const seen = new Set(); + while (!lesson.snapshot.completed) { + const { state, step, canContinue } = lesson.snapshot; + const current = chapters["rising-waters"].steps[step]; + seen.add(current.id); + if (current.id === "coasts") { + assert.equal(state.players[0].money, 0); + assert.deepEqual(state.board["0,0"].dikes, ["0,1", "1,0"]); + assert.deepEqual(state.board["0,0"].huts, [0]); + assert.equal(state.waterCountdown, 2); + } + if (current.id === "tourist") assert.equal(state.waterCountdown, 1); + if (current.id === "flood") { + assert.equal(state.waterTriggered, true); + assert.equal(state.board["0,0"].water, 4); + assert.equal(state.board["0,0"].submerged, false); + assert.equal(state.board["2,1"].submerged, true); + assert.deepEqual(state.board["2,1"].huts, []); + assert.deepEqual(state.board["2,1"].goods, {}); + assert.equal(state.board["2,1"].tourists, 0); + assert.equal(state.board["2,1"].drawings, 0); + assert.equal(state.round, 4); + } + if (canContinue) await lesson.continue(); + else + await lesson.play( + availableMoves(state, 0).find((m) => !current.validateMove?.(state, m)), + ); + } + assert.equal(seen.size, chapters["rising-waters"].steps.length); + lesson.destroy(); +}); + +test("the export lesson explains both the ordinary reward and ship completion bonus", async () => { + for (const good of ["copra", "beef"]) { + const lesson = await createTutorial(chapters.trade); + let count = 0; + while (!lesson.snapshot.completed && count++ < 12) { + const { state, step, canContinue } = lesson.snapshot; + if (canContinue) { + await lesson.continue(); + continue; + } + const current = chapters.trade.steps[step]; + const selected = availableMoves(state, 0).find( + (m) => + !current.validateMove?.(state, m) && + (m.action !== "buy" || m.good === good), + ); + assert.ok(selected, `${good}/${current.id}`); + assert.equal(await lesson.play(selected), true); + } + assert.equal(lesson.snapshot.completed, true); + const { state, text } = lesson.snapshot; + assert.equal(state.players[0].score, good === "copra" ? 3 : 7); + assert.equal(state.players[0].money, good === "copra" ? 1 : 0); + assert.equal(state.demands[0].filled.every(Boolean), good === "beef"); + assert.equal(state.demands[1].filled.every(Boolean), false); + assert.match( + text, + good === "copra" ? /no completion bonus/ : /7 prosperity/, + ); + lesson.destroy(); + } +}); diff --git a/viewer/activity.js b/viewer/activity.js index 6209de6..f596a9c 100644 --- a/viewer/activity.js +++ b/viewer/activity.js @@ -1,3 +1,7 @@ +import { assets } from "./assets.js"; +import { tilePreviewSvg } from "./board.js"; +import { blockingHtml } from "./blocking.js"; +import { translateText } from "./localization/index.js"; import { mountChat } from "@boardgamers/protocol/chat/dom"; import { icon as renderIcon, token as renderToken, esc } from "./art.js"; import { translator } from "./labels.js"; @@ -115,7 +119,7 @@ export function mountActivity( case "neutral": return `${actor} ${e.actions.map((a) => icon(a)).join("")}${e.type === "neutral" ? ` ●` : ""}`; case "character": - return `${actor} ${esc(CHARACTERS[e.character]?.["name"] ?? e.character)}`; + return `${actor}${p.includes("<") ? p : esc(t(p))}
${esc(t("Original rulebook"))} ↗ · ${esc(t("Two-player rules"))} ↗
`; + const sectionIcons = { + "First player": "first", + [EXTEND_TITLE]: "overview", + "Five markers, up to five actions": "marker", + "Retrieve markers": "undo", + "Be in the right place": "sail", + Trade: "sell", + "Develop the islands": "build", + Rest: "rest", + "Final scoring": "point", + "Rising Waters (expansion only)": "water", + }; + return `${p.includes("<") ? p : esc(t(p))}
${esc(t("Original rulebook"))} ↗ · ${esc(t("Two-player rules"))} ↗
`; } diff --git a/viewer/style.css b/viewer/style.css index ca5af06..c2d1aa3 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -247,13 +247,13 @@ box-shadow: inset 3px 0 #ae793f; } .vanuatu .action-dock .retrieve-only { - background: #eeece1; - box-shadow: inset 3px 0 #8c9890; + background: #fff0d8; + box-shadow: inset 3px 0 #ad5d16; } .vanuatu .retrieve-only-icon .icon { - width: 14px; - height: 14px; - color: #697e74; + width: 17px; + height: 17px; + color: #ad5d16; } .vanuatu .action-dock .chosen { background: #f5d99f; @@ -310,7 +310,7 @@ position: relative; width: 100%; overflow: auto; - overscroll-behavior: contain; + overscroll-behavior: auto; scrollbar-width: thin; min-height: 490px; height: min(69vh, 740px); @@ -991,7 +991,7 @@ padding: 12px 20px; height: 100%; overflow: auto; - overscroll-behavior: contain; + overscroll-behavior: auto; scrollbar-width: thin; list-style: none; } @@ -1047,7 +1047,7 @@ flex: 1; max-height: none; min-height: 0; - overscroll-behavior: contain; + overscroll-behavior: auto; } .vanuatu .chat-panel input { background: #fffdf5; @@ -1249,7 +1249,7 @@ body:has(.vanuatu) { box-shadow: inset 0 3px #ae793f; } .vanuatu .action-dock .retrieve-only { - box-shadow: inset 0 3px #8c9890; + box-shadow: inset 0 3px #ad5d16; } .vanuatu .action-dock .chosen { box-shadow: @@ -1548,3 +1548,80 @@ body:has(.vanuatu) { min-height: 40px; } } + +.vanuatu .expand-help { + flex-basis: 100%; + margin: 4px 0; + font-size: 12px; + line-height: 1.45; +} +.vanuatu .expand-help summary { + cursor: pointer; + padding: 6px 0; +} +.vanuatu .retrieval-help { + flex-basis: 100%; + margin: 4px 0; + font-size: 12px; + line-height: 1.5; +} +.vanuatu .event-list .round-divider { + margin-top: 12px; + padding: 8px 0; + border-bottom: 1px solid var(--line); + border-top: 1px solid var(--line); +} +.vanuatu .event-character { + width: 32px; + height: 40px; + object-fit: cover; + border-radius: 4px; +} +.vanuatu .event-tile { + width: 82px; + display: inline-flex; +} +.vanuatu .event-tile svg { + width: 100%; + height: 72px; +} +.vanuatu .event-explanation { + flex-basis: 100%; + font-size: 11px; + line-height: 1.4; +} +.vanuatu .event-list li { + flex-wrap: wrap; +} + +.vanuatu .retrieve-warning { + background: #fff0d8; + border: 2px solid #ad5d16; + color: #743d0d; + font-weight: 700; +} +.vanuatu .retrieve-warning:hover:not(:disabled) { + background: #ffe0ac; +} +.vanuatu .retrieval-tray { + border-left: 4px solid #ad5d16; +} +.vanuatu .retrieval-tray .tray-title { + color: #743d0d; +} + +.vanuatu .rest-bonuses { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 8px; +} +.vanuatu .rest-bonuses > span { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 6px 10px; + border: 1px solid var(--line); + border-radius: 999px; + background: #f0eddd; +} diff --git a/viewer/tutorial-copy.js b/viewer/tutorial-copy.js new file mode 100644 index 0000000..aad0897 --- /dev/null +++ b/viewer/tutorial-copy.js @@ -0,0 +1,56 @@ +export const LESSON = { + character: + "Choose a character. Its bonus can be used once this round. Next round, choose a new character before returning this one.", + fishingStart: + "Your markers are already placed for this route: sail to the fish, catch them, then sell beside your hut. Watch your vatus and the fish price.", + fishingHold: + "The catch is now in your hold, not money yet. Your boat is beside your hut, so you can sell it. Without your own hut here, you would need to sail elsewhere.", + islandStart: + "You are the Builder and your boat is beside the island. Turn your 3 vatus into a hut, then add a drawing and a tourist.", + usedCharacter: + "The Builder saved you 2 vatus and is now used for this round. Other players can also develop this island: huts belong to players, but drawings and tourists stay on the island.", + tradeStart: + "Explore the wreck, sell its treasure, then compare two exports: with or without completing a ship.", + explore: + "Explore this wreck. Take treasure worth 2; only 1 treasure marker will remain on this sea tile.", + keepTreasure: + "Treasures can be kept for twice their value in prosperity at game end, or sold at any time for their value in vatus. Selling uses no action marker.", + sellTreasure: + "You have 1 vatu. Sell your treasure for 2 more to afford the beef export, which costs 3.", + export: + "Export beef from the island beside your boat. It costs 3 vatus and earns 5 prosperity. It also fills the ship's last space for 2 extra prosperity.", + tradeDone: + "You earned 7 prosperity from one export. Goods fill the first ship that needs them. Completed ships are replaced at the start of the next round.", + tradeCompare: + "Copra costs 2 vatus and earns 3 prosperity. It goes to the second ship, which still needs beef: no completion bonus. Beef costs 3 vatus and fills the first ship's last space: 5 prosperity + 2 for completing the ship = 7.", + tradeChoose: + "Export copra or beef from the island beside your boat. Compare the cost and prosperity shown before confirming your choice.", + tradeIncomplete: + "You earned 3 prosperity for the copra. The second ship still needs beef, so you received no completion bonus. Completing a ship adds 2 prosperity to the exported good's usual reward. Try the lesson again with beef to see the difference.", + restStart: + "Rest lets you choose a secret bonus. You receive it at the end of the round, after all action markers have been removed.", + restChoice: + "Choose the First player token. The other bonuses are 1 vatu, 1 prosperity, or both.", + extendStart: + "Round 2 has begun. You hold the First player marker, so you place the new tiles. The other players wait during this step.", + extendCharacter: + "The map is ready. Choose your character for this round. The newly revealed pair of tiles is a preview for the next round.", + waterStart: + "This optional expansion adds dikes and flooding. Protect the islands together: if three sink, everyone loses. Otherwise, prosperity still decides the winner.", + waterCountdown: + "This position starts in round 4 with 3 actions before flooding. The starting island already has 3 water markers and one dike. Build before the countdown reaches zero.", + waterBuild: + "On the starting island, build a hut and a dike together for 4 vatus. Place the new dike towards the sea tile with fish value 2, where your boat is.", + waterCoasts: + "Two coasts are now protected. Only the side towards the sea tile with the other boats remains exposed. Each unprotected side touching a sea tile adds 1 water; empty board spaces add none.", + waterFish: + "Fish once. The countdown falls from 2 to 1. Only performed actions count: retrieving markers without acting does not advance it.", + waterTourist: + "Bring a tourist to the starting island. This is the last action before flooding: the waters rise immediately afterwards, before the next player acts.", + waterResult: + "Your island gained 1 water and survived at 4. The other island reached 5 and sank: its huts, goods, drawings and tourists were removed. A submerged island is inaccessible.", + waterScoring: + "If three islands sink, everyone loses. At game end, each hut on an island with 1 / 2 / 3 / 4 water loses 1 / 3 / 5 / 7 prosperity, in addition to normal scoring.", + waterDone: + "A dike protects one coast, not the whole island. Existing water stays. Watch both the countdown and the exposed coasts before spending your Build action.", +}; diff --git a/viewer/tutorials.js b/viewer/tutorials.js index 3a9b730..0eb04ee 100644 --- a/viewer/tutorials.js +++ b/viewer/tutorials.js @@ -1,23 +1,41 @@ +import { LESSON } from "./tutorial-copy.js"; +import { FIRST_HELP } from "./learning.js"; +import { + EXTEND_TITLE, + EXTEND_WHO, + EXTEND_HOW, + EXTEND_WHEN, + REMAINING_TILES, +} from "./learning.js"; import * as E from "../engine/index.js"; export const chapterMetadata = [ { id: "planning", - version: 2, + version: 4, title: "Plan your day", description: "Place five markers and understand action majorities.", }, { id: "fishing", - version: 1, + version: 2, title: "From sea to market", description: "Sail, fish and sell your catch beside your hut.", }, { id: "islands", - version: 1, + version: 2, title: "An island economy", description: "Build a hut, draw in the sand and welcome a tourist.", }, + { id: "trade", version: 2, title: "Trade", description: LESSON.tradeStart }, + { id: "rest", version: 1, title: "Rest", description: LESSON.restStart }, + { id: "expansion", version: 2, title: EXTEND_TITLE, description: EXTEND_WHO }, + { + id: "rising-waters", + version: 1, + title: "Rising Waters (expansion only)", + description: LESSON.waterStart, + }, ]; function prepared(phase = "actions") { const s = E.init(3, [], {}, "vanuatu-lesson"); @@ -39,30 +57,117 @@ function prepared(phase = "actions") { s.tourists = 2; return s; } -function play(s, m) { +function play(s, m, opponentMove = E.moveAI) { let next = E.move(s, m, 0), n = 0; while (!next.finished && next.actor !== 0 && n++ < 100) - next = E.moveAI(next, next.actor); + next = opponentMove(next, next.actor); return next; } +// Demonstrate several stacks and useful action sequences instead of the general +// bot's scoring strategy. Pick only legal moves so the player's choices stay free. +const planningOpponents = { + 1: { + characters: ["fisherman", "navigator"], + passes: [["fish", "sail"], ["fish", "draw"], ["rest"]], + actions: ["fish", "sail", "draw", "rest"], + }, + 2: { + characters: ["diver", "builder"], + passes: [["explore", "build"], ["explore", "tourist"], ["rest"]], + actions: ["explore", "build", "tourist", "rest"], + }, +}; +function planningOpponent(s, p) { + if (s.round !== 1) return E.moveAI(s, p); + const script = planningOpponents[p]; + const legal = E.availableMoves(s, p); + let selected; + if (s.phase === "character") + selected = script.characters + .map((character) => legal.find((m) => m.character === character)) + .find(Boolean); + else if (s.phase === "plan") + selected = legal.find( + (m) => + m.type === "plan" && + m.actions.join() === script.passes[s.planningPass].join(), + ); + else if (s.phase === "actions") + selected = script.actions + .map((action) => + legal.find( + (m) => + m.type === "act" && + m.action === action && + (action !== "sail" || m.path.length === 1), + ), + ) + .find(Boolean); + return selected ? E.move(s, selected, p) : E.moveAI(s, p); +} 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 = { + expansion: { + game: "vanuatu", + id: "expansion", + version: 2, + initialState: () => { + const s = prepared("expand"); + s.round = 2; + return s; + }, + move: (s, m) => E.move(s, m, 0), + steps: [ + { id: "round", title: EXTEND_TITLE, text: LESSON.extendStart }, + { + id: "first-tile", + title: EXTEND_TITLE, + text: EXTEND_HOW, + complete: (s) => s.upcoming.length === 1, + validateMove: (s, m) => (m.type === "place" ? undefined : EXTEND_HOW), + }, + { + id: "second-tile", + title: REMAINING_TILES, + text: EXTEND_WHO, + complete: (s) => s.phase !== "expand", + validateMove: (s, m) => (m.type === "place" ? undefined : EXTEND_HOW), + }, + { + id: "character", + title: "Choose a character", + text: LESSON.extendCharacter, + complete: (s) => !!s.players[0].character, + validateMove: (s, m) => + m.type === "character" ? undefined : LESSON.extendCharacter, + }, + ], + completion: { title: EXTEND_TITLE, text: EXTEND_WHEN }, + }, planning: { game: "vanuatu", id: "planning", - version: 2, + version: 4, initialState: () => { - const s = prepared("plan"); - s.characters = []; - s.options.characters = false; + const s = prepared("character"); + s.players[1].boat = "1,0"; + s.players[2].boat = "0,1"; return s; }, - move: play, + move: (s, m) => play(s, m, planningOpponent), steps: [ + { + id: "character", + title: "Choose a character", + text: LESSON.character, + complete: (s) => s.phase === "plan", + validateMove: (s, m) => + m.type === "character" ? undefined : LESSON.character, + }, { id: "five-actions", title: "Five markers, up to five actions", @@ -124,7 +229,7 @@ export const chapters = { fishing: { game: "vanuatu", id: "fishing", - version: 1, + version: 2, initialState: () => { const s = prepared(); s.board["0,0"].huts = [0]; @@ -138,6 +243,7 @@ export const chapters = { }, move: play, steps: [ + { id: "route", title: "From sea to market", text: LESSON.fishingStart }, { id: "sail", title: "Find a fishing ground", @@ -155,6 +261,7 @@ export const chapters = { complete: (s) => s.players[0].fish.includes(2), validateMove: only("fish"), }, + { id: "hold", title: "Fish in hold", text: LESSON.fishingHold }, { id: "sell", title: "Sell your catch", @@ -171,7 +278,7 @@ export const chapters = { islands: { game: "vanuatu", id: "islands", - version: 1, + version: 2, initialState: () => { const s = prepared(); s.players[0].character = "builder"; @@ -181,6 +288,7 @@ export const chapters = { }, move: play, steps: [ + { id: "route", title: "An island economy", text: LESSON.islandStart }, { id: "hut", title: "Build a beach hut", @@ -191,6 +299,11 @@ export const chapters = { ? undefined : "Build a hut with the Builder bonus enabled.", }, + { + id: "shared-island", + title: "Character bonus", + text: LESSON.usedCharacter, + }, { id: "drawing", title: "Draw in the sand", @@ -211,4 +324,174 @@ export const chapters = { text: "Prosperity comes from trade, drawings, characters and endgame scoring. Keep enough vatus to fund the actions you plan.", }, }, + + trade: { + game: "vanuatu", + id: "trade", + version: 2, + initialState: () => { + const s = prepared(); + s.players[0].boat = "0,1"; + s.players[0].money = 1; + for (const a of ["explore", "buy", "rest"]) s.players[0].markers[a] = 1; + s.demands[0] = { + id: 10, + goods: ["kava", "copra", "beef"], + filled: [true, true, false], + }; + s.demands[1] = { + id: 3, + goods: ["beef", "beef", "copra"], + filled: [false, false, false], + }; + return s; + }, + move: play, + steps: [ + { id: "route", title: "Trade", text: LESSON.tradeStart }, + { + id: "explore", + title: "Explore", + text: LESSON.explore, + complete: (s) => s.players[0].treasures.includes(2), + validateMove: only("explore"), + }, + { id: "choice", title: "Explore", text: LESSON.keepTreasure }, + { + id: "sell-treasure", + title: "Sell treasures", + text: LESSON.sellTreasure, + complete: (s) => s.players[0].money === 3, + validateMove: (s, m) => + m.type === "treasure" ? undefined : LESSON.sellTreasure, + }, + { id: "compare", title: "Export", text: LESSON.tradeCompare }, + { + id: "export", + title: "Export", + text: LESSON.tradeChoose, + complete: (s) => s._history.some((h) => h.move.action === "buy"), + validateMove: (s, m) => + m.action === "buy" && ["copra", "beef"].includes(m.good) + ? undefined + : LESSON.tradeChoose, + }, + ], + completion: { + title: "Trade", + text: (s) => + s.players[0].score === 7 ? LESSON.tradeDone : LESSON.tradeIncomplete, + }, + }, + rest: { + game: "vanuatu", + id: "rest", + version: 1, + initialState: () => { + const s = prepared(); + s.first = 1; + s.players[0].markers.rest = 1; + return s; + }, + move: play, + steps: [ + { id: "bonus", title: "Rest", text: LESSON.restStart }, + { + id: "rest", + title: "Rest", + text: LESSON.restStart, + complete: (s) => s.phase === "rest", + validateMove: only("rest"), + }, + { + id: "token", + title: "Choose a rest token", + text: LESSON.restChoice, + complete: (s) => s.round === 2 && s.first === 0, + validateMove: (s, m) => + m.type === "rest" && m.token === "first" + ? undefined + : LESSON.restChoice, + }, + ], + completion: { title: "First player", text: FIRST_HELP }, + }, + "rising-waters": { + game: "vanuatu", + id: "rising-waters", + version: 1, + initialState: () => { + const s = prepared(); + s.options.risingWaters = true; + s.round = 4; + s.waterCountdown = 3; + s.players[0].boat = "1,0"; + s.players[0].money = 4; + for (const a of ["build", "fish", "tourist", "sail", "rest"]) + s.players[0].markers[a] = 1; + s.board["0,0"].water = 3; + s.board["0,0"].dikes = ["0,1"]; + s.board["2,1"] = E.tileState("a1"); + Object.assign(s.board["2,1"], { + water: 4, + huts: [1], + tourists: 1, + drawings: 1, + }); + s.players[1].hutsLeft = 7; + s.dikesLeft = 19; + return s; + }, + move: play, + steps: [ + { + id: "expansion", + title: "Rising Waters (expansion only)", + text: LESSON.waterStart, + }, + { + id: "timing", + title: "How a round works", + text: "In rounds 2, 4, 6 and 8, a die rolled at the start of the round sets a countdown. During the action phase, each performed action reduces it by 1. At 0, the waters rise immediately after that action, before the next player acts.", + }, + { + id: "countdown", + title: "Actions until the waters rise", + text: LESSON.waterCountdown, + }, + { + id: "dike", + title: "Build", + text: LESSON.waterBuild, + complete: (s) => + s.board["0,0"].dikes.includes("1,0") && + s.board["0,0"].huts.includes(0), + validateMove: (s, m) => + m.action === "build" && m.cell === "0,0" && m.hut && m.dike === "1,0" + ? undefined + : LESSON.waterBuild, + }, + { id: "coasts", title: "Dike", text: LESSON.waterCoasts }, + { + id: "fish", + title: "Catch the fish", + text: LESSON.waterFish, + complete: (s) => s.waterCountdown === 1, + validateMove: only("fish"), + }, + { + id: "tourist", + title: "Welcome a visitor", + text: LESSON.waterTourist, + complete: (s) => s.waterTriggered, + validateMove: (s, m) => + m.action === "tourist" && m.cell === "0,0" + ? undefined + : LESSON.waterTourist, + }, + { id: "flood", title: "Rising Waters", text: LESSON.waterResult }, + { id: "score", title: "Final scoring", text: LESSON.waterScoring }, + ], + completion: { title: "Rising Waters", text: LESSON.waterDone }, + }, }; diff --git a/viewer/ui.js b/viewer/ui.js index 5cb6cdb..ce3c84b 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -1,3 +1,6 @@ +import { blockingHtml, blockingText } from "./blocking.js"; +import { FIRST_HELP, RETRIEVE_HELP } from "./learning.js"; +import { EXTEND_WHO, EXTEND_HOW, REMAINING_TILES } from "./learning.js"; import morphdom from "morphdom"; import { ACTIONS, @@ -18,7 +21,11 @@ import { translator, characterHelp } from "./labels.js"; import { mountActivity } from "./activity.js"; import { rulesHtml } from "./rules.js"; import { createMoveSound } from "./sound.js"; -import { languages, resolveLocale } from "./localization/index.js"; +import { + languages, + resolveLocale, + translateText, +} from "./localization/index.js"; const total = (a) => a.reduce((a, b) => a + b, 0); const unique = (a) => [...new Set(a)]; function coastArrow(cell, edge) { @@ -27,6 +34,20 @@ function coastArrow(cell, edge) { angle = (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI; return ``; } +const actionHelp = { + sail: "Sail 1–3 ocean spaces, paying 1 vatu per space.", + fish: "Take a fish tile from your ocean space. Its value equals the fish remaining there.", + explore: + "Take a treasure tile from your ocean space. Treasures can be sold for vatus or kept for final scoring.", + sell: "Sell fish beside one of your huts at the current market price. The price then falls by 1.", + build: + "Build a hut on an adjacent island for 3 vatus. Each hut scores 2 prosperity per tourist at game end.", + buy: "Export a good from an adjacent island to a ship that needs it. Pay 1/2/3 vatus for kava/copra/beef and earn 1/3/5 prosperity.", + draw: "Make a sand drawing on an adjacent island to earn 3 prosperity.", + tourist: + "Bring a tourist to an adjacent island and earn 1 vatu for every hut there, of any colour.", + rest: "Choose a rest token. Its bonus is resolved at the end of the round.", +}; const symbols = ["●", "◆", "▲", "■", "✦"]; export function mountGame(target, options = {}) { const root = document.createElement("div"); @@ -120,7 +141,7 @@ export function mountGame(target, options = {}) { if (m.type === "plan" || m.type === "neutral") return m.actions.map((a) => icon(a)).join(""); if (m.type === "discard") - return `${icon("undo")} ${"Retrieve without acting"} ${icon(m.action)}`; + return `${icon("warning", "Retrieve without acting")} ${icon(m.action)}`; if (m.type === "rest") return restContent(m.token); if (m.type === "governor") return `${icon(m.from)} → ${icon(m.to)}`; if (m.type === "treasure") @@ -161,8 +182,12 @@ export function mountGame(target, options = {}) { const idx = (s.legal ?? []).indexOf(m); return btn( actionDetail(m), - `data-move="${idx}" ${pending ? "disabled" : ""}`, - primary ? "primary move-option" : "move-option", + `title="${esc(m.type === "discard" ? translateText("Retrieve without acting", lang) : m.action ? translateText(actionHelp[m.action], lang) : t(m.type === "plan" || m.type === "neutral" ? "plan" : m.type))}" data-move="${idx}" ${m.type === "discard" ? `aria-label="${esc(translateText("Retrieve without acting", lang))} — ${esc(translateText(t(m.action), lang))}"` : ""} ${pending ? "disabled" : ""}`, + m.type === "discard" + ? "move-option retrieve-warning" + : primary + ? "primary move-option" + : "move-option", ); } function restContent(key) { @@ -174,7 +199,7 @@ export function mountGame(target, options = {}) { } function playerCard(p, i) { const c = CHARACTERS[p.character]; - return `${blockingHtml(s, player, action, lang)}
${esc(translateText(RETRIEVE_HELP, lang))}
${esc(translateText(RETRIEVE_HELP, lang))}
` : ""}${hasBonus && hasNormal ? `` : ""}${pickText}${governor ? btn(`${icon("marker")} ↔`, `data-governor title="${t("governor")}"`) : ""}${selectedAction ? titled(t("cancel"), icon("close"), "data-cancel", "icon-button") : ""}${esc(translateText(FIRST_HELP, lang))}
`, + ); + return; + } if ("unavailable" in d) { showDialog(`${esc(d.unavailable)}
`); return; } if ("move" in d) { - send(s.legal[Number(d.move)]); + const move = s.legal[Number(d.move)]; + if ( + move?.type === "discard" && + !("confirmedRetrieval" in d) && + legal().some((m) => m.type !== "discard") + ) { + showDialog( + `${esc(translateText("You can still take another action. Retrieve this stack without acting?", lang))}
`, + ); + return; + } + send(move); return; } if ("bgsPlayer" in d) { @@ -593,7 +639,7 @@ export function mountGame(target, options = {}) { } if ("help" in d) { showDialog( - `