From 89401e3ed5caa037a8ac1fd276ee142fe9102f16 Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Thu, 22 Oct 2026 18:37:26 +0200 Subject: [PATCH] Prepare Acquire private beta with localized tutorials and BGS integration fixes --- README.md | 11 + docs/admin/README.md | 30 +- docs/admin/credits.md | 2 + docs/admin/gameinfo.json | 122 +++++ docs/admin/release-check.md | 62 +++ docs/registering.md | 4 + package.json | 4 +- packages/viewer/index.html | 10 +- packages/viewer/package.json | 2 +- packages/viewer/src/App.svelte | 4 + packages/viewer/src/dev.ts | 440 ++++++++++--------- packages/viewer/src/lib/ChainTable.svelte | 56 +-- packages/viewer/src/lib/Chat.svelte | 29 ++ packages/viewer/src/lib/PlayerName.svelte | 7 +- packages/viewer/src/lib/Players.svelte | 84 ++-- packages/viewer/src/lib/locales/da.ts | 40 ++ packages/viewer/src/lib/locales/de.ts | 40 ++ packages/viewer/src/lib/locales/el.ts | 40 ++ packages/viewer/src/lib/locales/en.ts | 40 ++ packages/viewer/src/lib/locales/fa.ts | 39 ++ packages/viewer/src/lib/locales/fr.ts | 41 ++ packages/viewer/src/lib/locales/hi.ts | 37 ++ packages/viewer/src/lib/locales/it.ts | 40 ++ packages/viewer/src/lib/locales/ko.ts | 39 ++ packages/viewer/src/lib/locales/nl.ts | 40 ++ packages/viewer/src/lib/locales/pl.ts | 39 ++ packages/viewer/src/lib/locales/pt-BR.ts | 40 ++ packages/viewer/src/lib/locales/ro.ts | 40 ++ packages/viewer/src/lib/locales/ru.ts | 40 ++ packages/viewer/src/lib/locales/vi.ts | 40 ++ packages/viewer/src/lib/locales/zh-CN.ts | 35 ++ packages/viewer/src/lib/locales/zh-TW.ts | 35 ++ packages/viewer/src/lib/store.svelte.ts | 2 +- packages/viewer/src/lib/theme.css | 6 + packages/viewer/src/tutorial/Guide.svelte | 90 ++++ packages/viewer/src/tutorial/lessons.spec.ts | 102 +++++ packages/viewer/src/tutorial/lessons.ts | 117 +++++ packages/viewer/src/tutorial/mount.svelte.ts | 91 ++++ packages/viewer/src/tutorial/tutorial.css | 14 + packages/viewer/src/viewer.ts | 109 ++--- pnpm-lock.yaml | 29 ++ scripts/check-browser.mjs | 265 +++++++++++ 42 files changed, 2010 insertions(+), 347 deletions(-) create mode 100644 docs/admin/gameinfo.json create mode 100644 docs/admin/release-check.md create mode 100644 packages/viewer/src/tutorial/Guide.svelte create mode 100644 packages/viewer/src/tutorial/lessons.spec.ts create mode 100644 packages/viewer/src/tutorial/lessons.ts create mode 100644 packages/viewer/src/tutorial/mount.svelte.ts create mode 100644 packages/viewer/src/tutorial/tutorial.css create mode 100644 scripts/check-browser.mjs diff --git a/README.md b/README.md index 49cc894..bdbe27a 100644 --- a/README.md +++ b/README.md @@ -53,3 +53,14 @@ Each GitHub Release has the built engine package and viewer files attached, read ## Licence AGPL-3.0. See [LICENSE](LICENSE). + +## Interactive tutorials and browser checks + +After `pnpm build`, open the dev server with `?bundle=1&tutorial=founding` (or +`mergers`, `scoring`). Add `&locale=fr` to switch languages. Tutorials use the real +engine, remember progress locally and support replaying a step or restarting. + +`pnpm test:browser` starts its own Vite server on port 5191 and checks the compiled +viewer, not a source-only preview. Install Chromium once with +`pnpm exec playwright install chromium`. Screenshots and the report go to ignored +`release/qa/`. Set `ACQUIRE_TEST_URL` to reuse an existing dev server. diff --git a/docs/admin/README.md b/docs/admin/README.md index 8e794b5..e8f58cc 100644 --- a/docs/admin/README.md +++ b/docs/admin/README.md @@ -3,13 +3,13 @@ Everything to paste or upload in the BGS admin panel for Acquire. All text is our own wording; nothing is taken from any published edition's rulebook, card or box. -| File | Where it goes | -| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [description.md](description.md) | Game metadata → **description** (Markdown). | -| [rules.md](rules.md) | Game metadata → **rules** (Markdown; the boardgame page's "See rules" toggle). The BGS guide also mentions a CMS page `acquire:rules`; if the admin panel still uses that, paste the same text there. | -| [credits.md](credits.md) | Game metadata → **credits** (Markdown). | -| [pictogram.svg](pictogram.svg) | Pictogram upload: transparent background, tight bounds, square corners. Export to PNG at the size the panel asks for if it does not take SVG. | -| [screenshots/](screenshots) | Screenshot gallery, in the order below. | +| File | Where it goes | +| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | +| [description.md](description.md) | Game metadata → **description** (Markdown). | +| [rules.md](rules.md) | CMS page `acquire:rules` (English); set the metadata rules field to `[Rules](/page/acquire:rules)`. | +| [credits.md](credits.md) | Game metadata → **credits** (Markdown). | +| [pictogram.svg](pictogram.svg) | Pictogram upload: transparent background, tight bounds, square corners. Export to PNG at the size the panel asks for if it does not take SVG. | +| [screenshots/](screenshots) | Screenshot gallery, in the order below. | Description, rules and credits are English. BGS stores per-language overlays for these three fields (the admin panel can translate them); the viewer itself is already translated. @@ -17,14 +17,13 @@ fields (the admin panel can translate them); the viewer itself is already transl ## Links - **bgg:** https://boardgamegeek.com/boardgame/5/acquire -- **source:** https://github.com/MikeIsom/mergers-game -- **publisher / purchase:** Renegade Game Studios' Acquire page, if you want one. Optional. +- **source:** https://github.com/boardgamers/mergers-game +- **publisher / purchase:** https://renegadegamestudios.com/acquire/ ## Tags -The BGS guide says to pick tags from a shared list (`packages/models/boardgame-tags.ts`), but that -file and a tags field don't exist in the BGS repository yet. Suggested tags for when they do: -**economic**, **stock holding**, **tile placement**, **area majority**, **classic**, **family**. +Use **economic**, from BGS’s shared tag list. Useful missing categories to propose are +**tile placement** and **stock holding**; do not substitute unrelated tags. ## Screenshots @@ -40,3 +39,10 @@ Upload each light image and add the dark one with **Add dark version**. To recreate them, run the viewer dev server and open, for example, `http://localhost:5173/?players=4&seed=bgs&publicHoldings=1&bar=0&theme=dark&moves=50&merger=1` in a 1280 × 860 window (390 × 844 for the phone view). + +## Private beta configuration + +`gameinfo.json` records the initial private registration, including all three tutorial +chapters. The engine and viewer URLs are supplied by the upload tools. Keep `public` false. + +See [release-check.md](release-check.md) for validation and remaining public-release gaps. diff --git a/docs/admin/credits.md b/docs/admin/credits.md index 516ff6e..bce4c56 100644 --- a/docs/admin/credits.md +++ b/docs/admin/credits.md @@ -1,3 +1,5 @@ **Acquire** was designed by **Sid Sackson**, first published by 3M in 1964, and is currently published by Renegade Game Studios. This is an unofficial open-source implementation of Acquire for boardgamers.space. Not affiliated with or endorsed by Hasbro, Avalon Hill, Renegade Game Studios or any other publisher of Acquire. The rules text, chain colours, chain marks and artwork in this implementation are its own; no text or artwork from any published edition is used. + +Digital implementation: [MikeIsom](https://github.com/MikeIsom/mergers-game). BGS integration and interactive tutorials: Boardgamers. diff --git a/docs/admin/gameinfo.json b/docs/admin/gameinfo.json new file mode 100644 index 0000000..390ee6f --- /dev/null +++ b/docs/admin/gameinfo.json @@ -0,0 +1,122 @@ +{ + "label": "Acquire", + "displayTitle": { + "title": "Acquire" + }, + "releaseYear": 1964, + "tags": ["economic"], + "players": [2, 3, 4, 5, 6], + "public": false, + "description": "Build hotel chains, buy their stock and cash in when they merge. Each turn you place a tile on a 12 × 9 grid: tiles next to each other found a chain, chains grow, and when a tile joins two chains the larger one takes over the smaller. Shareholders of the chain taken over collect bonuses and sell or trade their stock. Whoever has the most money at the end wins. A classic stock-market game for 2–6 players, live or asynchronous.", + "rules": "[Rules](/page/acquire:rules)", + "credits": "**Acquire** was designed by **Sid Sackson**, first published by 3M in 1964, and is currently published by Renegade Game Studios.\n\nThis is an unofficial open-source implementation of Acquire for boardgamers.space. Not affiliated with or endorsed by Hasbro, Avalon Hill, Renegade Game Studios or any other publisher of Acquire. The rules text, chain colours, chain marks and artwork in this implementation are its own; no text or artwork from any published edition is used.\n\nDigital implementation: [MikeIsom](https://github.com/MikeIsom/mergers-game). BGS integration and interactive tutorials: Boardgamers.", + "links": { + "source": "https://github.com/boardgamers/mergers-game", + "bgg": "https://boardgamegeek.com/boardgame/5/acquire", + "publisher": "https://renegadegamestudios.com/acquire/", + "buy": "https://renegadegamestudios.com/acquire/" + }, + "viewer": { + "url": "", + "dependencies": { + "scripts": [], + "stylesheets": [] + }, + "topLevelVariable": "acquire", + "chat": true, + "integratedControls": ["chat"], + "replayable": true, + "fullScreenMobile": false + }, + "engine": { + "package": { + "name": "", + "version": "" + }, + "entryPoint": "dist/wrapper.js" + }, + "preferences": [ + { + "name": "colorBlind", + "label": "Color-blind mode", + "type": "checkbox", + "default": false + } + ], + "options": [ + { + "name": "publicHoldings", + "label": "Public holdings (everyone sees all stock and cash)", + "type": "checkbox", + "default": false + }, + { + "name": "teamPlay", + "label": "Team play (4 players: seats 1+3 against 2+4)", + "type": "checkbox", + "default": false + }, + { + "name": "twoPlayerMode", + "label": "Two-player mode", + "type": "select", + "default": "bank", + "items": [ + { + "name": "bank", + "label": "Bank as third shareholder" + }, + { + "name": "fourHands", + "label": "Four hands (each player controls two seats)" + } + ] + }, + { + "name": "autoEnd", + "label": "End automatically when an end condition is met", + "type": "checkbox", + "default": false + }, + { + "name": "endSize", + "label": "Chain size that ends the game", + "type": "select", + "default": "41", + "items": [ + { + "name": "41", + "label": "41 tiles (standard)" + }, + { + "name": "31", + "label": "31 tiles (shorter game)" + } + ] + } + ], + "settings": [], + "expansions": [], + "tutorial": { + "chapters": [ + { + "id": "founding", + "version": 1, + "title": "Found a chain", + "description": "Place a tile, found a hotel chain and buy your first shares." + }, + { + "id": "mergers", + "version": 1, + "title": "Resolve a merger", + "description": "Collect shareholder bonuses, then sell, trade or keep your stock." + }, + { + "id": "scoring", + "version": 1, + "title": "End and score", + "description": "Learn when to end the game and how the final payout works." + } + ] + } +} diff --git a/docs/admin/release-check.md b/docs/admin/release-check.md new file mode 100644 index 0000000..453d0c0 --- /dev/null +++ b/docs/admin/release-check.md @@ -0,0 +1,62 @@ +# Acquire private beta — 22 October 2026 + +Private BGS registration: `acquire`, version `1`. Engine `0.0.1`, viewer `0.0.2`. +Source: . Keep `public: false`. + +## Validation + +- `pnpm check`: formatting, lint, TypeScript/Svelte checks, 198 engine tests, + 52 viewer/tutorial tests, and the production build. Two pre-existing lint warnings + remain (an unused test import and Svelte's `bind:this` assignment). +- Protocol diagnostics: all eight required engine methods; full core/chat/replay + viewer coverage, preferences, avatars and theme handlers. Protocol `0.10.0` is the + latest published npm version checked for this release. +- `pnpm test:browser` loads the compiled IIFE and CSS. It covers 68 combinations + of locale and viewport (1280, 844, 390 and 320 pixels), Persian RTL, color-blind + symbols, chat permissions/sending, analysis chat suppression, every six-player + and four-hands seat plus spectators, replay/live navigation and real tile moves. +- All three tutorials run through normal controls on desktop and phone. Checks + cover saved progress, reload, step retry, rejected unrelated actions, French and + Persian resume, and the final $15,800 scoring example. Unit tests complete and + restore every chapter in all 17 locales using the real engine. +- Screenshots and a machine-readable report are generated in `release/qa/`. + The gallery uses three distinct views, each with light and dark variants. + +## Fixes made for beta + +- Snapshot Svelte move data before handing it to the host. Nested share selections + and merger-order arrays must be structured-cloneable for iframe messaging and + tutorial persistence. +- Contain wide player/chain tables on narrow screens, without widening the page. +- Supply default player symbols in color-blind mode when BGS sends no assignments. +- Translate shared chat permissions, unread counts and dates in all 17 locales. +- Add three interactive tutorials: founding, mergers and scoring. Lesson text and + controls are translated in all 17 locales; progress is stored locally. +- Add a built-bundle development mode and repeatable browser checks. + +## Still required before a public release + +- Translate the English CMS rules, description, credits and BGS setup/preference + labels, including the tutorial launcher cards. The in-game UI, journal and + tutorial content are translated; the engine's plain `simple` last-move summaries + used by the BGS game list remain English. Do not use automated translation APIs. +- Implement and test playable historical analysis. The engine supports replay, + but has no `createAnalysis`, `analysisMove` or hidden-information scenario + implementation. Do not enable ongoing-game analysis. +- Human playtesting of the private beta, including two-player bank mode, four + hands, team play, long games and translation quality. Automated coverage is not + a claim of a complete human rules review. + +## Metadata + +- Base title: Acquire; 2–6 players; publication year 1964. +- Credits name Sid Sackson, 3M, current publisher Renegade Game Studios and the + digital implementation's author. Publisher/purchase: + ; BGG: + . +- Upload the original transparent `pictogram.svg`, English rules as the CMS page + `acquire:rules`, and `gameinfo.json` for the initial version/configuration. +- Use the existing `economic` tag. Suggested additions to BGS's shared list: + `tile placement` and `stock holding`. +- Intended beta accounts: not2cool, Spock and AlphaZero. GitHub collaborator: + MikeIsom, write permission (requires accepting GitHub's invitation). diff --git a/docs/registering.md b/docs/registering.md index f79c90c..015a574 100644 --- a/docs/registering.md +++ b/docs/registering.md @@ -102,6 +102,8 @@ source maps in devtools, `acquire-viewer.iife.js.map`, together. Then set: chat panel sits beside the log and is hidden in analysis mode. - Replayable: on. - Full screen on mobile: off. The layout is width-based and works at content height. +- Tutorials: copy `tutorial` from `docs/admin/gameinfo.json` (founding, mergers and scoring). + All three are interactive and translated into the 17 viewer locales. Save, open the game page, create a private game, and play. @@ -152,3 +154,5 @@ BGS's release checklist, and where this repo stands: comes from the English `simple` line that `logSlice` adds to each log entry. - Admin panel content (rules page, pictogram, credits, description, links, screenshots) is in `docs/admin/`; its README says where each file goes. + +The October 2026 private-beta audit is in [admin/release-check.md](admin/release-check.md). diff --git a/package.json b/package.json index fd31912..fec1aff 100644 --- a/package.json +++ b/package.json @@ -13,11 +13,13 @@ "fmt": "oxfmt", "fmt:check": "oxfmt --check", "lint": "oxlint", - "check": "pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build" + "check": "pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build", + "test:browser": "pnpm build && node scripts/check-browser.mjs" }, "devDependencies": { "oxfmt": "0.61.0", "oxlint": "1.76.0", + "playwright": "1.62.1", "svelte": "5.56.8" }, "engines": { diff --git a/packages/viewer/index.html b/packages/viewer/index.html index e2d5762..4bee157 100644 --- a/packages/viewer/index.html +++ b/packages/viewer/index.html @@ -8,7 +8,15 @@
diff --git a/packages/viewer/package.json b/packages/viewer/package.json index d7700aa..cad5eef 100644 --- a/packages/viewer/package.json +++ b/packages/viewer/package.json @@ -1,6 +1,6 @@ { "name": "acquire-viewer", - "version": "0.0.1", + "version": "0.0.2", "private": true, "description": "Browser viewer for Acquire on boardgamers.space", "license": "AGPL-3.0-only", diff --git a/packages/viewer/src/App.svelte b/packages/viewer/src/App.svelte index dc49578..e601f61 100644 --- a/packages/viewer/src/App.svelte +++ b/packages/viewer/src/App.svelte @@ -70,9 +70,13 @@ } .info { grid-area: info; + min-width: 0; display: grid; gap: 16px; } + .info > :global(section) { + min-width: 0; + } /* Tablets and phones in landscape: the board beside the decision and hand. */ @media (min-width: 700px) { .layout { diff --git a/packages/viewer/src/dev.ts b/packages/viewer/src/dev.ts index 7b30a42..8f16bb5 100644 --- a/packages/viewer/src/dev.ts +++ b/packages/viewer/src/dev.ts @@ -7,9 +7,25 @@ import * as rules from "acquire-engine"; import { currentSeat, legalMoves, type GameState } from "acquire-engine"; import * as engine from "acquire-engine/wrapper.js"; import { LOCALES } from "./lib/i18n.ts"; -import { viewer } from "./viewer"; const params = new URLSearchParams(window.location.search); +const viewer = params.get("bundle") === "1" ? await loadBuiltViewer() : (await import("./viewer")).viewer; + +async function loadBuiltViewer(): Promise { + const revision = Date.now(); + const style = document.createElement("link"); + style.rel = "stylesheet"; + style.href = `/dist/acquire-viewer.css?build=${revision}`; + document.head.append(style); + await new Promise((resolve, reject) => { + const script = document.createElement("script"); + script.src = `/dist/acquire-viewer.iife.js?build=${revision}`; + script.onload = () => resolve(); + script.onerror = () => reject(new Error("Build the viewer with pnpm build before using bundle=1")); + document.head.append(script); + }); + return (window as unknown as { acquire: typeof import("./viewer").viewer }).acquire; +} const players = Math.min(6, Math.max(2, Number(params.get("players") ?? 4))); const seed = params.get("seed") ?? "dev"; const options: Record = {}; @@ -33,220 +49,226 @@ if (Number.isNaN(viewAs) || viewAs >= players) { viewAs = undefined; } -const emitter = viewer.launch("#app"); +if (params.has("tutorial")) { + await viewer.launchTutorial("#app", { chapter: params.get("tutorial")!, locale: params.get("locale") ?? "en" }); +} else { + const emitter = viewer.launch("#app"); -let hotSeat = params.get("hotseat") !== "0"; + let hotSeat = params.get("hotseat") !== "0"; -function sync(): void { - if (hotSeat && !state.ended) { - viewAs = engine.currentPlayer(state); - select.value = String(viewAs); + function sync(): void { + if (hotSeat && !state.ended) { + viewAs = engine.currentPlayer(state); + select.value = String(viewAs); + } + emitter.emit("player", { index: viewAs }); + emitter.emit("state", engine.stripSecret(structuredClone(state), viewAs)); + status.textContent = state.ended + ? "Game over" + : `Move ${state.log.filter((e) => e.type === "move" && !e.auto).length} · acting: player ${engine.currentPlayer(state)}`; } - emitter.emit("player", { index: viewAs }); - emitter.emit("state", engine.stripSecret(structuredClone(state), viewAs)); - status.textContent = state.ended - ? "Game over" - : `Move ${state.log.filter((e) => e.type === "move" && !e.auto).length} · acting: player ${engine.currentPlayer(state)}`; -} -let rng = 1; -function randomMove(): boolean { - if (state.ended) { - return false; - } - const moves = legalMoves(state).filter((move) => move.type !== "announce"); - rng = (Math.imul(rng, 1103515245) + 12345) >>> 0; - const move = (moves.length > 0 ? moves : legalMoves(state))[rng % Math.max(1, moves.length)]!; - engine.move(state, move, state.seatOwner[currentSeat(state)!]!); - return true; -} - -function play(count: number): void { - for (let i = 0; i < count && randomMove(); i++) {} - sync(); -} - -const bar = document.getElementById("dev")!; -const status = document.createElement("span"); -const button = (label: string, action: () => void) => { - const b = document.createElement("button"); - b.textContent = label; - b.addEventListener("click", action); - bar.append(b); -}; -button("Random move", () => play(1)); -button("10 moves", () => play(10)); -button("100 moves", () => play(100)); -function nextMerger(): void { - // Plays random moves until someone faces a merger decision (survivor, order or disposal). - for (let i = 0; i < 2000 && !["survivor", "defunctOrder", "dispose"].includes(state.phase) && randomMove(); i++) {} -} -button("Next merger", () => { - nextMerger(); - sync(); -}); -button("Announce", () => { - const move = legalMoves(state).find((m) => m.type === "announce"); - if (move) { + let rng = 1; + function randomMove(): boolean { + if (state.ended) { + return false; + } + const moves = legalMoves(state).filter((move) => move.type !== "announce"); + rng = (Math.imul(rng, 1103515245) + 12345) >>> 0; + const move = (moves.length > 0 ? moves : legalMoves(state))[rng % Math.max(1, moves.length)]!; engine.move(state, move, state.seatOwner[currentSeat(state)!]!); + return true; + } + + function play(count: number): void { + for (let i = 0; i < count && randomMove(); i++) {} sync(); } -}); -button("Restart", () => { - state = engine.init(players, [], options, seed); - NAMES.slice(0, players).forEach((name, player) => engine.setPlayerMetaData(state, player, { name })); - sync(); -}); -const select = document.createElement("select"); -for (let p = 0; p < players; p++) { - select.append(new Option(`View as ${NAMES[p]}`, String(p))); -} -select.append(new Option("Spectator", "")); -select.value = viewAs === undefined ? "" : String(viewAs); -select.addEventListener("change", () => { - viewAs = select.value === "" ? undefined : Number(select.value); - sync(); -}); -const hot = document.createElement("label"); -const hotBox = document.createElement("input"); -hotBox.type = "checkbox"; -hotBox.checked = hotSeat; -hotBox.addEventListener("change", () => { - hotSeat = hotBox.checked; - sync(); -}); -hot.append(hotBox, " Hot seat (view as whoever must act)"); -// The shared BGS colour-blind preference, sent the way BGS sends preferences. -const blind = document.createElement("label"); -const blindBox = document.createElement("input"); -blindBox.type = "checkbox"; -blindBox.checked = params.get("colorBlind") === "1"; -// Player appearance as BGS sends it: host-resolved colours, symbols and Supporter flags in player -// order, plus avatars. Avatars are neutral silhouettes and the badge is served by the dev server, -// so the dev page needs no network. BGS requires the badge URL to be http(s). -const COLORS = ["#4595d1", "#e68b32", "#8a5cc2", "#3aa35b", "#d14545", "#7a7a7a"]; -const SYMBOLS = ["circle", "triangle", "square", "diamond", "plus", "star"] as const; -const svg = (body: string) => - `data:image/svg+xml,${encodeURIComponent(`${body}`)}`; -const avatars = NAMES.slice(0, players).map(() => - svg( - `` - ) -); -const appearance = { - players: NAMES.slice(0, players).map((_, i) => ({ pro: i === 1 })), - supporterBadge: { url: `${location.origin}/dev-badge.svg`, label: "Supporter" }, - playerColors: COLORS.slice(0, players), - playerSymbols: [...SYMBOLS.slice(0, players)], -}; -// The BGS interface language, sent as preferences.locale. -const language = document.createElement("select"); -language.append(...LOCALES.map((locale) => new Option(`Language: ${locale}`, locale))); -language.value = params.get("locale") ?? "en"; -language.addEventListener("change", () => { - const url = new URL(location.href); - url.searchParams.set("locale", language.value); - history.replaceState(null, "", url); + + const bar = document.getElementById("dev")!; + const status = document.createElement("span"); + const button = (label: string, action: () => void) => { + const b = document.createElement("button"); + b.textContent = label; + b.addEventListener("click", action); + bar.append(b); + }; + button("Random move", () => play(1)); + button("10 moves", () => play(10)); + button("100 moves", () => play(100)); + function nextMerger(): void { + // Plays random moves until someone faces a merger decision (survivor, order or disposal). + for (let i = 0; i < 2000 && !["survivor", "defunctOrder", "dispose"].includes(state.phase) && randomMove(); i++) {} + } + button("Next merger", () => { + nextMerger(); + sync(); + }); + button("Announce", () => { + const move = legalMoves(state).find((m) => m.type === "announce"); + if (move) { + engine.move(state, move, state.seatOwner[currentSeat(state)!]!); + sync(); + } + }); + button("Restart", () => { + state = engine.init(players, [], options, seed); + NAMES.slice(0, players).forEach((name, player) => engine.setPlayerMetaData(state, player, { name })); + sync(); + }); + const select = document.createElement("select"); + for (let p = 0; p < players; p++) { + select.append(new Option(`View as ${NAMES[p]}`, String(p))); + } + select.append(new Option("Spectator", "")); + select.value = viewAs === undefined ? "" : String(viewAs); + select.addEventListener("change", () => { + viewAs = select.value === "" ? undefined : Number(select.value); + sync(); + }); + const hot = document.createElement("label"); + const hotBox = document.createElement("input"); + hotBox.type = "checkbox"; + hotBox.checked = hotSeat; + hotBox.addEventListener("change", () => { + hotSeat = hotBox.checked; + sync(); + }); + hot.append(hotBox, " Hot seat (view as whoever must act)"); + // The shared BGS colour-blind preference, sent the way BGS sends preferences. + const blind = document.createElement("label"); + const blindBox = document.createElement("input"); + blindBox.type = "checkbox"; + blindBox.checked = params.get("colorBlind") === "1"; + // Player appearance as BGS sends it: host-resolved colours, symbols and Supporter flags in player + // order, plus avatars. Avatars are neutral silhouettes and the badge is served by the dev server, + // so the dev page needs no network. BGS requires the badge URL to be http(s). + const COLORS = ["#4595d1", "#e68b32", "#8a5cc2", "#3aa35b", "#d14545", "#7a7a7a"]; + const SYMBOLS = ["circle", "triangle", "square", "diamond", "plus", "star"] as const; + const svg = (body: string) => + `data:image/svg+xml,${encodeURIComponent(`${body}`)}`; + const avatars = NAMES.slice(0, players).map(() => + svg( + `` + ) + ); + const appearance = { + players: NAMES.slice(0, players).map((_, i) => ({ pro: i === 1 })), + supporterBadge: { url: `${location.origin}/dev-badge.svg`, label: "Supporter" }, + playerColors: COLORS.slice(0, players), + playerSymbols: SYMBOLS.slice(0, players), + }; + // The BGS interface language, sent as preferences.locale. + const language = document.createElement("select"); + language.append(...LOCALES.map((locale) => new Option(`Language: ${locale}`, locale))); + language.value = params.get("locale") ?? "en"; + language.addEventListener("change", () => { + const url = new URL(location.href); + url.searchParams.set("locale", language.value); + history.replaceState(null, "", url); + sendPreferences(); + }); + const sendPreferences = () => + emitter.emit("preferences", { colorBlind: blindBox.checked, bgs: appearance, locale: language.value }); + emitter.emit("avatars", avatars); + blindBox.addEventListener("change", sendPreferences); + blind.append(blindBox, " Colour-blind mode"); + // Theme as BGS would send it. "Not sent" leaves the viewer on its prefers-color-scheme fallback, + // which can only be restored by reloading, as in BGS before the first theme event. + const theme = document.createElement("select"); + theme.append( + new Option("Theme: not sent (system)", ""), + new Option("Theme: BGS light", "light"), + new Option("Theme: BGS dark", "dark") + ); + theme.value = params.get("theme") ?? ""; + function applyTheme(): void { + if (theme.value) { + emitter.emit("theme", { dark: theme.value === "dark" }); + document.documentElement.style.colorScheme = theme.value; + } + } + theme.addEventListener("change", () => { + const url = new URL(location.href); + url.searchParams.set("theme", theme.value); + history.replaceState(null, "", url); + if (theme.value) { + applyTheme(); + } else { + location.reload(); + } + }); + // BGS replay controls: the viewer answers with replay:info, which drives the step buttons. + let replayInfo: { start: number; current: number; end: number } | undefined; + const replayLabel = document.createElement("span"); + emitter.on("replay:info", (info) => { + replayInfo = info; + replayLabel.textContent = ` replay ${info.current}/${info.end}`; + }); + button("Replay", () => emitter.emit("replay:start")); + button("◀", () => replayInfo && emitter.emit("replay:to", Math.max(replayInfo.start, replayInfo.current - 10))); + button("▶", () => replayInfo && emitter.emit("replay:to", Math.min(replayInfo.end, replayInfo.current + 10))); + button("Live", () => { + replayInfo = undefined; + replayLabel.textContent = ""; + emitter.emit("replay:end"); + }); + bar.append(select, theme, language, hot, blind, replayLabel, status); + + // For poking at positions from the browser console: window.acquireDev.load(state). + (window as unknown as { acquireDev: unknown }).acquireDev = { + rules, + engine, + emitter, + viewer, + get state() { + return state; + }, + load(next: GameState) { + state = next; + sync(); + }, + }; + + // Chat as BGS would run it: a short history, permission to send, and every accepted message + // echoed back through chat:appended with an acknowledgement. + let chatId = 0; + const chatMessage = (author: string, text: string, playerIndex?: number) => ({ + _id: (++chatId).toString(16).padStart(24, "0"), + author, + text, + type: "text" as const, + createdAt: new Date().toISOString(), + ...(playerIndex === undefined ? {} : { playerIndex }), + segments: [{ kind: "text" as const, text }], + }); + emitter.emit("chat:state", { canSend: true }); + emitter.emit("chat:messages", [ + chatMessage("Bo", "Good luck everyone", 1), + chatMessage("Cy", "Watch out for Tower", 2), + ]); + emitter.on("chat:send", ({ text, requestId }) => { + emitter.emit("chat:appended", [chatMessage(NAMES[viewAs ?? 0] ?? "You", text, viewAs)]); + if (requestId) { + emitter.emit("chat:result", { requestId, ok: true }); + } + }); + + for (let i = 0; i < Number(params.get("moves") ?? 0) && randomMove(); i++) {} + if (params.get("merger") === "1") { + nextMerger(); + } + if (params.get("bar") === "0") { + bar.style.display = "none"; + } + emitter.on("fetchState", sync); + applyTheme(); sendPreferences(); -}); -const sendPreferences = () => - emitter.emit("preferences", { colorBlind: blindBox.checked, bgs: appearance, locale: language.value }); -emitter.emit("avatars", avatars); -blindBox.addEventListener("change", sendPreferences); -blind.append(blindBox, " Colour-blind mode"); -// Theme as BGS would send it. "Not sent" leaves the viewer on its prefers-color-scheme fallback, -// which can only be restored by reloading, as in BGS before the first theme event. -const theme = document.createElement("select"); -theme.append( - new Option("Theme: not sent (system)", ""), - new Option("Theme: BGS light", "light"), - new Option("Theme: BGS dark", "dark") -); -theme.value = params.get("theme") ?? ""; -function applyTheme(): void { - if (theme.value) { - emitter.emit("theme", { dark: theme.value === "dark" }); - document.documentElement.style.colorScheme = theme.value; - } + emitter.on("move", (move) => { + if (viewAs !== undefined) { + engine.move(state, structuredClone(move), viewAs); + sync(); + } + }); + sync(); } -theme.addEventListener("change", () => { - const url = new URL(location.href); - url.searchParams.set("theme", theme.value); - history.replaceState(null, "", url); - if (theme.value) { - applyTheme(); - } else { - location.reload(); - } -}); -// BGS replay controls: the viewer answers with replay:info, which drives the step buttons. -let replayInfo: { start: number; current: number; end: number } | undefined; -const replayLabel = document.createElement("span"); -emitter.on("replay:info", (info) => { - replayInfo = info; - replayLabel.textContent = ` replay ${info.current}/${info.end}`; -}); -button("Replay", () => emitter.emit("replay:start")); -button("◀", () => replayInfo && emitter.emit("replay:to", Math.max(replayInfo.start, replayInfo.current - 10))); -button("▶", () => replayInfo && emitter.emit("replay:to", Math.min(replayInfo.end, replayInfo.current + 10))); -button("Live", () => { - replayInfo = undefined; - replayLabel.textContent = ""; - emitter.emit("replay:end"); -}); -bar.append(select, theme, language, hot, blind, replayLabel, status); - -// For poking at positions from the browser console: window.acquireDev.load(state). -(window as unknown as { acquireDev: unknown }).acquireDev = { - rules, - engine, - get state() { - return state; - }, - load(next: GameState) { - state = next; - sync(); - }, -}; - -// Chat as BGS would run it: a short history, permission to send, and every accepted message -// echoed back through chat:appended with an acknowledgement. -let chatId = 0; -const chatMessage = (author: string, text: string, playerIndex?: number) => ({ - _id: (++chatId).toString(16).padStart(24, "0"), - author, - text, - type: "text" as const, - createdAt: new Date().toISOString(), - ...(playerIndex === undefined ? {} : { playerIndex }), - segments: [{ kind: "text" as const, text }], -}); -emitter.emit("chat:state", { canSend: true }); -emitter.emit("chat:messages", [ - chatMessage("Bo", "Good luck everyone", 1), - chatMessage("Cy", "Watch out for Tower", 2), -]); -emitter.on("chat:send", ({ text, requestId }) => { - emitter.emit("chat:appended", [chatMessage(NAMES[viewAs ?? 0] ?? "You", text, viewAs)]); - if (requestId) { - emitter.emit("chat:result", { requestId, ok: true }); - } -}); - -for (let i = 0; i < Number(params.get("moves") ?? 0) && randomMove(); i++) {} -if (params.get("merger") === "1") { - nextMerger(); -} -if (params.get("bar") === "0") { - bar.style.display = "none"; -} -emitter.on("fetchState", sync); -applyTheme(); -sendPreferences(); -emitter.on("move", (move) => { - if (viewAs !== undefined) { - engine.move(state, move, viewAs); - sync(); - } -}); -sync(); diff --git a/packages/viewer/src/lib/ChainTable.svelte b/packages/viewer/src/lib/ChainTable.svelte index 5452b91..c0e620b 100644 --- a/packages/viewer/src/lib/ChainTable.svelte +++ b/packages/viewer/src/lib/ChainTable.svelte @@ -18,34 +18,36 @@

{t("chains.title")}

- - - - - - - - {#if seats.length > 0}{/if} - - - - {#each rows as row (row.chain)} - - - - - - {#if seats.length > 0}{/if} +
+
{t("chains.chain")}{t("chains.size")}{t("chains.price")}{t("chains.bank")}{t("chains.yours")}
- {#if row.size === 0} - {t("chains.notOnBoard")} - {:else} - {row.size}{#if row.size >= SAFE_SIZE}{t("chains.safe")}{/if} - {/if} - {row.price === undefined ? "" : store.lang.money(row.price)}{store.lang.count(row.bank)}{row.held}
+ + + + + + + {#if seats.length > 0}{/if} - {/each} - -
{t("chains.chain")}{t("chains.size")}{t("chains.price")}{t("chains.bank")}{t("chains.yours")}
+ + + {#each rows as row (row.chain)} + + + + {#if row.size === 0} + {t("chains.notOnBoard")} + {:else} + {row.size}{#if row.size >= SAFE_SIZE}{t("chains.safe")}{/if} + {/if} + + {row.price === undefined ? "" : store.lang.money(row.price)} + {store.lang.count(row.bank)} + {#if seats.length > 0}{row.held}{/if} + + {/each} + + +
diff --git a/packages/viewer/src/tutorial/lessons.spec.ts b/packages/viewer/src/tutorial/lessons.spec.ts new file mode 100644 index 0000000..cac93b7 --- /dev/null +++ b/packages/viewer/src/tutorial/lessons.spec.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createTutorial } from "@boardgamers/protocol/tutorial"; +import { allTiles, CHAIN_IDS, viewFor, HIDDEN, type Move } from "acquire-engine"; +import { CHAPTERS, lesson, preparedPosition, type Chapter } from "./lessons.ts"; +import { LOCALES } from "../lib/i18n.ts"; + +const solutions: Record = { + founding: [ + { type: "place", tile: "2A" }, + { type: "found", chain: "tower" }, + { type: "buy", shares: { tower: 2 } }, + ], + mergers: [ + { type: "place", tile: "4A" }, + { type: "dispose", sell: 1, trade: 2 }, + { type: "buy", shares: {} }, + ], + scoring: [{ type: "announce" }, { type: "place", tile: "12A" }, { type: "buy", shares: {} }], +}; + +for (const chapter of CHAPTERS) { + test(`${chapter}: prepared position conserves tiles and shares and hides opponents' hands`, () => { + const state = preparedPosition(chapter); + const tiles = [ + ...state.pool, + ...state.seats.flatMap((seat) => seat.hand), + ...allTiles().filter((tile) => state.board[tile] !== null), + ]; + assert.equal(tiles.length, 108); + assert.equal(new Set(tiles).size, 108); + for (const chain of CHAIN_IDS) { + assert.equal(state.bank[chain] + state.seats.reduce((sum, seat) => sum + seat.shares[chain], 0), 25); + } + const shown = viewFor(state, 0); + assert.ok(shown.seats[1]!.hand.every((tile) => tile === HIDDEN)); + assert.equal(shown.seats[1]!.cash, HIDDEN); + }); + test(`${chapter}: all languages finish, persist, retry and replay with the real engine`, async () => { + for (const locale of LOCALES) { + const saved = new Map(); + const storage = { + getItem: (key: string) => saved.get(key) ?? null, + setItem: (key: string, value: string) => { + saved.set(key, value); + }, + }; + const options = { ...lesson(chapter, locale), storage }; + const controller = await createTutorial(options); + const first = solutions[chapter][0]!; + assert.equal(await controller.play(first), true); + const afterFirst = structuredClone(controller.snapshot.state); + await controller.previousStep(); + assert.equal(controller.snapshot.step, 0); + assert.equal(await controller.play(first), true); + assert.deepEqual(controller.snapshot.state, afterFirst); + await controller.restartStep(); + assert.equal(controller.snapshot.step, 1); + const resumed = await createTutorial(options); + assert.deepEqual(resumed.snapshot.state, controller.snapshot.state); + controller.destroy(); + for (const move of solutions[chapter].slice(1)) { + assert.equal(await resumed.play(move), true, resumed.snapshot.error); + } + assert.equal(resumed.snapshot.completed, true); + const state = resumed.snapshot.state; + if (chapter === "founding") { + assert.equal(state.seats[0]!.cash, 5600); + assert.equal(state.seats[0]!.shares.tower, 3); + } + if (chapter === "mergers") { + assert.equal(state.seats[0]!.cash, 8200); + assert.equal(state.seats[0]!.shares.tower, 1); + assert.equal(state.seats[0]!.shares.luxor, 0); + } + if (chapter === "scoring") { + assert.equal(state.ended, true); + assert.deepEqual( + state.seats.map((seat) => seat.cash), + [15800, 10900, 6700] + ); + } + const finished = await createTutorial(options); + assert.equal(finished.snapshot.completed, true); + assert.deepEqual(finished.snapshot.state, state); + await finished.restart(); + assert.equal(finished.snapshot.step, 0); + resumed.destroy(); + finished.destroy(); + } + }); +} + +test("tutorial rejects an unrelated move without changing the state or advancing", async () => { + const controller = await createTutorial(lesson("founding", "fr")); + const before = structuredClone(controller.snapshot.state); + assert.equal(await controller.play({ type: "buy", shares: {} }), false); + assert.equal(controller.snapshot.step, 0); + assert.deepEqual(controller.snapshot.state, before); + assert.match(controller.snapshot.error, /Sélectionnez 2A/); + controller.destroy(); +}); diff --git a/packages/viewer/src/tutorial/lessons.ts b/packages/viewer/src/tutorial/lessons.ts new file mode 100644 index 0000000..77858d2 --- /dev/null +++ b/packages/viewer/src/tutorial/lessons.ts @@ -0,0 +1,117 @@ +import type { TutorialOptions, TutorialStep } from "@boardgamers/protocol/tutorial"; +import { + allTiles, + applyMove, + CHAIN_IDS, + currentSeat, + initGame, + parseTile, + type GameState, + type Move, + type Shares, +} from "acquire-engine"; +import { langFor, type Lang } from "../lib/format.ts"; +import type { Locale, MessageKey } from "../lib/i18n.ts"; + +export const CHAPTERS = ["founding", "mergers", "scoring"] as const; +export type Chapter = (typeof CHAPTERS)[number]; +const tile = (label: string) => parseTile(label)!; + +export function preparedPosition(chapter: Chapter): GameState { + const game = initGame(3, {}, `acquire-tutorial-${chapter}-1`); + game.board.fill(null); + game.activeSeat = 0; + game.phase = "place"; + game.turn = 1; + game.log = [{ type: "turn", seat: 0 }]; + game.seats.forEach((seat, index) => { + seat.name = ["Alex", "Bo", "Cy"][index]!; + seat.hand = [tile(["2A", "12I", "10I"][index]!)]; + for (const chain of CHAIN_IDS) { + seat.shares[chain] = 0; + } + }); + if (chapter === "founding") { + game.board[tile("1A")] = "loose"; + } else if (chapter === "mergers") { + for (const label of ["1A", "2A", "3A"]) { + game.board[tile(label)] = "tower"; + } + for (const label of ["5A", "6A"]) { + game.board[tile(label)] = "luxor"; + } + game.seats[0]!.hand = [tile("4A")]; + game.seats.forEach((seat, index) => { + seat.shares.luxor = [3, 2, 1][index]!; + }); + } else { + for (let column = 1; column <= 11; column++) { + game.board[tile(`${column}A`)] = "tower"; + } + game.seats[0]!.hand = [tile("12A")]; + game.seats.forEach((seat, index) => { + seat.shares.tower = [4, 2, 1][index]!; + }); + } + for (const chain of CHAIN_IDS) { + game.bank[chain] = 25 - game.seats.reduce((sum, seat) => sum + seat.shares[chain], 0); + } + const held = new Set(game.seats.flatMap((seat) => seat.hand)); + game.pool = allTiles().filter((entry) => game.board[entry] === null && !held.has(entry)); + return game; +} + +function step( + lang: Lang, + chapter: Chapter, + index: number, + accept: (move: Move) => boolean +): TutorialStep { + const text = lang.t(`tutorial.${chapter}.${index}` as MessageKey); + return { + id: `${chapter}-${index}`, + title: lang.t(`tutorial.${chapter}.title`), + text, + complete: () => true, + validateMove: (_state, move) => (accept(move) ? undefined : text), + }; +} +const buy = (shares: Partial, move: Move) => + move.type === "buy" && CHAIN_IDS.every((chain) => (move.shares[chain] ?? 0) === (shares[chain] ?? 0)); + +export function lesson(chapter: Chapter, locale: Locale): TutorialOptions { + const lang = langFor(locale); + const steps = + chapter === "founding" + ? [ + step(lang, chapter, 0, (move) => move.type === "place" && move.tile === "2A"), + step(lang, chapter, 1, (move) => move.type === "found" && move.chain === "tower"), + step(lang, chapter, 2, (move) => buy({ tower: 2 }, move)), + ] + : chapter === "mergers" + ? [ + step(lang, chapter, 0, (move) => move.type === "place" && move.tile === "4A"), + step(lang, chapter, 1, (move) => move.type === "dispose" && move.sell === 1 && move.trade === 2), + step(lang, chapter, 2, (move) => buy({}, move)), + ] + : [ + step(lang, chapter, 0, (move) => move.type === "announce"), + step(lang, chapter, 1, (move) => move.type === "place" && move.tile === "12A"), + step(lang, chapter, 2, (move) => buy({}, move)), + ]; + return { + game: "acquire", + id: chapter, + version: 1, + initialState: () => preparedPosition(chapter), + move(state, move) { + applyMove(state, move, 0); + while (state.phase === "dispose" && currentSeat(state) !== 0) { + applyMove(state, { type: "dispose", sell: 0, trade: 0 }, currentSeat(state)!); + } + return state; + }, + steps, + completion: { title: lang.t("tutorial.complete"), text: lang.t(`tutorial.${chapter}.done`) }, + }; +} diff --git a/packages/viewer/src/tutorial/mount.svelte.ts b/packages/viewer/src/tutorial/mount.svelte.ts new file mode 100644 index 0000000..7963fb6 --- /dev/null +++ b/packages/viewer/src/tutorial/mount.svelte.ts @@ -0,0 +1,91 @@ +import { mount, tick, unmount } from "svelte"; +import { createTutorial, type TutorialMount } from "@boardgamers/protocol/tutorial"; +import { stripSecret } from "acquire-engine/wrapper"; +import App from "../App.svelte"; +import { isRightToLeft, resolveLocale } from "../lib/i18n"; +import { initialTheme, themeCss } from "../lib/palette"; +import { STORE, ViewerStore } from "../lib/store.svelte"; +import { CHAPTERS, lesson, type Chapter } from "./lessons"; +import Guide from "./Guide.svelte"; +import "./tutorial.css"; + +export const mountTutorial: TutorialMount = async (target, options) => { + if (!CHAPTERS.includes(options.chapter as Chapter)) { + throw new Error("Unknown Acquire tutorial"); + } + const locale = resolveLocale(options.locale); + let storage: Storage | undefined; + try { + storage = localStorage; + } catch { + storage = undefined; + } + const controller = await createTutorial({ + ...lesson(options.chapter as Chapter, locale), + storage, + onProgress: options.onProgress, + }); + const style = document.createElement("style"); + style.textContent = themeCss(); + document.head.append(style); + const wrapper = document.createElement("div"); + wrapper.className = "acquire acquire-tutorial"; + wrapper.lang = locale; + wrapper.dir = isRightToLeft(locale) ? "rtl" : "ltr"; + const guideHost = document.createElement("div"); + guideHost.className = "tutorial-top"; + const gameHost = document.createElement("div"); + wrapper.append(guideHost, gameHost); + target.append(wrapper); + const store = new ViewerStore((move) => { + void controller.play(move); + return true; + }); + store.player = 0; + store.locale = locale; + store.analysis = true; + store.theme = initialTheme(); + wrapper.dataset.theme = store.theme; + store.setState(stripSecret(controller.snapshot.state, 0)); + let snapshot = $state(controller.snapshot); + const guide = mount(Guide, { + target: guideHost, + props: { + get snapshot() { + return snapshot; + }, + controller, + lang: store.lang, + nextChapter: options.nextChapter, + }, + }); + const app = mount(App, { target: gameHost, props: { store }, context: new Map([[STORE, store]]) }); + const unsubscribe = controller.subscribe((value) => { + snapshot = value; + wrapper.dataset.step = String(value.step); + wrapper.dataset.completed = String(value.completed); + options.nextChapter?.onVisibilityChange?.(value.completed); + gameHost.inert = value.busy || value.completed; + if (!value.busy) { + store.setState(stripSecret(value.state, 0)); + } + }); + const media = matchMedia("(prefers-color-scheme: dark)"); + const theme = () => { + store.theme = media.matches ? "dark" : "light"; + wrapper.dataset.theme = store.theme; + }; + media.addEventListener("change", theme); + await tick(); + return () => { + options.nextChapter?.onVisibilityChange?.(false); + media.removeEventListener("change", theme); + unsubscribe(); + controller.destroy(); + store.chat.destroy(); + style.remove(); + void unmount(guide); + void unmount(app); + wrapper.remove(); + }; +}; diff --git a/packages/viewer/src/tutorial/tutorial.css b/packages/viewer/src/tutorial/tutorial.css new file mode 100644 index 0000000..5f413ee --- /dev/null +++ b/packages/viewer/src/tutorial/tutorial.css @@ -0,0 +1,14 @@ +.acquire-tutorial { + padding: 0; + min-height: 100vh; +} +.acquire-tutorial .tutorial-top { + position: sticky; + top: 0; + z-index: 5; +} +@media (max-width: 699px) { + .acquire-tutorial .tutorial-top { + position: static; + } +} diff --git a/packages/viewer/src/viewer.ts b/packages/viewer/src/viewer.ts index 8f48cbb..c309a83 100644 --- a/packages/viewer/src/viewer.ts +++ b/packages/viewer/src/viewer.ts @@ -6,56 +6,61 @@ import { resolveLocale } from "./lib/i18n"; import { initialTheme, themeCss } from "./lib/palette"; import { STORE, ViewerStore } from "./lib/store.svelte"; import "./lib/theme.css"; +import { mountTutorial } from "./tutorial/mount.svelte"; -export const viewer = registerViewer("acquire", ({ target, move, setReplayInfo }) => { - const style = document.createElement("style"); - style.textContent = themeCss(); - document.head.append(style); - const store = new ViewerStore(move); - store.theme = initialTheme(); - const app = mount(App, { target, props: { store }, context: new Map([[STORE, store]]) }); - return { - chat: store.chat, - async onState(state) { - store.setState(state); - await tick(); - }, - onPlayer({ index }) { - store.player = index; - }, - onPreferences(preferences) { - store.colorBlind = preferences.colorBlind === true; - store.appearance = preferences.bgs; - store.analysis = preferences.analysis === true; - store.locale = resolveLocale(preferences.locale); - }, - onAvatars(avatars) { - store.avatars = avatars; - }, - onTheme({ dark }) { - store.theme = dark ? "dark" : "light"; - }, - onReplayStart() { - const { start, end } = store.replayRange(); - store.replayAt = end; - setReplayInfo({ start, current: end, end }); - }, - onReplayTo(index) { - const { start, end } = store.replayRange(); - store.replayAt = Math.min(end, Math.max(start, index)); - setReplayInfo({ start, current: store.replayAt, end }); - }, - onReplayEnd() { - store.replayAt = undefined; - }, - onMoveResult({ ok }) { - if (!ok) { - store.sending = false; - } - }, - destroy() { - style.remove(); - void unmount(app); - }, - }; -}); +export const viewer = registerViewer( + "acquire", + ({ target, move, setReplayInfo }) => { + const style = document.createElement("style"); + style.textContent = themeCss(); + document.head.append(style); + const store = new ViewerStore(move); + store.theme = initialTheme(); + const app = mount(App, { target, props: { store }, context: new Map([[STORE, store]]) }); + return { + chat: store.chat, + async onState(state) { + store.setState(state); + await tick(); + }, + onPlayer({ index }) { + store.player = index; + }, + onPreferences(preferences) { + store.colorBlind = preferences.colorBlind === true; + store.appearance = preferences.bgs; + store.analysis = preferences.analysis === true; + store.locale = resolveLocale(preferences.locale); + }, + onAvatars(avatars) { + store.avatars = avatars; + }, + onTheme({ dark }) { + store.theme = dark ? "dark" : "light"; + }, + onReplayStart() { + const { start, end } = store.replayRange(); + store.replayAt = end; + setReplayInfo({ start, current: end, end }); + }, + onReplayTo(index) { + const { start, end } = store.replayRange(); + store.replayAt = Math.min(end, Math.max(start, index)); + setReplayInfo({ start, current: store.replayAt, end }); + }, + onReplayEnd() { + store.replayAt = undefined; + }, + onMoveResult({ ok }) { + if (!ok) { + store.sending = false; + } + }, + destroy() { + style.remove(); + void unmount(app); + }, + }; + }, + { tutorial: mountTutorial } +); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dd890c2..9915a75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -14,6 +14,9 @@ importers: oxlint: specifier: 1.76.0 version: 1.76.0 + playwright: + specifier: 1.62.1 + version: 1.62.1 svelte: specifier: 5.56.8 version: 5.56.8 @@ -512,6 +515,11 @@ packages: picomatch: optional: true + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -646,6 +654,16 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + playwright-core@1.62.1: + resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.62.1: + resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==} + engines: {node: '>=20'} + hasBin: true + postcss@8.5.31: resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} engines: {node: ^10 || ^12 || >=14} @@ -996,6 +1014,9 @@ snapshots: optionalDependencies: picomatch: 4.0.7 + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true @@ -1115,6 +1136,14 @@ snapshots: picomatch@4.0.7: {} + playwright-core@1.62.1: {} + + playwright@1.62.1: + dependencies: + playwright-core: 1.62.1 + optionalDependencies: + fsevents: 2.3.2 + postcss@8.5.31: dependencies: nanoid: 3.3.20 diff --git a/scripts/check-browser.mjs b/scripts/check-browser.mjs new file mode 100644 index 0000000..e198580 --- /dev/null +++ b/scripts/check-browser.mjs @@ -0,0 +1,265 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import { chromium } from "playwright"; + +const base = process.env.ACQUIRE_TEST_URL ?? "http://127.0.0.1:5191"; +const server = process.env.ACQUIRE_TEST_URL + ? undefined + : spawn( + "pnpm", + ["--filter", "acquire-viewer", "exec", "vite", "--host", "127.0.0.1", "--port", "5191", "--strictPort"], + { + stdio: "pipe", + detached: process.platform !== "win32", + } + ); +let serverOutput = ""; +server?.stdout.on("data", (data) => (serverOutput += data)); +server?.stderr.on("data", (data) => (serverOutput += data)); +let browser; +const errors = []; +const locales = [ + "en", + "de", + "fr", + "pl", + "ro", + "el", + "hi", + "ru", + "da", + "pt-BR", + "ko", + "zh-TW", + "zh-CN", + "vi", + "it", + "nl", + "fa", +]; +const output = new URL("../release/qa/", import.meta.url); +await mkdir(output, { recursive: true }); +const report = { layouts: [], diagnostics: null, scenarios: [] }; + +try { + for (let attempt = 0; ; attempt++) { + if (server && server.exitCode !== null) { + throw new Error(serverOutput); + } + if ( + await fetch(base) + .then((r) => r.ok) + .catch(() => false) + ) { + break; + } + if (attempt >= 100) { + throw new Error(`Dev server did not start: ${serverOutput}`); + } + await delay(100); + } + browser = await chromium.launch({ headless: true }); + const page = await browser.newPage({ viewport: { width: 1280, height: 900 }, hasTouch: true }); + page.on("pageerror", (error) => errors.push(error.message)); + const settle = async () => + page.evaluate(() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))); + const open = async (params = "") => { + await page.goto(`${base}/?bundle=1&seed=bgs&bar=0&${params}`); + await page.waitForSelector("main .board"); + await settle(); + }; + const preferences = async (value) => { + await page.evaluate((prefs) => window.acquireDev.emitter.emit("preferences", prefs), value); + await settle(); + }; + await open("players=4&moves=50&merger=1&theme=light"); + report.diagnostics = await page.evaluate(() => window.acquireDev.viewer.diagnostics(["core", "chat", "replay"])); + assert.equal(report.diagnostics.compatible, true); + assert.equal(report.diagnostics.recommended.percent, 100); + + for (const [width, height] of [ + [1280, 900], + [390, 844], + [320, 700], + [844, 390], + ]) { + await page.setViewportSize({ width, height }); + for (const locale of locales) { + await preferences({ locale, colorBlind: true }); + assert.equal(await page.locator("main").getAttribute("lang"), locale); + assert.equal(await page.locator("main").getAttribute("dir"), locale === "fa" ? "rtl" : "ltr"); + const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth); + assert.ok(scrollWidth <= width + 1, `${locale} ${width}px: page overflow ${scrollWidth}`); + assert.ok((await page.locator(".player .symbol").count()) >= 4, "default color-blind player symbols"); + report.layouts.push({ width, height, locale, scrollWidth }); + } + } + report.scenarios.push("17 live languages at four viewport sizes, touch controls, RTL and default player symbols"); + + await page.setViewportSize({ width: 390, height: 844 }); + await preferences({ locale: "fr", colorBlind: true }); + await page.evaluate(() => window.acquireDev.emitter.emit("chat:state", { canSend: false, reason: "not-a-player" })); + await settle(); + assert.match(await page.locator(".chat-status").innerText(), /Seuls les joueurs/); + await preferences({ locale: "de", colorBlind: true }); + assert.match(await page.locator(".chat-status").innerText(), /Nur Spieler/); + await page.evaluate(() => window.acquireDev.emitter.emit("chat:state", { canSend: true })); + await preferences({ locale: "en" }); + await page.locator(".chat-composer input").fill("Private beta smoke test"); + await page.locator(".chat-composer button").click(); + await page.waitForFunction(() => + document.querySelector(".chat-messages")?.textContent.includes("Private beta smoke test") + ); + await preferences({ locale: "en", analysis: true }); + assert.equal(await page.locator(".chat").count(), 0); + await preferences({ locale: "en", analysis: false }); + assert.equal(await page.locator(".chat").count(), 1); + report.scenarios.push("chat send acknowledgement, localized permissions, live language change, analysis hides chat"); + + for (const mode of ["players=6", "players=2&twoPlayerMode=fourHands"]) { + await open(`${mode}&moves=35&hotseat=0&view=0`); + const count = mode.startsWith("players=6") ? 6 : 2; + for (let player = 0; player <= count; player++) { + const view = player === count ? null : player; + await page.evaluate((viewer) => { + const dev = window.acquireDev; + const index = viewer ?? undefined; + dev.emitter.emit("player", { index }); + dev.emitter.emit("state", dev.engine.stripSecret(structuredClone(dev.state), index)); + }, view); + await settle(); + const hands = view === null ? 0 : count === 2 ? 2 : 1; + assert.equal(await page.locator("section.hand").count(), hands); + const liveBoard = await page.locator("main .board").first().innerText(); + await page.evaluate(() => { + const emitter = window.acquireDev.emitter; + emitter.emit("replay:start"); + emitter.emit("replay:to", 0); + }); + await settle(); + assert.equal(await page.locator("section.hand").count(), 0); + assert.equal(await page.locator(".panel button").count(), 0); + assert.notEqual(await page.locator("main .board").first().innerText(), liveBoard); + await page.evaluate(() => window.acquireDev.emitter.emit("replay:end")); + await settle(); + assert.equal(await page.locator("main .board").first().innerText(), liveBoard); + assert.equal(await page.locator("section.hand").count(), hands); + } + } + report.scenarios.push("every six-player and four-hands seat plus spectators: replay navigation and live return"); + + await open("players=4&theme=light"); + const before = await page.evaluate(() => window.acquireDev.state.log.length); + await page.locator("section.hand button").first().click(); + await page + .locator(".panel") + .getByRole("button", { name: /^Place / }) + .click(); + await page.waitForFunction((length) => window.acquireDev.state.log.length > length, before); + await settle(); + assert.equal(await page.getByText("Sending…", { exact: true }).count(), 0); + const after = await page.locator("main .board").first().innerText(); + await page.evaluate(() => window.acquireDev.emitter.emit("state:updated")); + await settle(); + assert.equal(await page.locator("main .board").first().innerText(), after); + report.scenarios.push("real tile move through the built viewer and state refresh"); + + for (const [name, params, width, height] of [ + ["overview", "players=4&moves=95&publicHoldings=1", 1280, 900], + ["merger", "players=4&moves=50&merger=1&publicHoldings=1", 1280, 900], + ["phone", "players=4&moves=50&merger=1&publicHoldings=1", 390, 844], + ]) { + await page.setViewportSize({ width, height }); + for (const theme of ["light", "dark"]) { + await open(`${params}&theme=${theme}`); + await page.screenshot({ path: new URL(`${name}-${theme}.png`, output).pathname, fullPage: true }); + } + } + await preferences({ locale: "fa", colorBlind: true }); + await page.screenshot({ path: new URL("phone-fa.png", output).pathname, fullPage: true }); + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 900 }); + for (const chapter of ["founding", "mergers", "scoring"]) { + await page.evaluate((id) => localStorage.removeItem(`bgs:tutorial:acquire:${id}`), chapter); + await page.goto(`${base}/?bundle=1&tutorial=${chapter}&locale=en`); + await page.waitForSelector('.acquire-tutorial[data-step="0"]'); + assert.equal(await page.locator(".chat").count(), 0); + const place = async (tile) => { + await page.locator("section.hand").getByRole("button", { name: tile, exact: true }).click(); + await page + .locator(".panel") + .getByRole("button", { name: `Place ${tile}`, exact: true }) + .click(); + }; + if (chapter === "scoring") { + await page.getByRole("button", { name: "Announce the end…", exact: true }).click(); + await page.getByRole("button", { name: "Announce the end", exact: true }).click(); + } else { + await place(chapter === "founding" ? "2A" : "4A"); + } + await page.waitForSelector('.acquire-tutorial[data-step="1"]'); + await page.reload(); + await page.waitForSelector('.acquire-tutorial[data-step="1"]'); + await page.getByRole("button", { name: "Retry step", exact: true }).click(); + if (chapter === "founding") { + await page.locator(".choices button").filter({ hasText: "Luxor" }).click(); + await page.getByRole("alert").waitFor(); + await page.locator(".choices button").filter({ hasText: "Tower" }).click(); + } else if (chapter === "mergers") { + await page.getByRole("button", { name: "Sell one more", exact: true }).click(); + await page.getByRole("button", { name: "Trade two more", exact: true }).click(); + await page.locator("main .panel button.primary").click(); + } else { + await place("12A"); + } + await page.waitForSelector('.acquire-tutorial[data-step="2"]'); + if (chapter === "founding") { + await page.getByRole("button", { name: "Buy one more Tower", exact: true }).click(); + await page.getByRole("button", { name: "Buy one more Tower", exact: true }).click(); + } + await page.locator("main .panel button.primary").click(); + await page.waitForSelector('.acquire-tutorial[data-completed="true"]'); + if (chapter === "scoring") { + assert.match(await page.locator(".results").innerText(), /15,800/); + } + for (const locale of ["fr", "fa"]) { + await page.evaluate(async ({ chapter, locale }) => window.acquire.launchTutorial("#app", { chapter, locale }), { + chapter, + locale, + }); + await page.waitForSelector('.acquire-tutorial[data-completed="true"]'); + assert.equal(await page.locator(".acquire-tutorial").getAttribute("lang"), locale); + assert.equal(await page.locator("main").getAttribute("dir"), locale === "fa" ? "rtl" : "ltr"); + assert.ok( + await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), + `${chapter} ${locale} tutorial overflow` + ); + } + await page.screenshot({ path: new URL(`tutorial-${chapter}-${width}.png`, output).pathname, fullPage: true }); + } + } + report.scenarios.push( + "three tutorials completed through real controls on desktop and phone; reload, retry, rejected move, French/Persian resume and final scoring" + ); + + await page.evaluate(() => window.acquire.destroy()); + await settle(); + assert.equal(await page.locator("main").count(), 0); + assert.deepEqual(errors, []); + report.scenarios.push("light/dark production-bundle screenshots and clean viewer teardown"); + await writeFile(new URL("report.json", output), JSON.stringify(report, null, 2) + "\n"); + console.log( + `Browser checks passed: ${report.layouts.length} locale/viewport combinations; ${report.scenarios.length} integration scenarios.` + ); +} finally { + await browser?.close(); + if (server?.pid) { + if (process.platform === "win32") { + server.kill(); + } else { + process.kill(-server.pid, "SIGTERM"); + } + } +}