diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100644 index 0000000..8cc690e --- /dev/null +++ b/.githooks/pre-commit @@ -0,0 +1,7 @@ +#!/bin/sh +# Blocks the commit unless pnpm check passes. Enable with: git config core.hooksPath .githooks +cd "$(git rev-parse --show-toplevel)" || exit 1 +if ! pnpm check; then + echo "pre-commit: pnpm check failed; commit blocked." >&2 + exit 1 +fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2671b9a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +node_modules +dist +dist-test +.vite +.pnpm-store +*.local +*.tgz +release/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..5003ba8 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +24.2.0 diff --git a/.oxfmtrc.json b/.oxfmtrc.json new file mode 100644 index 0000000..e98905f --- /dev/null +++ b/.oxfmtrc.json @@ -0,0 +1,10 @@ +{ + "printWidth": 120, + "tabWidth": 2, + "useTabs": true, + "semi": true, + "singleQuote": false, + "trailingComma": "es5", + "svelte": true, + "ignorePatterns": ["**/dist/**", "**/dist-test/**", "**/node_modules/**", "release/**", "pnpm-lock.yaml", "rules.md"] +} diff --git a/.oxlintrc.json b/.oxlintrc.json new file mode 100644 index 0000000..e8333dd --- /dev/null +++ b/.oxlintrc.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/npm/oxlint/configuration_schema.json", + "rules": { + "curly": ["error", "all"] + }, + "ignorePatterns": ["**/dist/**", "**/dist-test/**", "**/node_modules/**", "release/**"] +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..49cc894 --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# Acquire for boardgamers.space + +An unofficial implementation of Sid Sackson's Acquire for [boardgamers.space](https://www.boardgamers.space), +for 2 to 6 players. Not affiliated with or endorsed by Hasbro, Avalon Hill, Renegade Game +Studios or any other publisher of Acquire. + +- `packages/engine`: the rules engine. `wrapper.ts` implements the BGS Engine API. +- `packages/viewer`: the Svelte viewer, built as one IIFE bundle for the BGS iframe. +- `rules.md`: the rules the engine follows. Tests cite its section numbers. +- `docs/registering.md`: how to publish the engine and viewer to BGS. +- `docs/admin/`: the text, pictogram and screenshots for the BGS admin panel. + +## Setup + +Requires Node 24 and pnpm 11 (`corepack enable pnpm` provides pnpm). + +```bash +pnpm install +pnpm check +``` + +`pnpm check` formats, lints, type-checks, runs the tests and builds both packages. To run it +before every commit, enable the hook with `git config core.hooksPath .githooks`. + +## Playing locally + +```bash +pnpm build +pnpm dev +``` + +Open http://localhost:5173. The test page runs the engine in the browser and shows the viewer +as each player sees it. With hot seat on, it switches to whoever must act, so one person can +play every seat. The toolbar plays random moves, jumps to the next merger, and switches +player, theme, language and colour-blind mode. + +URL parameters: `players=2..6`, `seed=...`, `publicHoldings=1`, `teamPlay=1`, `autoEnd=1`, +`endSize=31`, `twoPlayerMode=fourHands`, `theme=light|dark`, `locale=de`, `moves=50` (random +moves on load), `merger=1` (continue to the next merger). + +## What ships + +The test page (`packages/viewer/index.html`, `src/dev.ts`, `dev-badge.svg`) is never part of +what BGS runs, so nothing needs removing for live: + +- The viewer build bundles only `src/viewer.ts` and what it imports, into + `acquire-viewer.iife.js` and `acquire-viewer.css`. +- The engine package (`pnpm pack` in `packages/engine`) contains only `dist/` and + `package.json`. + +Each GitHub Release has the built engine package and viewer files attached, ready to upload. + +## Licence + +AGPL-3.0. See [LICENSE](LICENSE). diff --git a/docs/admin/README.md b/docs/admin/README.md new file mode 100644 index 0000000..a356a99 --- /dev/null +++ b/docs/admin/README.md @@ -0,0 +1,42 @@ +# Admin panel content + +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. | + +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. + +## Links + +- **bgg:** https://boardgamegeek.com/boardgame/5/acquire +- **source:** the public repository URL, once the repository is published (it has no remote yet). +- **publisher / purchase:** Renegade Game Studios' Acquire page, if you want one. Optional. + +## 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**. + +## Screenshots + +Captured from the dev page with a fixed seed (`seed=bgs`, 4 players, public holdings) at 2× scale. +Upload each light image and add the dark one with **Add dark version**. + +| Order | Light | Dark | Caption | +| ----- | ------------------ | ----------------- | -------------------------------------------------------------------------- | +| 1 | overview-light.png | overview-dark.png | Hotel chains grow across the board; Continental is already safe. | +| 2 | merger-light.png | merger-dark.png | A merger: sell, trade 2 for 1 or keep your shares of the chain taken over. | +| 3 | phone-light.png | phone-dark.png | The same decision on a phone. | + +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). diff --git a/docs/admin/credits.md b/docs/admin/credits.md new file mode 100644 index 0000000..516ff6e --- /dev/null +++ b/docs/admin/credits.md @@ -0,0 +1,3 @@ +**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. diff --git a/docs/admin/description.md b/docs/admin/description.md new file mode 100644 index 0000000..d70a29a --- /dev/null +++ b/docs/admin/description.md @@ -0,0 +1 @@ +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. diff --git a/docs/admin/pictogram.svg b/docs/admin/pictogram.svg new file mode 100644 index 0000000..cf6d4ee --- /dev/null +++ b/docs/admin/pictogram.svg @@ -0,0 +1,14 @@ + + Acquire + + + + + + + + + + + diff --git a/docs/admin/rules.md b/docs/admin/rules.md new file mode 100644 index 0000000..4352612 --- /dev/null +++ b/docs/admin/rules.md @@ -0,0 +1,111 @@ +## Goal + +Finish with the most money. You earn it by buying stock in hotel chains early, collecting bonuses when chains are taken over, and selling your stock at the end. + +## The board and the chains + +The board has 108 squares in 12 columns (1–12) and 9 rows (A–I). Each square has exactly one tile, named after it: tile **5C** can only go on square 5C. + +There are 7 hotel chains, in three price tiers: + +- **Minor:** Tower, Luxor +- **Medium:** Worldwide, American, Festival +- **Major:** Imperial, Continental + +Each chain has 25 shares. Everyone starts with $6,000 and a hand of 6 tiles. Before the game, each player places one tile from the pool; the lowest tile (by number, then letter) goes first, and play continues in seat order. + +A chain of 11 or more tiles is **safe**: it can never be taken over. + +## Your turn + +1. **Place one tile** from your hand. +2. **Buy up to 3 shares**, in any active chains (optional). +3. **Draw** back up to 6 tiles. + +### What a tile does + +- **Next to nothing:** it stays on the board as a loose tile. +- **Next to loose tiles only:** it founds a new chain. You pick any chain not on the board, and you get one free share of it. The chain takes in all connected loose tiles. +- **Next to one chain:** it joins that chain, along with any loose tiles it connects. +- **Next to two or more chains:** it causes a **merger** (below). + +### Tiles you can't play + +- A tile that would merge two safe chains can never be played. At the end of your turn it is swapped for a new one automatically. +- A tile that would found an 8th chain can't be played while all 7 chains are on the board. You keep it; it becomes playable when a chain disappears. +- If none of your tiles can be played, you skip placing and may still buy stock. + +## Mergers + +The **largest** chain survives and takes over the others. If chains tie for largest, the player who placed the tile chooses the survivor. Sizes are counted before the merging tile is placed. + +Each chain being taken over is settled in turn, largest first (the merging player breaks ties, choosing the whole order up front): + +1. **Bonuses.** The biggest shareholder gets the 1st bonus, the second biggest gets the 2nd bonus (see the price table). + - Only one shareholder: they get both bonuses. + - Tie for biggest: the 1st and 2nd bonuses are added together and split evenly among them; nobody else gets a bonus. + - Tie for second: the 2nd bonus is split evenly among them. + - Split amounts are rounded up to the next $100. +2. **Your shares.** Starting with the merging player and going round the table, everyone holding shares of that chain decides what to do with them, in any mix: + - **Sell** them to the bank at the chain's price. + - **Trade** them 2 for 1 for shares of the surviving chain, while the bank has some left. + - **Keep** them. They are worth nothing unless the chain is founded again later. + +Then the survivor absorbs all the tiles. The names of the chains taken over are free to be founded again. + +## Buying stock + +After placing, you may buy up to 3 shares in total, in one or more chains on the board. Prices depend on each chain's current size and stay fixed for the rest of your turn. You can't borrow, and you can't sell stock except in a merger or at the end. + +## Price table + +Find a chain's size in the column for its tier. + +| Tower, Luxor | Worldwide, American, Festival | Imperial, Continental | Share price | 1st bonus | 2nd bonus | +| --- | --- | --- | --- | --- | --- | +| 2 | — | — | $200 | $2,000 | $1,000 | +| 3 | 2 | — | $300 | $3,000 | $1,500 | +| 4 | 3 | 2 | $400 | $4,000 | $2,000 | +| 5 | 4 | 3 | $500 | $5,000 | $2,500 | +| 6–10 | 5 | 4 | $600 | $6,000 | $3,000 | +| 11–20 | 6–10 | 5 | $700 | $7,000 | $3,500 | +| 21–30 | 11–20 | 6–10 | $800 | $8,000 | $4,000 | +| 31–40 | 21–30 | 11–20 | $900 | $9,000 | $4,500 | +| 41+ | 31–40 | 21–30 | $1,000 | $10,000 | $5,000 | +| — | 41+ | 31–40 | $1,100 | $11,000 | $5,500 | +| — | — | 41+ | $1,200 | $12,000 | $6,000 | + +The game shows this table under **Price table**, with each chain marked in its current row. + +## Ending the game + +On your turn you may **announce the end** once either of these is true: + +- a chain has 41 or more tiles, or +- every chain on the board is safe. + +You can announce before placing your tile or while buying. Announcing is optional; you finish your turn, then the game ends. The game also ends by itself if a whole round goes by with nobody placing a tile. + +**Final scoring:** bonuses are paid for every chain on the board, then everyone sells all their shares in those chains at current prices. Shares of chains not on the board are worthless. The most money wins; ties share the win. + +## Two players + +With two players, the bank also acts as a shareholder whenever bonuses are paid. For each chain being settled, a tile is drawn from the pool: the bank holds as many shares as the tile's column number (9F means 9 shares). Bonuses the bank wins aren't paid to anyone. After the merger, these bank tiles are placed on the board; one that would cause a merger triggers it, one that would found a chain stays loose, and one that can't be played is removed. At the end, a tile is drawn for each chain in the same way. + +## What you can see + +Your tiles are private. Unless the game was created with **public holdings**, each player's cash and shares are private too; the game log is always public, so a careful player can work them out. + +## Game options + +- **Public holdings:** everyone's cash and shares are visible. +- **Team play** (4 players only): seats 1 and 3 play against seats 2 and 4; each team's money is added together at the end. +- **Two-player mode:** *Bank as third shareholder* (above) or *Four hands*, where each player controls two seats in a normal four-seat game and the player with the single richest seat wins. +- **End automatically when an end condition is met:** the game ends at the end of that turn, with no announcement. +- **Chain size that ends the game:** 41 tiles (standard) or 31 tiles for a shorter game. Safe size and prices don't change. + +Options that don't fit the number of players are ignored, and the log says so. + +## Players who leave + +If a player leaves, the game plays on for them with safe defaults: it places their first playable tile, holds their stock in mergers, buys nothing and never announces the end. They are ranked below every player who stayed. When only one player is left, the game ends at once. diff --git a/docs/admin/screenshots/merger-dark.png b/docs/admin/screenshots/merger-dark.png new file mode 100644 index 0000000..d10f223 Binary files /dev/null and b/docs/admin/screenshots/merger-dark.png differ diff --git a/docs/admin/screenshots/merger-light.png b/docs/admin/screenshots/merger-light.png new file mode 100644 index 0000000..9dbe70f Binary files /dev/null and b/docs/admin/screenshots/merger-light.png differ diff --git a/docs/admin/screenshots/overview-dark.png b/docs/admin/screenshots/overview-dark.png new file mode 100644 index 0000000..270361a Binary files /dev/null and b/docs/admin/screenshots/overview-dark.png differ diff --git a/docs/admin/screenshots/overview-light.png b/docs/admin/screenshots/overview-light.png new file mode 100644 index 0000000..f760069 Binary files /dev/null and b/docs/admin/screenshots/overview-light.png differ diff --git a/docs/admin/screenshots/phone-dark.png b/docs/admin/screenshots/phone-dark.png new file mode 100644 index 0000000..d9de565 Binary files /dev/null and b/docs/admin/screenshots/phone-dark.png differ diff --git a/docs/admin/screenshots/phone-light.png b/docs/admin/screenshots/phone-light.png new file mode 100644 index 0000000..d0ef9d9 Binary files /dev/null and b/docs/admin/screenshots/phone-light.png differ diff --git a/docs/registering.md b/docs/registering.md new file mode 100644 index 0000000..f79c90c --- /dev/null +++ b/docs/registering.md @@ -0,0 +1,154 @@ +# Registering Acquire on boardgamers.space + +How to publish the engine and viewer to BGS, following the BGS guide +(). You need BGS admin access, or an +admin token with the `gameinfo` grant for the command-line route. + +Save the game private first (`public: false`) and play-test it there. + +## 1. Build the two artifacts + +Each GitHub Release has both attached. To build them yourself: + +```bash +pnpm install +pnpm check +cd packages/engine && pnpm pack +``` + +| Artifact | File(s) | BGS field | +| -------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| Engine | `packages/engine/acquire-engine-.tgz` (contains `dist/` and `package.json` only) | `engine.package` (set by the upload), `engine.entryPoint: "dist/wrapper.js"` | +| Viewer | `packages/viewer/dist/acquire-viewer.iife.js`, `acquire-viewer.css`, optional `acquire-viewer.iife.js.map` | `viewer.url`, `viewer.dependencies.stylesheets`, `viewer.topLevelVariable: "acquire"` | + +`pnpm check` rebuilds `packages/viewer/dist` from scratch, so upload that folder straight +after it. The engine's only runtime dependency is `seedrandom`, which BGS installs. + +## 2. Register the game (admin panel) + +In Boardgames, choose + New game and fill in: + +- **Game id:** `acquire`; **version:** `1`. +- **Label:** `Acquire`. +- **Players:** `[2, 3, 4, 5, 6]`. Player counts are not a game option. +- **Options:** paste the declarations below. +- **Preferences:** the shared colour-blind setting: + `[{ "name": "colorBlind", "label": "Color-blind mode", "type": "checkbox", "default": false }]`. +- **Settings:** none. +- **Public:** off. + +Save. + +### Game options + +These match rules.md §15 and the engine's option reader. Unticked checkboxes are not sent, +and selects are always sent as strings; the engine handles both, never rejects an option, and +logs any option that does not apply to the player count. + +```json +[ + { + "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)" } + ] + } +] +``` + +## 3. Upload the engine + +In the version form, choose Upload .tgz… and pick `acquire-engine-.tgz`. BGS reads the +package name and version from the tarball and sets `engine.package` itself. Then set +**entry point** to `dist/wrapper.js` and save. + +BGS installs the engine within about a minute. `meta.replay` is set because the engine +exports `replay`; `meta.bots` stays off, as there is no bot. + +## 4. Upload the viewer + +Choose Upload bundle… and select `acquire-viewer.iife.js`, `acquire-viewer.css` and, if you want +source maps in devtools, `acquire-viewer.iife.js.map`, together. Then set: + +- Top-level variable: `acquire` (the global `registerViewer` creates). +- Chat: on, with in-game controls always accessible (`integratedControls: ["chat"]`). The + 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. + +Save, open the game page, create a private game, and play. + +## Command-line alternative + +The same steps against the admin API, with a token from a platform admin (never commit it): + +```bash +AUTH="Authorization: Bearer $BGS_ADMIN_TOKEN" +BASE=https://admin.boardgamers.space/api/admin/gameinfo/acquire + +# Engine: the raw npm-pack tarball; this sets engine.package on version 1. +curl -X POST "$BASE/1/engine" -H "$AUTH" -H "Content-Type: application/octet-stream" \ + --data-binary @packages/engine/acquire-engine-0.0.1.tgz + +# Viewer files: one POST each with a shared bundle id; each returns the hosted URL. +BUNDLE=acquire-$(git rev-parse --short HEAD) +JS_URL=$(curl -X POST "$BASE/1/viewer/file?filename=acquire-viewer.iife.js&bundle=$BUNDLE" -H "$AUTH" \ + -H "Content-Type: application/octet-stream" --data-binary @packages/viewer/dist/acquire-viewer.iife.js | jq -r .url) +CSS_URL=$(curl -X POST "$BASE/1/viewer/file?filename=acquire-viewer.css&bundle=$BUNDLE" -H "$AUTH" \ + -H "Content-Type: application/octet-stream" --data-binary @packages/viewer/dist/acquire-viewer.css | jq -r .url) + +# Save the URLs, entry point and global name into the version doc. +curl "$BASE/1" -H "$AUTH" | + jq --arg js "$JS_URL" --arg css "$CSS_URL" \ + '.viewer.url = $js | .viewer.dependencies.stylesheets = [$css] | .viewer.topLevelVariable = "acquire" | .engine.entryPoint = "dist/wrapper.js"' | + curl -X PUT "$BASE/1" -H "$AUTH" -H "Content-Type: application/json" --data-binary @- +``` + +## Updating later + +Bump `packages/engine/package.json`'s version and upload the new tarball to the **same** +version integer: ongoing games pick up the new engine within about a minute. A new version +integer only affects new games. Upload the engine and viewer together whenever the move or +state format changes, since they are coupled. + +## Before making a version public + +BGS's release checklist, and where this repo stands: + +- Protocol: core, chat, replay, preferences and avatar handlers are implemented. +- Replays and analysis: the engine exports `replay`, and the viewer's replay controls rebuild + each position from the public log. Analysis of ongoing games stays off. +- Mobile: phone portrait and landscape, tablet and desktop, both themes, 44px touch targets. +- History: no tentative or revisable moves. +- Colour-blind mode: declare the `colorBlind` preference (step 2). +- Languages: the viewer is translated into all 17 BGS locales. The game list's last-move text + 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. diff --git a/package.json b/package.json new file mode 100644 index 0000000..fd31912 --- /dev/null +++ b/package.json @@ -0,0 +1,28 @@ +{ + "name": "acquire", + "version": "0.0.0", + "private": true, + "description": "Acquire for boardgamers.space (engine + viewer)", + "license": "AGPL-3.0-only", + "type": "module", + "scripts": { + "dev": "pnpm --filter acquire-viewer dev", + "build": "pnpm --filter acquire-engine build && pnpm --filter acquire-viewer build", + "test": "pnpm --filter acquire-engine test && pnpm --filter acquire-engine build && pnpm --filter acquire-viewer test", + "tsc": "pnpm --filter acquire-engine tsc && pnpm --filter acquire-engine build && pnpm --filter acquire-viewer tsc", + "fmt": "oxfmt", + "fmt:check": "oxfmt --check", + "lint": "oxlint", + "check": "pnpm fmt:check && pnpm lint && pnpm tsc && pnpm test && pnpm build" + }, + "devDependencies": { + "oxfmt": "0.61.0", + "oxlint": "1.76.0", + "svelte": "5.56.8" + }, + "engines": { + "node": ">=24", + "pnpm": ">=11" + }, + "packageManager": "pnpm@11.11.0" +} diff --git a/packages/engine/index.ts b/packages/engine/index.ts new file mode 100644 index 0000000..58126d4 --- /dev/null +++ b/packages/engine/index.ts @@ -0,0 +1,18 @@ +export * from "./src/types.js"; +export * from "./src/config.js"; +export * from "./src/tiles.js"; +export * from "./src/prices.js"; +export * from "./src/board.js"; +export * from "./src/setup.js"; +export * from "./src/moves.js"; +export * from "./src/legal.js"; +export * from "./src/bonuses.js"; +export * from "./src/merger.js"; +export * from "./src/scoring.js"; +export * from "./src/bank.js"; +export * from "./src/options.js"; +export * from "./src/autoplay.js"; +export * from "./src/view.js"; +export * from "./src/replay.js"; +export * from "./src/position.js"; +export * from "./src/simple.js"; diff --git a/packages/engine/package.json b/packages/engine/package.json new file mode 100644 index 0000000..da44ae0 --- /dev/null +++ b/packages/engine/package.json @@ -0,0 +1,45 @@ +{ + "name": "acquire-engine", + "version": "0.0.1", + "description": "Acquire rules engine for boardgamers.space", + "license": "AGPL-3.0-only", + "files": [ + "dist" + ], + "type": "module", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./wrapper": { + "types": "./dist/wrapper.d.ts", + "default": "./dist/wrapper.js" + }, + "./wrapper.js": { + "types": "./dist/wrapper.d.ts", + "default": "./dist/wrapper.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "prepack": "pnpm build", + "tsc": "tsc --noEmit", + "test": "tsc -p tsconfig.test.json && node --test \"dist-test/src/*.spec.js\"" + }, + "dependencies": { + "seedrandom": "3.0.5" + }, + "devDependencies": { + "@boardgamers/protocol": "0.10.0", + "@types/node": "24.10.1", + "@types/seedrandom": "3.0.8", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=24" + } +} diff --git a/packages/engine/src/autoplay.spec.ts b/packages/engine/src/autoplay.spec.ts new file mode 100644 index 0000000..7be7c13 --- /dev/null +++ b/packages/engine/src/autoplay.spec.ts @@ -0,0 +1,282 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { activeChains } from "./board.js"; +import { legalMoves } from "./legal.js"; +import { applyMove, currentSeat } from "./moves.js"; +import { initGame } from "./setup.js"; +import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +const place = (tile: string) => ({ type: "place", tile }); +const buy = { type: "buy", shares: {} }; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +function autoMoves(state: GameState): { seat: number; move: unknown }[] { + return state.log + .filter((e): e is Extract => e.type === "move" && e.auto === true) + .map(({ seat, move }) => ({ seat, move })); +} + +test("§16 a dropped player's turn is played automatically: first playable tile in board order, buy nothing", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["12I", "3I", "5E"], ["11G"]], + activeSeat: 1, + }); + wrapper.dropPlayer(state, 1); + checkInvariants(state); + assert.deepEqual(autoMoves(state), [ + { seat: 1, move: { type: "place", tile: "3I" } }, + { seat: 1, move: { type: "buy", shares: {} } }, + ]); + assert.equal(state.activeSeat, 2); + assert.deepEqual( + state.log.filter((e) => e.type === "dropped"), + [{ type: "dropped", seat: 1 }] + ); +}); + +test("§16 a dropped player is only played for when it is their decision", () => { + const state = scenario({ hands: [["9G"], ["9I"], ["11G"]] }); + wrapper.dropPlayer(state, 2); + assert.equal(autoMoves(state).length, 0); + assert.equal(currentSeat(state), 0); + play(state, 0, place("9G")); + play(state, 1, place("9I")); + assert.deepEqual(autoMoves(state), [{ seat: 2, move: { type: "place", tile: "11G" } }]); + assert.equal(currentSeat(state), 0); +}); + +test("§16 a dropped founder names the first available chain in config order", () => { + const state = scenario({ + board: { ...chainAt("tower", ["1A", "2A"]), "9F": "loose" }, + hands: [["12I"], ["9G"], ["11G"]], + activeSeat: 1, + }); + wrapper.dropPlayer(state, 1); + assert.equal(state.board[t("9G")], "luxor"); + assert.equal(state.seats[1]!.shares.luxor, 1); +}); + +test("§16 a dropped mergermaker picks the first tied survivor and orders tied defunct chains in config order", () => { + const board = { + ...chainAt("festival", ["3E", "4E"]), + ...chainAt("luxor", ["6E", "7E"]), + ...chainAt("imperial", ["5F", "5G"]), + ...chainAt("tower", ["5C", "5D"]), + }; + const state = scenario({ board, hands: [["9I"], ["5E"], ["11G"]], activeSeat: 1 }); + wrapper.dropPlayer(state, 1); + const plan = state.log.find((e) => e.type === "mergerPlan"); + assert.deepEqual(plan, { type: "mergerPlan", survivor: "tower", defunct: ["luxor", "festival", "imperial"] }); + assert.deepEqual(activeChains(state.board), ["tower"]); +}); + +test("§16 a dropped holder who is not the active player holds all defunct stock mid-merger", () => { + const board = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + const state = scenario({ board, hands: [["4A"], ["9I"], ["11G"]], shares: [{}, { luxor: 2 }, { luxor: 3 }] }); + wrapper.dropPlayer(state, 2); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 1); + play(state, 1, { type: "dispose", sell: 2, trade: 0 }); + assert.deepEqual(autoMoves(state), [{ seat: 2, move: { type: "dispose", sell: 0, trade: 0 } }]); + assert.equal(state.seats[2]!.shares.luxor, 3); + assert.equal(state.phase, "buy"); + assert.equal(currentSeat(state), 0); +}); + +test("§16 a player who drops while they must dispose is played for immediately", () => { + const board = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + const state = scenario({ board, hands: [["4A"], ["9I"], ["11G"]], shares: [{}, { luxor: 2 }, { luxor: 3 }] }); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 1); + wrapper.dropPlayer(state, 1); + assert.equal(currentSeat(state), 2); + assert.equal(state.seats[1]!.shares.luxor, 2); +}); + +test("§16 a dropped player never announces the end", () => { + const state = scenario({ board: chainAt("tower", row("A", 1, 11)), hands: [["9G"], [], ["11G"]], activeSeat: 1 }); + assert.equal(state.phase, "place", "an announcement point"); + wrapper.dropPlayer(state, 1); + assert.deepEqual(autoMoves(state), [ + { seat: 1, move: { type: "pass" } }, + { seat: 1, move: { type: "buy", shares: {} } }, + ]); + assert.equal(state.endAnnounced, null); + assert.equal(state.ended, false); +}); + +test("§16 dropping is idempotent and has no effect after the game ends", () => { + const state = scenario({ board: chainAt("tower", row("A", 1, 11)), hands: [["9G"], ["9I"], ["11G"]] }); + wrapper.dropPlayer(state, 2); + const once = structuredClone(state); + wrapper.dropPlayer(state, 2); + assert.deepEqual(state, once); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.equal(state.ended, true); + const ended = structuredClone(state); + wrapper.dropPlayer(state, 1); + assert.deepEqual(state, ended); + assert.throws(() => wrapper.dropPlayer(state, 7), /Unknown player/); +}); + +test("§16 when a drop leaves one player, the game ends and is scored immediately", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 5)), + hands: [["9G"], ["9I"], ["11G"]], + shares: [{ tower: 2 }, { tower: 5 }, { tower: 1 }], + }); + wrapper.dropPlayer(state, 1); + assert.equal(state.ended, false, "two players remain, so play goes on"); + wrapper.dropPlayer(state, 2); + assert.equal(state.ended, true); + assert.equal(wrapper.currentPlayer(state), undefined); + assert.deepEqual( + state.log.filter((e) => e.type === "gameEnd"), + [{ type: "gameEnd", reason: "dropped" }] + ); + // Tower (minor, size 5: $500, bonuses $5,000 / $2,500): seat 1 first, seat 0 second; all stock sold. + assert.deepEqual( + state.seats.map((seat) => seat.cash), + [6000 + 2500 + 2 * 500, 6000 + 5000 + 5 * 500, 6000 + 1 * 500] + ); + assert.deepEqual(wrapper.rankings(state), [1, 2, 2], "§16 dropped players rank last, whatever their cash"); + checkInvariants(state); +}); + +test("§16 a drop that leaves one player ends the game mid-merger; the merger is abandoned", () => { + // Two players with the bank: 4A merges luxor into tower, and seat 1 must dispose of luxor. + const board = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + const state = scenario({ + seats: 2, + board, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 2 }], + poolTop: ["9C"], + }); + applyMove(state, place("4A"), 0); + assert.equal(state.phase, "dispose"); + assert.deepEqual(state.bankTiles, [t("9C")]); + wrapper.dropPlayer(state, 1); + assert.equal(state.ended, true); + assert.equal(state.merger, null); + assert.deepEqual(state.bankTiles, []); + assert.ok(state.removed.includes(t("9C")), "§16 waiting bank tiles are removed from the game"); + assert.deepEqual(activeChains(state.board), ["tower", "luxor"], "§16 the untaken chain is scored as active"); + assert.equal(state.seats[1]!.shares.luxor, 0, "§11.2 its stock was sold at final scoring"); + assert.deepEqual(wrapper.rankings(state), [1, 2]); + checkInvariants(state); +}); + +test("§16 a dropped player ranks below every remaining player even with the most cash", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11G"]], + cash: [3000, 50000, 2000], + }); + wrapper.dropPlayer(state, 1); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.equal(state.ended, true); + assert.deepEqual(wrapper.scores(state), [3000, 50000, 2000], "§16 a dropped player's cash is still their score"); + assert.deepEqual(wrapper.rankings(state), [1, 3, 2]); +}); + +test("§16 several dropped players share the rank below the remaining players", () => { + const state = scenario({ + seats: 4, + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11G"], ["12G"]], + cash: [3000, 9000, 2000, 8000], + }); + wrapper.dropPlayer(state, 1); + wrapper.dropPlayer(state, 3); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.deepEqual(wrapper.rankings(state), [1, 3, 2, 3]); +}); + +test("§15/§16 teamPlay: teams are ranked by combined cash, and a dropped teammate still ranks last", () => { + const state = scenario({ + seats: 4, + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11G"], ["12G"]], + cash: [3000, 2000, 4000, 9000], + options: { teamPlay: true }, + }); + wrapper.dropPlayer(state, 3); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.deepEqual(wrapper.scores(state), [7000, 11000, 7000, 11000]); + assert.deepEqual(wrapper.rankings(state), [2, 1, 2, 3]); +}); + +const OPTION_SETS: Record[] = [ + {}, + { publicHoldings: true }, + { autoEnd: true }, + { endSize: "31" }, + { teamPlay: true }, + { twoPlayerMode: "fourHands" }, + { autoEnd: true, endSize: "31", publicHoldings: true }, +]; + +test("§16 auto-play between two remaining players stays far inside the 10-second move limit", () => { + let slowest = 0; + for (let players = 3; players <= 6; players++) { + for (const options of OPTION_SETS) { + const state = initGame(players, options, `two-left-${players}-${JSON.stringify(options)}`); + const time = (action: () => void) => { + const started = performance.now(); + action(); + slowest = Math.max(slowest, performance.now() - started); + }; + for (let player = 2; player < players; player++) { + time(() => wrapper.dropPlayer(state, player)); + } + for (let step = 0; !state.ended; step++) { + assert.ok(step < 5000, "game did not finish"); + const moves = legalMoves(state).filter((move) => move.type !== "announce"); + const player = wrapper.currentPlayer(state)!; + assert.ok(player === 0 || player === 1, "only remaining players are asked to move"); + time(() => wrapper.move(state, moves[(step * 7919) % moves.length]!, player)); + checkInvariants(state); + } + } + } + assert.ok(slowest < 1000, `slowest call took ${slowest.toFixed(0)} ms (BGS allows 10 s)`); +}); + +test("§16 players dropping at random points never deadlock and keep every invariant", () => { + for (let players = 2; players <= 6; players++) { + for (const options of OPTION_SETS) { + const state = initGame(players, options, `random-drop-${players}-${JSON.stringify(options)}`); + let step = 0; + while (!state.ended) { + step++; + assert.ok(step < 5000, "game did not finish"); + if (step % 37 === 0) { + wrapper.dropPlayer(state, step % players); + checkInvariants(state); + continue; + } + const moves = legalMoves(state); + const move = moves[(step * 7919) % moves.length]!; + applyMove(state, move, currentSeat(state)!); + checkInvariants(state); + } + } + } +}); diff --git a/packages/engine/src/autoplay.ts b/packages/engine/src/autoplay.ts new file mode 100644 index 0000000..ece1035 --- /dev/null +++ b/packages/engine/src/autoplay.ts @@ -0,0 +1,33 @@ +import { activeChains, playableTiles } from "./board.js"; +import { CHAIN_IDS } from "./config.js"; +import { merger, survivorCandidates } from "./merger.js"; +import { sortTiles, tileLabel } from "./tiles.js"; +import type { GameState, Move } from "./types.js"; + +/** rules.md §16: the decision a dropped seat makes in the current phase. Never announces. */ +export function defaultMove(state: GameState, seat: number): Move { + switch (state.phase) { + case "place": { + const [tile] = sortTiles(playableTiles(state, seat)); + return tile === undefined ? { type: "pass" } : { type: "place", tile: tileLabel(tile) }; + } + case "found": { + const active = activeChains(state.board); + return { type: "found", chain: CHAIN_IDS.find((chain) => !active.includes(chain))! }; + } + case "survivor": + return { type: "survivor", chain: survivorCandidates(merger(state))[0]! }; + case "defunctOrder": { + const m = merger(state); + const defunct = CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined && chain !== m.survivor); + // Array.prototype.sort is stable, so equal sizes keep config order. + return { type: "defunctOrder", chains: defunct.sort((a, b) => m.sizes[b]! - m.sizes[a]!) }; + } + case "dispose": + return { type: "dispose", sell: 0, trade: 0 }; + case "buy": + return { type: "buy", shares: {} }; + default: + throw new Error(`No default move in phase ${state.phase}`); + } +} diff --git a/packages/engine/src/bank.spec.ts b/packages/engine/src/bank.spec.ts new file mode 100644 index 0000000..ea0abed --- /dev/null +++ b/packages/engine/src/bank.spec.ts @@ -0,0 +1,346 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { placeNextBankTile } from "./bank.js"; +import { activeChains, chainSize } from "./board.js"; +import { applyMove, currentSeat } from "./moves.js"; +import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +const place = (tile: string) => ({ type: "place", tile }); +const dispose = (sell: number, trade: number) => ({ type: "dispose", sell, trade }); +const buy = (shares: Record = {}) => ({ type: "buy", shares }); + +function entries(state: GameState, type: T): Extract[] { + return state.log.filter((e): e is Extract => e.type === type); +} + +// tower 1A-3A (3) and luxor 5A-6A (2, minor: $200, bonuses $2,000 / $1,000); 4A merges them. +const TWO_CHAINS = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + +test("§12.1.1 the bank holds shares equal to the drawn tile's column and can win the majority", () => { + const state = scenario({ + seats: 2, + board: TWO_CHAINS, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 3 }], + poolTop: ["9C"], + }); + play(state, 0, place("4A")); + const [bonus] = entries(state, "bonuses"); + assert.deepEqual(bonus?.bank, { tile: t("9C"), shares: 9, amount: 2000 }); + assert.deepEqual(bonus?.payouts, [{ seat: 1, amount: 1000 }]); + assert.equal(state.seats[1]!.cash, 7000, "§12.1.2 the bank's majority bonus is not paid to anyone"); +}); + +test("§12.1.2 a bank tie is split normally and the bank's portion is not paid out", () => { + const state = scenario({ + seats: 2, + board: TWO_CHAINS, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 4 }], + poolTop: ["4I"], + }); + play(state, 0, place("4A")); + const [bonus] = entries(state, "bonuses"); + assert.deepEqual(bonus?.bank, { tile: t("4I"), shares: 4, amount: 1500 }); + assert.deepEqual(bonus?.payouts, [{ seat: 1, amount: 1500 }]); +}); + +test("§12.1.3 the bank never disposes of stock", () => { + const state = scenario({ + seats: 2, + board: TWO_CHAINS, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 2 }], + poolTop: ["9C"], + }); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 1); + play(state, 1, dispose(2, 0)); + assert.equal(state.phase, "buy"); + assert.equal(entries(state, "disposed").length, 1); +}); + +test("§12.1.5 one bank tile is drawn per defunct chain", () => { + const board = { + ...chainAt("tower", row("E", 1, 4)), + ...chainAt("luxor", row("E", 6, 8)), + ...chainAt("festival", ["5F", "5G"]), + }; + const state = scenario({ seats: 2, board, hands: [["5E"], ["12A"]], poolTop: ["12I", "10I"] }); + play(state, 0, place("5E")); + assert.deepEqual( + entries(state, "bonuses").map((e) => [e.chain, e.bank?.shares]), + [ + ["luxor", 12], + ["festival", 10], + ] + ); +}); + +test("§12.1.5 with an empty pool the bank holds 0 shares", () => { + const state = scenario({ + seats: 2, + board: TWO_CHAINS, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 1 }], + poolOnly: true, + }); + play(state, 0, place("4A")); + const [bonus] = entries(state, "bonuses"); + assert.deepEqual(bonus?.bank, { tile: null, shares: 0, amount: 0 }); + assert.deepEqual(bonus?.payouts, [{ seat: 1, amount: 3000 }], "§10 a single holder gets both bonuses"); + assert.deepEqual(entries(state, "bankTile"), []); +}); + +test("§12.1.4 bank tiles are placed after every defunct chain is resolved, before the buy step", () => { + const state = scenario({ + seats: 2, + board: TWO_CHAINS, + hands: [["4A"], ["12I"]], + shares: [{}, { luxor: 2 }], + poolTop: ["9C"], + }); + play(state, 0, place("4A")); + assert.equal(state.phase, "dispose"); + assert.equal(state.board[t("9C")], null); + assert.deepEqual(state.bankTiles, [t("9C")], "§14.3 a drawn bank tile waits in the bank queue"); + play(state, 1, dispose(0, 0)); + assert.equal(state.board[t("9C")], "loose"); + assert.deepEqual(state.bankTiles, []); + assert.equal(state.phase, "buy"); + assert.equal(state.activeSeat, 0); +}); + +test("§12.1.4 waiting bank tiles are placed in the order they were drawn", () => { + const board = { + ...chainAt("tower", row("E", 1, 4)), + ...chainAt("luxor", row("E", 6, 8)), + ...chainAt("festival", ["5F", "5G"]), + }; + const state = scenario({ seats: 2, board, hands: [["5E"], ["12A"]], poolTop: ["12I", "10I"] }); + play(state, 0, place("5E")); + assert.deepEqual( + entries(state, "bankTile").map((e) => e.tile), + [t("12I"), t("10I")] + ); +}); + +test("§12.1.4 a bank tile joining a chain brings connected loose tiles with it", () => { + const board = { + ...TWO_CHAINS, + ...chainAt("festival", ["9A", "9B"]), + "10C": "loose" as const, + "11C": "loose" as const, + }; + const state = scenario({ seats: 2, board, hands: [["4A"], ["12I"]], poolTop: ["9C"] }); + play(state, 0, place("4A")); + assert.deepEqual(entries(state, "bankTile"), [{ type: "bankTile", tile: t("9C"), result: "joined" }]); + assert.ok(["9C", "10C", "11C"].every((label) => state.board[t(label)] === "festival")); + assert.equal(chainSize(state.board, "festival"), 5); +}); + +test("§12.1.4 a bank tile causing another merger resolves it with a fresh bank draw, repeating until no merger occurs", () => { + // The player's 4A merges tower and luxor; the bank draws 9B. 9B merges worldwide (3) and + // american (2); the bank draws 9G. 9G merges imperial (3) and festival (2); the bank draws 1I, + // which lands on its own. + const board = { + ...TWO_CHAINS, + ...chainAt("worldwide", ["8B", "8C", "8D"]), + ...chainAt("american", ["10B", "11B"]), + ...chainAt("imperial", ["10G", "11G", "12G"]), + ...chainAt("festival", ["7G", "8G"]), + }; + const state = scenario({ + seats: 2, + board, + hands: [["4A"], ["12I"]], + shares: [{ american: 2, festival: 1 }, { luxor: 1 }], + poolTop: ["9B", "9G", "1I"], + }); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 1, "luxor disposal"); + play(state, 1, dispose(1, 0)); + assert.equal(currentSeat(state), 0, "american disposal in the bank-tile merger"); + play(state, 0, dispose(0, 2)); + assert.equal(currentSeat(state), 0, "festival disposal in the second bank-tile merger"); + play(state, 0, dispose(1, 0)); + + assert.deepEqual( + entries(state, "merger").map((e) => [e.tile, e.byBank === true]), + [ + [t("4A"), false], + [t("9B"), true], + [t("9G"), true], + ] + ); + assert.deepEqual( + entries(state, "bonuses").map((e) => [e.chain, e.bank?.tile]), + [ + ["luxor", t("9B")], + ["american", t("9G")], + ["festival", t("1I")], + ] + ); + assert.deepEqual( + entries(state, "bankTile").map((e) => [e.tile, e.result]), + [ + [t("9B"), "merger"], + [t("9G"), "merger"], + [t("1I"), "loose"], + ] + ); + assert.deepEqual(activeChains(state.board), ["tower", "worldwide", "imperial"]); + assert.equal(chainSize(state.board, "tower"), 6); + assert.equal(chainSize(state.board, "worldwide"), 6); + assert.equal(chainSize(state.board, "imperial"), 6); + assert.equal(state.board[t("1I")], "loose"); + assert.equal(state.seats[0]!.shares.worldwide, 1); + assert.equal(state.phase, "buy"); + assert.equal(state.activeSeat, 0); +}); + +test("§12.1.4 in a merger caused by a bank tile the active player is the mergermaker", () => { + // Seat 1 plays 4A; the bank's 9B ties worldwide (2) and american (2). + const board = { + ...TWO_CHAINS, + ...chainAt("worldwide", ["8B", "8C"]), + ...chainAt("american", ["10B", "11B"]), + }; + const state = scenario({ + seats: 2, + board, + hands: [["12I"], ["4A"]], + activeSeat: 1, + shares: [{ american: 2 }, { american: 1 }], + poolTop: ["9B", "1I"], + }); + play(state, 1, place("4A")); + assert.equal(state.phase, "survivor"); + assert.equal(currentSeat(state), 1); + assert.throws(() => applyMove(state, { type: "survivor", chain: "worldwide" }, 0), /not your turn/); + play(state, 1, { type: "survivor", chain: "worldwide" }); + // American (medium, size 2: $300, $3,000 / $1,500): seat 0 first; seat 1 ties the bank (1I = 1). + const american = entries(state, "bonuses").find((e) => e.chain === "american"); + assert.deepEqual(american?.payouts, [ + { seat: 0, amount: 3000 }, + { seat: 1, amount: 800 }, + ]); + assert.deepEqual(american?.bank, { tile: t("1I"), shares: 1, amount: 800 }); + assert.equal(currentSeat(state), 1, "disposal starts with the active player"); + play(state, 1, dispose(1, 0)); + assert.equal(currentSeat(state), 0); + play(state, 0, dispose(0, 0)); + assert.equal(state.phase, "buy"); + assert.equal(state.activeSeat, 1); +}); + +test("§12.1.4 a permanently unplayable bank tile is removed from the game", () => { + const board = { ...TWO_CHAINS, ...chainAt("worldwide", row("G", 1, 11)), ...chainAt("american", row("I", 1, 11)) }; + const state = scenario({ seats: 2, board, hands: [["4A"], ["12I"]], poolTop: ["1H"] }); + play(state, 0, place("4A")); + assert.deepEqual(entries(state, "bankTile"), [{ type: "bankTile", tile: t("1H"), result: "removed" }]); + assert.equal(state.board[t("1H")], null); + assert.ok(state.removed.includes(t("1H"))); + assert.equal(state.phase, "buy"); +}); + +test("§12.1.4 a bank tile that would found a chain stays loose; the next player to extend it founds and gets the bonus", () => { + const state = scenario({ + seats: 2, + board: { ...TWO_CHAINS, "9E": "loose" }, + hands: [["4A"], ["9G"]], + poolTop: ["9F"], + }); + play(state, 0, place("4A")); + assert.equal(state.board[t("9F")], "loose"); + assert.equal(state.board[t("9E")], "loose"); + assert.deepEqual(activeChains(state.board), ["tower"]); + play(state, 0, buy()); + play(state, 1, place("9G")); + play(state, 1, { type: "found", chain: "festival" }); + assert.equal(chainSize(state.board, "festival"), 3); + assert.equal(state.seats[1]!.shares.festival, 1); + assert.equal(state.seats[0]!.shares.festival, 0); +}); + +test("§12.1.4 a bank tile that would found a chain stays loose even with all 7 chains active", () => { + // A merger always frees a name, so this cannot arise from a real merger; the placement step is + // exercised directly on a constructed position to pin down the rule. + const seven = { + ...chainAt("tower", ["1A", "2A"]), + ...chainAt("luxor", ["4A", "5A"]), + ...chainAt("worldwide", ["7A", "8A"]), + ...chainAt("american", ["10A", "11A"]), + ...chainAt("festival", ["1C", "2C"]), + ...chainAt("imperial", ["4C", "5C"]), + ...chainAt("continental", ["7C", "8C"]), + "1G": "loose" as const, + }; + const state = scenario({ seats: 2, board: seven, hands: [["12I"], ["10I"]], poolTop: ["1H"] }); + state.pool.pop(); + state.bankTiles = [t("1H")]; + checkInvariants(state); + placeNextBankTile(state); + assert.equal(state.board[t("1H")], "loose"); + assert.equal(state.board[t("1G")], "loose"); + assert.equal(activeChains(state.board).length, 7); + checkInvariants(state); +}); + +test("§12.2 at final scoring the bank draws a tile per active chain, competes, and the tiles are set aside", () => { + // Tower and luxor are both safe at 11 (minor: $700, bonuses $7,000 / $3,500). + const state = scenario({ + seats: 2, + board: { ...chainAt("tower", row("A", 1, 11)), ...chainAt("luxor", row("C", 1, 11)) }, + hands: [["9G"], ["12I"]], + shares: [{ tower: 5 }, { luxor: 4 }], + poolTop: ["1E", "2E", "3E", "4E", "5E", "6E", "8I", "2I"], + poolOnly: true, + }); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.equal(state.ended, true); + const bonuses = entries(state, "bonuses"); + assert.deepEqual( + bonuses.map((e) => [e.chain, e.bank, e.payouts]), + [ + ["tower", { tile: t("8I"), shares: 8, amount: 7000 }, [{ seat: 0, amount: 3500 }]], + ["luxor", { tile: t("2I"), shares: 2, amount: 3500 }, [{ seat: 1, amount: 7000 }]], + ] + ); + assert.deepEqual( + state.seats.map((seat) => seat.cash), + [6000 + 3500 + 5 * 700, 6000 + 7000 + 4 * 700] + ); + assert.equal(state.board[t("8I")], null, "§12.2 bank tiles are not placed"); + assert.equal(state.board[t("2I")], null); + assert.ok( + state.removed.includes(t("8I")) && state.removed.includes(t("2I")), + "§14.3 set-aside tiles count as removed" + ); + assert.deepEqual(state.bankTiles, []); + checkInvariants(state); +}); + +test("§12 with three or more players there is no bank shareholder", () => { + const state = scenario({ + seats: 3, + board: TWO_CHAINS, + hands: [["4A"], ["12I"], ["10I"]], + shares: [{}, { luxor: 1 }], + }); + const poolBefore = state.pool.length; + play(state, 0, place("4A")); + const [bonus] = entries(state, "bonuses"); + assert.equal(bonus?.bank, undefined); + assert.deepEqual(bonus?.payouts, [{ seat: 1, amount: 3000 }]); + assert.equal(state.pool.length, poolBefore); +}); diff --git a/packages/engine/src/bank.ts b/packages/engine/src/bank.ts new file mode 100644 index 0000000..dee6a58 --- /dev/null +++ b/packages/engine/src/bank.ts @@ -0,0 +1,68 @@ +import { connectedLoose, placementEffect, tileLegality, chainSize } from "./board.js"; +import { startMerger } from "./merger.js"; +import { tileColumn } from "./tiles.js"; +import { drawTile, enterBuyPhase } from "./turn.js"; +import type { BankHolding, GameState } from "./types.js"; + +/** rules.md §12/§15: the bank is a third shareholder with exactly 2 players and twoPlayerMode "bank". */ +export function isBankMode(state: GameState): boolean { + return state.players === 2 && state.options.twoPlayerMode === "bank"; +} + +/** + * rules.md §12.1.1/§12.1.5/§12.2: draw a tile; the bank holds as many shares as its column + * number, or 0 if the pool is empty. At a merger the tile waits to be placed; at final scoring + * it is set aside (removed from the game). Returns undefined outside bank mode. + */ +export function bankHolding(state: GameState, fate: "wait" | "setAside"): Omit | undefined { + if (!isBankMode(state)) { + return undefined; + } + const tile = drawTile(state); + if (tile === undefined) { + return { tile: null, shares: 0 }; + } + if (fate === "wait") { + state.bankTiles.push(tile); + } else { + state.removed.push(tile); + } + return { tile, shares: tileColumn(tile) }; +} + +/** + * rules.md §12.1.4: place waiting bank tiles in draw order, before the active player's buy step. + * A tile that causes a merger starts it; when that merger completes it calls back here, so the + * queue (including tiles drawn by that merger) continues where it left off. + */ +export function placeNextBankTile(state: GameState): void { + const tile = state.bankTiles.shift(); + if (tile === undefined) { + enterBuyPhase(state); + return; + } + if (tileLegality(state.board, tile) === "permanentlyUnplayable") { + state.removed.push(tile); + state.log.push({ type: "bankTile", tile, result: "removed" }); + placeNextBankTile(state); + return; + } + const effect = placementEffect(state.board, tile); + state.board[tile] = "loose"; + if (effect.kind === "merge") { + state.log.push({ type: "bankTile", tile, result: "merger" }); + startMerger(state, tile, effect.chains, true); + return; + } + if (effect.kind === "grow") { + for (const t of connectedLoose(state.board, tile)) { + state.board[t] = effect.chain; + } + state.log.push({ type: "bankTile", tile, result: "joined" }); + state.log.push({ type: "grew", chain: effect.chain, size: chainSize(state.board, effect.chain) }); + } else { + // A tile that would found a chain stays loose, even with all 7 chains active (§12.1.4). + state.log.push({ type: "bankTile", tile, result: "loose" }); + } + placeNextBankTile(state); +} diff --git a/packages/engine/src/board.spec.ts b/packages/engine/src/board.spec.ts new file mode 100644 index 0000000..5055d81 --- /dev/null +++ b/packages/engine/src/board.spec.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { placementEffect, tileLegality } from "./board.js"; +import { allTiles } from "./tiles.js"; +import { chainAt, row, t } from "./test/helpers.js"; +import type { Cell } from "./types.js"; + +function boardOf(spec: Record>): Cell[] { + const board: Cell[] = allTiles().map(() => null); + for (const [label, cell] of Object.entries(spec)) { + board[t(label)] = cell; + } + return board; +} + +const SEVEN_CHAINS = { + ...chainAt("tower", ["1A", "2A"]), + ...chainAt("luxor", ["4A", "5A"]), + ...chainAt("worldwide", ["7A", "8A"]), + ...chainAt("american", ["10A", "11A"]), + ...chainAt("festival", ["1C", "2C"]), + ...chainAt("imperial", ["4C", "5C"]), + ...chainAt("continental", ["7C", "8C"]), +}; + +test("§5.1 a tile with no neighbours becomes loose", () => { + assert.deepEqual(placementEffect(boardOf({ "1A": "loose" }), t("5E")), { kind: "loose" }); +}); + +test("§5.1 a tile next to only loose tiles founds a chain", () => { + assert.deepEqual(placementEffect(boardOf({ "5D": "loose" }), t("5E")), { kind: "found" }); +}); + +test("§5.1 a tile next to one chain (and loose tiles) grows that chain", () => { + const board = boardOf({ ...chainAt("tower", ["5C", "5D"]), "6E": "loose" }); + assert.deepEqual(placementEffect(board, t("5E")), { kind: "grow", chain: "tower" }); +}); + +test("§5.1 a tile next to two different chains causes a merger", () => { + const board = boardOf({ ...chainAt("tower", ["5C", "5D"]), ...chainAt("luxor", ["6E", "7E"]) }); + assert.deepEqual(placementEffect(board, t("5E")), { kind: "merge", chains: ["tower", "luxor"] }); +}); + +test("§5.2 merging two safe chains is permanently unplayable", () => { + const board = boardOf({ ...chainAt("tower", row("A", 1, 11)), ...chainAt("luxor", row("C", 1, 11)) }); + assert.equal(tileLegality(board, t("1B")), "permanentlyUnplayable"); +}); + +test("§5.2 merging two safe chains is unplayable even when an open chain is also touched", () => { + const board = boardOf({ + ...chainAt("tower", row("A", 1, 11)), + ...chainAt("luxor", row("C", 1, 11)), + ...chainAt("festival", ["12B", "12C"]), + }); + assert.equal(tileLegality(board, t("11B")), "permanentlyUnplayable"); +}); + +test("§5.2 one safe chain may take over an open chain", () => { + const board = boardOf({ ...chainAt("tower", row("A", 1, 11)), ...chainAt("luxor", row("C", 1, 10)) }); + assert.equal(tileLegality(board, t("1B")), "playable"); +}); + +test("§5.2 founding while all 7 chains are active is temporarily unplayable", () => { + const board = boardOf({ ...SEVEN_CHAINS, "1G": "loose" }); + assert.equal(tileLegality(board, t("1H")), "temporarilyUnplayable"); +}); + +test("§5.2 a tile touching a chain is not blocked by the 7-chain rule, even if it touches loose tiles", () => { + const board = boardOf({ ...SEVEN_CHAINS, "10C": "loose" }); + assert.equal(tileLegality(board, t("9C")), "playable"); +}); + +test("§5.2 a tile with no neighbours is playable with all 7 chains active", () => { + assert.equal(tileLegality(boardOf(SEVEN_CHAINS), t("10G")), "playable"); +}); + +test("§5.2 legality is recomputed from the board: freeing a chain name makes the tile playable", () => { + const board = boardOf({ ...SEVEN_CHAINS, "1G": "loose" }); + assert.equal(tileLegality(board, t("1H")), "temporarilyUnplayable"); + board[t("7C")] = null; + board[t("8C")] = null; + assert.equal(tileLegality(board, t("1H")), "playable"); +}); diff --git a/packages/engine/src/board.ts b/packages/engine/src/board.ts new file mode 100644 index 0000000..4220523 --- /dev/null +++ b/packages/engine/src/board.ts @@ -0,0 +1,77 @@ +import { CHAIN_IDS, END_SIZE, SAFE_SIZE, type ChainId } from "./config.js"; +import { neighbours, type Tile } from "./tiles.js"; +import type { Cell, GameState } from "./types.js"; + +export type Placement = + | { kind: "loose" } + | { kind: "found" } + | { kind: "grow"; chain: ChainId } + | { kind: "merge"; chains: ChainId[] }; + +export type Legality = "playable" | "temporarilyUnplayable" | "permanentlyUnplayable"; + +export function chainSize(board: Cell[], chain: ChainId): number { + return board.filter((cell) => cell === chain).length; +} + +export function activeChains(board: Cell[]): ChainId[] { + return CHAIN_IDS.filter((chain) => board.includes(chain)); +} + +export function isSafe(board: Cell[], chain: ChainId): boolean { + return chainSize(board, chain) >= SAFE_SIZE; +} + +/** rules.md §5.1: what placing this tile on the current board would do. */ +export function placementEffect(board: Cell[], tile: Tile): Placement { + const adjacent = neighbours(tile).map((t) => board[t] ?? null); + const chains = CHAIN_IDS.filter((chain) => adjacent.includes(chain)); + if (chains.length >= 2) { + return { kind: "merge", chains }; + } + if (chains.length === 1) { + return { kind: "grow", chain: chains[0]! }; + } + return adjacent.includes("loose") ? { kind: "found" } : { kind: "loose" }; +} + +/** rules.md §5.2, computed fresh from the board every time. */ +export function tileLegality(board: Cell[], tile: Tile): Legality { + const effect = placementEffect(board, tile); + if (effect.kind === "merge" && effect.chains.filter((chain) => isSafe(board, chain)).length >= 2) { + return "permanentlyUnplayable"; + } + if (effect.kind === "found" && activeChains(board).length === CHAIN_IDS.length) { + return "temporarilyUnplayable"; + } + return "playable"; +} + +export function playableTiles(state: GameState, seat: number): Tile[] { + return (state.seats[seat]?.hand ?? []).filter((tile) => tileLegality(state.board, tile) === "playable"); +} + +/** The tile plus every loose tile connected to it through other loose tiles. */ +export function connectedLoose(board: Cell[], tile: Tile): Tile[] { + const group = new Set([tile]); + const frontier = [tile]; + while (frontier.length > 0) { + const current = frontier.pop()!; + for (const next of neighbours(current)) { + if (board[next] === "loose" && !group.has(next)) { + group.add(next); + frontier.push(next); + } + } + } + return [...group]; +} + +/** rules.md §11.1: any chain has reached the end size (§15 endSize), or every active chain is safe. */ +export function endConditionHolds(board: Cell[], endSize = END_SIZE): boolean { + const chains = activeChains(board); + if (chains.some((chain) => chainSize(board, chain) >= endSize)) { + return true; + } + return chains.length > 0 && chains.every((chain) => isSafe(board, chain)); +} diff --git a/packages/engine/src/bonuses.spec.ts b/packages/engine/src/bonuses.spec.ts new file mode 100644 index 0000000..56caa3c --- /dev/null +++ b/packages/engine/src/bonuses.spec.ts @@ -0,0 +1,35 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { computeBonuses } from "./bonuses.js"; + +test("§10 single holder receives both the majority and minority bonus", () => { + assert.deepEqual(computeBonuses([0, 5, 0], 4000, 2000), [0, 6000, 0]); +}); + +test("§10 clear first and clear second", () => { + assert.deepEqual(computeBonuses([5, 3, 1], 4000, 2000), [4000, 2000, 0]); +}); + +test("§10 tie for first: both bonuses are added and split; nobody else gets a minority bonus", () => { + assert.deepEqual(computeBonuses([5, 5, 1], 4000, 2000), [3000, 3000, 0]); + assert.deepEqual(computeBonuses([4, 4, 4], 3000, 1500), [1500, 1500, 1500]); +}); + +test("§10 clear first, tie for second: the minority bonus is split among the tied players", () => { + assert.deepEqual(computeBonuses([6, 2, 2], 6000, 3000), [6000, 1500, 1500]); +}); + +test("§10 rounding: a split first-place bonus is rounded up to the next $100", () => { + assert.deepEqual(computeBonuses([3, 3], 3000, 1500), [2300, 2300]); + assert.deepEqual(computeBonuses([2, 2, 2, 2], 7000, 3500), [2700, 2700, 2700, 2700]); +}); + +test("§10 rounding: a split second-place bonus is also rounded up to the next $100", () => { + assert.deepEqual(computeBonuses([6, 2, 2], 3000, 1500), [3000, 800, 800]); + assert.deepEqual(computeBonuses([9, 1, 1, 1], 5000, 2500), [5000, 900, 900, 900]); +}); + +test("§10 players with zero shares never receive a bonus", () => { + assert.deepEqual(computeBonuses([0, 0, 0], 2000, 1000), [0, 0, 0]); + assert.deepEqual(computeBonuses([0, 4, 0, 2], 2000, 1000), [0, 2000, 0, 1000]); +}); diff --git a/packages/engine/src/bonuses.ts b/packages/engine/src/bonuses.ts new file mode 100644 index 0000000..6281500 --- /dev/null +++ b/packages/engine/src/bonuses.ts @@ -0,0 +1,33 @@ +function roundUpToHundred(amount: number): number { + return Math.ceil(amount / 100) * 100; +} + +/** + * rules.md §10: majority and minority bonuses for one chain. `holdings[i]` is holder i's share + * count; the result gives each holder's payout. Holders with no shares never receive anything. + * Split amounts are rounded up to the next $100. + */ +export function computeBonuses(holdings: number[], majority: number, minority: number): number[] { + const payouts = holdings.map(() => 0); + const counts = [...new Set(holdings.filter((n) => n > 0))].sort((a, b) => b - a); + const top = counts[0]; + if (top === undefined) { + return payouts; + } + const firsts = holdings.flatMap((n, i) => (n === top ? [i] : [])); + const second = counts[1]; + if (firsts.length > 1 || second === undefined) { + const share = roundUpToHundred((majority + minority) / firsts.length); + for (const i of firsts) { + payouts[i] = share; + } + return payouts; + } + payouts[firsts[0]!] = majority; + const seconds = holdings.flatMap((n, i) => (n === second ? [i] : [])); + const share = roundUpToHundred(minority / seconds.length); + for (const i of seconds) { + payouts[i] = share; + } + return payouts; +} diff --git a/packages/engine/src/config.ts b/packages/engine/src/config.ts new file mode 100644 index 0000000..c980e20 --- /dev/null +++ b/packages/engine/src/config.ts @@ -0,0 +1,41 @@ +export type Tier = "minor" | "medium" | "major"; + +// rules.md §8: chain names and tiers live in this one table. Its order is the "config order" +// used for tie-breaking defaults (rules.md §16). +export const CHAINS = [ + { id: "tower", name: "Tower", tier: "minor" }, + { id: "luxor", name: "Luxor", tier: "minor" }, + { id: "worldwide", name: "Worldwide", tier: "medium" }, + { id: "american", name: "American", tier: "medium" }, + { id: "festival", name: "Festival", tier: "medium" }, + { id: "imperial", name: "Imperial", tier: "major" }, + { id: "continental", name: "Continental", tier: "major" }, +] as const satisfies readonly { id: string; name: string; tier: Tier }[]; + +export type ChainId = (typeof CHAINS)[number]["id"]; + +export const CHAIN_IDS: readonly ChainId[] = CHAINS.map((c) => c.id); + +export const BOARD_COLUMNS = 12; +export const BOARD_ROWS = 9; +export const TILE_COUNT = BOARD_COLUMNS * BOARD_ROWS; +export const STARTING_CASH = 6000; +export const HAND_SIZE = 6; +export const SHARES_PER_CHAIN = 25; +export const SAFE_SIZE = 11; +export const END_SIZE = 41; +/** Automatic turn advances allowed within one move before declaring a deadlock. */ +export const AUTO_TURN_LIMIT = 50; +/** Moves auto-played for dropped seats within one call; a whole game needs far fewer. */ +export const AUTO_MOVE_LIMIT = 20000; +export const MAX_BUY = 3; +export const MIN_PLAYERS = 2; +export const MAX_PLAYERS = 6; + +export function chainTier(chain: ChainId): Tier { + return CHAINS.find((c) => c.id === chain)!.tier; +} + +export function isChainId(value: unknown): value is ChainId { + return typeof value === "string" && (CHAIN_IDS as readonly string[]).includes(value); +} diff --git a/packages/engine/src/end.spec.ts b/packages/engine/src/end.spec.ts new file mode 100644 index 0000000..b9a30ea --- /dev/null +++ b/packages/engine/src/end.spec.ts @@ -0,0 +1,226 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { endConditionHolds } from "./board.js"; +import { legalMoves } from "./legal.js"; +import { applyMove, currentSeat } from "./moves.js"; +import { chainAt, checkInvariants, row, scenario } from "./test/helpers.js"; +import { startTurn } from "./turn.js"; +import type { GameState, LogEntry } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +const place = (tile: string) => ({ type: "place", tile }); +const buy = (shares: Record = {}) => ({ type: "buy", shares }); +const announce = { type: "announce" }; + +function entries(state: GameState, type: T): Extract[] { + return state.log.filter((e): e is Extract => e.type === type); +} + +const SAFE_TOWER = chainAt("tower", row("A", 1, 11)); +const TOWER_10 = chainAt("tower", row("A", 1, 10)); +const TOWER_41 = chainAt("tower", [ + ...row("A", 1, 10), + ...row("B", 1, 10), + ...row("C", 1, 10), + ...row("D", 1, 10), + "11A", +]); + +test("§11.1 end condition: a chain of 41 or more tiles, even with open chains on the board", () => { + const state = scenario({ board: { ...TOWER_41, ...chainAt("luxor", ["1G", "2G"]) }, hands: [["9I"]] }); + assert.equal(endConditionHolds(state.board), true); +}); + +test("§11.1 end condition: every active chain is safe", () => { + const both = scenario({ board: { ...SAFE_TOWER, ...chainAt("luxor", row("C", 1, 11)) }, hands: [["9I"]] }); + assert.equal(endConditionHolds(both.board), true); + const oneOpen = scenario({ board: { ...SAFE_TOWER, ...chainAt("luxor", ["1G", "2G"]) }, hands: [["9I"]] }); + assert.equal(endConditionHolds(oneOpen.board), false); +}); + +test("§11.1 end condition: never holds with no chain on the board", () => { + const state = scenario({ board: { "1A": "loose" }, hands: [["9I"]] }); + assert.equal(endConditionHolds(state.board), false); +}); + +test("§11.1 the end may be announced before placing, then the turn finishes normally", () => { + const state = scenario({ board: SAFE_TOWER, hands: [["9G"], ["9I"], ["11I"]], poolTop: ["12I"] }); + play(state, 0, announce); + assert.equal(state.phase, "place"); + assert.equal(state.endAnnounced, 0); + play(state, 0, place("9G")); + assert.equal(state.phase, "buy"); + assert.throws(() => applyMove(state, announce, 0), /cannot be ended/); + play(state, 0, buy({ tower: 1 })); + assert.equal(state.ended, true); + assert.equal(state.phase, "ended"); + assert.equal(currentSeat(state), undefined); + assert.deepEqual(entries(state, "gameEnd"), [{ type: "gameEnd", reason: "announced" }]); + assert.ok( + entries(state, "drew").some((e) => e.seat === 0), + "§4.5 the turn's draw still happens" + ); +}); + +test("§11.1 the end may be announced during the buy step", () => { + const state = scenario({ board: SAFE_TOWER, hands: [["9G"], ["9I"]] }); + play(state, 0, place("9G")); + play(state, 0, announce); + assert.equal(state.phase, "buy"); + play(state, 0, buy()); + assert.equal(state.ended, true); +}); + +test("§11.1 announcing is optional", () => { + const state = scenario({ board: SAFE_TOWER, hands: [["9G"], ["9I"]] }); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.equal(state.ended, false); + assert.equal(state.activeSeat, 1); +}); + +test("§11.1 the end cannot be announced when no condition holds", () => { + const state = scenario({ board: TOWER_10, hands: [["9G"], ["9I"]] }); + assert.throws(() => applyMove(state, announce, 0), /cannot be ended/); + play(state, 0, place("9G")); + assert.throws(() => applyMove(state, announce, 0), /cannot be ended/); +}); + +test("§11.1 the condition is checked when announcing: founding an unsafe chain removes the option", () => { + const state = scenario({ board: { ...SAFE_TOWER, "9F": "loose" }, hands: [["9G"], ["9I"]] }); + assert.ok( + legalMoves(state).some((move) => move.type === "announce"), + "announcing before placing is allowed" + ); + play(state, 0, place("9G")); + play(state, 0, { type: "found", chain: "luxor" }); + assert.equal(state.phase, "buy"); + assert.throws(() => applyMove(state, announce, 0), /cannot be ended/); +}); + +test("§11.1 the end can only be announced by the active player at the two announcement points", () => { + const tied = { ...chainAt("festival", ["3H", "4H"]), ...chainAt("imperial", ["6H", "7H"]), ...TOWER_41 }; + const state = scenario({ board: tied, hands: [["5H"], ["9I"]] }); + play(state, 0, place("5H")); + assert.equal(state.phase, "survivor"); + assert.throws(() => applyMove(state, announce, 0), /before placing a tile or while buying/); + assert.throws(() => applyMove(state, announce, 1), /not your turn/); +}); + +test("§11.2 final scoring: bonuses for every active chain, then all stock sold at current prices", () => { + // Both chains are safe at size 11: minor tier, $700 a share, bonuses $7,000 / $3,500. + const state = scenario({ + board: { ...SAFE_TOWER, ...chainAt("luxor", row("C", 1, 11)) }, + hands: [["9G"], ["9I"], ["11I"]], + shares: [{ tower: 5, luxor: 2, festival: 6 }, { tower: 3 }, { luxor: 4 }], + }); + play(state, 0, announce); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.deepEqual( + entries(state, "bonuses").map(({ chain, payouts }) => ({ chain, payouts })), + [ + { + chain: "tower", + payouts: [ + { seat: 0, amount: 7000 }, + { seat: 1, amount: 3500 }, + ], + }, + { + chain: "luxor", + payouts: [ + { seat: 0, amount: 3500 }, + { seat: 2, amount: 7000 }, + ], + }, + ] + ); + assert.deepEqual( + state.seats.map((seat) => seat.cash), + [6000 + 7000 + 3500 + 5 * 700 + 2 * 700, 6000 + 3500 + 3 * 700, 6000 + 7000 + 4 * 700] + ); + assert.equal(state.seats[0]!.shares.tower, 0); + assert.equal(state.bank.tower, 25); + assert.equal(state.bank.luxor, 25); + assert.equal(state.seats[0]!.shares.festival, 6, "§11.2.3 stock in chains not on the board is worthless"); + assert.equal(state.bank.festival, 19); + assert.deepEqual(wrapper.scores(state), [21400, 11600, 15800]); + assert.deepEqual(wrapper.rankings(state), [1, 3, 2]); + assert.deepEqual(entries(state, "result"), [{ type: "result", cash: [21400, 11600, 15800], ranks: [1, 3, 2] }]); +}); + +test("§11.2.4 tied players share the victory", () => { + const state = scenario({ board: SAFE_TOWER, hands: [["9G"], ["9I"], ["11I"]], cash: [5000, 3000, 5000] }); + play(state, 0, announce); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.deepEqual(wrapper.rankings(state), [1, 3, 1]); +}); + +test("§13 scores are 0 during play while holdings are private, then the final cash", () => { + const state = scenario({ seats: 2, board: SAFE_TOWER, hands: [["9G"], ["9I"]], cash: [4000, 7000] }); + assert.deepEqual(wrapper.scores(state), [0, 0]); + play(state, 0, announce); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.deepEqual(wrapper.scores(state), [4000, 7000]); +}); + +test("§13 scores are live cash while holdings are public", () => { + const state = scenario({ + seats: 2, + board: SAFE_TOWER, + hands: [["9G"], ["9I"]], + cash: [4000, 7000], + options: { publicHoldings: true }, + }); + assert.deepEqual(wrapper.scores(state), [4000, 7000]); +}); + +test("§11.1 stall rule: the game ends after a full round in which no tile was placed", () => { + const state = scenario({ board: chainAt("tower", ["1A", "2A"]), hands: [["9G"], [], []], poolOnly: true }); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.equal(state.activeSeat, 1); + assert.equal(state.phase, "buy"); + play(state, 1, buy()); + play(state, 2, buy()); + assert.equal(state.ended, false, "seat 0 placed a tile, so this round still had a placement"); + assert.equal(state.activeSeat, 0); + play(state, 0, buy()); + assert.equal(state.ended, true); + assert.deepEqual(entries(state, "gameEnd"), [{ type: "gameEnd", reason: "stall" }]); +}); + +test("§11.1 stall rule: a round of automatically skipped turns ends the game without hanging", () => { + const state = scenario({ hands: [["9G"], [], []], poolOnly: true }); + play(state, 0, place("9G")); + assert.equal(state.ended, true); + assert.deepEqual(entries(state, "gameEnd"), [{ type: "gameEnd", reason: "stall" }]); + assert.deepEqual( + state.log.filter((e) => e.type === "turn").map((e) => (e.type === "turn" ? e.seat : -1)), + [0, 1, 2, 0] + ); +}); + +test("automatic turn advances stop with a clear error if the stall rule ever fails to end the game", () => { + const state = scenario({ hands: [["9G"], [], []], poolOnly: true }); + state.seats[0]!.hand = []; + state.turnsWithoutPlacement = -1000; + assert.throws(() => startTurn(state), /Deadlock/); +}); + +test("no move is accepted after the game has ended", () => { + const state = scenario({ board: SAFE_TOWER, hands: [["9G"], ["9I"]] }); + play(state, 0, announce); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.throws(() => applyMove(state, buy(), 1), /ended/); +}); diff --git a/packages/engine/src/fourhands.spec.ts b/packages/engine/src/fourhands.spec.ts new file mode 100644 index 0000000..b4b3cdd --- /dev/null +++ b/packages/engine/src/fourhands.spec.ts @@ -0,0 +1,166 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js"; +import type { GameState } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +const FOUR_HANDS = { twoPlayerMode: "fourHands" }; +const place = (tile: string) => ({ type: "place", tile }); +const buy = { type: "buy", shares: {} }; + +function play(state: GameState, player: number, move: unknown): GameState { + wrapper.move(state, move, player); + checkInvariants(state); + return state; +} + +test("§15 fourHands: two players get four seats; player A has seats 1 and 3, player B seats 2 and 4", () => { + const state = wrapper.init(2, [], FOUR_HANDS, "four"); + assert.equal(state.players, 2); + assert.equal(state.seats.length, 4); + assert.deepEqual(state.seatOwner, [0, 1, 0, 1]); + for (const seat of state.seats) { + assert.equal(seat.cash, 6000); + assert.equal(seat.hand.length, 6); + } + checkInvariants(state); +}); + +test("§15 fourHands: currentPlayer maps the acting seat to the player who controls it", () => { + for (const [activeSeat, player] of [ + [0, 0], + [1, 1], + [2, 0], + [3, 1], + ] as const) { + const state = scenario({ hands: [["9G"], ["9I"], ["11I"], ["12G"]], activeSeat, options: FOUR_HANDS }); + assert.equal(wrapper.currentPlayer(state), player); + } +}); + +test("§15 fourHands: only the controlling player may move for a seat", () => { + const state = scenario({ hands: [["9G"], ["9I"], ["11I"], ["12G"]], activeSeat: 2, options: FOUR_HANDS }); + assert.throws(() => wrapper.move(state, place("11I"), 1), /not your turn/); + play(state, 0, place("11I")); + assert.equal(state.activeSeat, 3); + assert.equal(wrapper.currentPlayer(state), 1); +}); + +test("§15 fourHands: during disposal currentPlayer is the controller of the disposing seat", () => { + const board = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + const state = scenario({ + board, + hands: [["4A"], ["9I"], ["11I"], ["12G"]], + shares: [{}, {}, {}, { luxor: 2 }], + options: FOUR_HANDS, + }); + play(state, 0, place("4A")); + assert.equal(state.phase, "dispose"); + assert.equal(wrapper.currentPlayer(state), 1); + assert.throws(() => wrapper.move(state, { type: "dispose", sell: 0, trade: 0 }, 0), /not your turn/); + play(state, 1, { type: "dispose", sell: 2, trade: 0 }); + assert.equal(wrapper.currentPlayer(state), 0); +}); + +test("§15 fourHands never uses the bank shareholder", () => { + const board = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + const state = scenario({ + board, + hands: [["4A"], ["9I"], ["11I"], ["12G"]], + shares: [{}, { luxor: 1 }], + options: FOUR_HANDS, + }); + const poolBefore = state.pool.length; + play(state, 0, place("4A")); + const bonus = state.log.find((e) => e.type === "bonuses"); + assert.ok(bonus?.type === "bonuses"); + assert.equal(bonus.bank, undefined); + assert.deepEqual(bonus.payouts, [{ seat: 1, amount: 3000 }]); + assert.equal(state.pool.length, poolBefore); + assert.deepEqual(state.bankTiles, []); +}); + +test("§13/§15 fourHands: stripSecret shows a player both of their own seats and nothing of the other's", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + shares: [{ tower: 1 }, { tower: 2 }, { tower: 3 }, { tower: 4 }], + cash: [1000, 2000, 3000, 4000], + options: FOUR_HANDS, + }); + for (const [player, own, other] of [ + [0, [0, 2], [1, 3]], + [1, [1, 3], [0, 2]], + ] as const) { + const view = wrapper.stripSecret(state, player); + for (const seat of own) { + assert.deepEqual(view.seats[seat]!.hand, state.seats[seat]!.hand); + assert.equal(view.seats[seat]!.cash, state.seats[seat]!.cash); + assert.equal(view.seats[seat]!.shares.tower, state.seats[seat]!.shares.tower); + } + for (const seat of other) { + assert.deepEqual(view.seats[seat]!.hand, [-1]); + assert.equal(view.seats[seat]!.cash, -1); + assert.equal(view.seats[seat]!.shares.tower, -1); + } + assert.equal(view.seed, ""); + assert.ok(view.pool.every((tile) => tile === -1)); + } + const spectator = wrapper.stripSecret(state, undefined); + assert.ok(spectator.seats.every((seat) => seat.cash === -1 && seat.hand.every((tile) => tile === -1))); +}); + +test("§13/§15 fourHands: scores and rankings are per player; scores stay 0 during play with private holdings", () => { + const state = scenario({ hands: [["9G"], ["9I"], ["11I"], ["12G"]], options: FOUR_HANDS }); + assert.deepEqual(wrapper.scores(state), [0, 0]); + assert.equal(wrapper.rankings(state).length, 2); +}); + +test("§15 fourHands: the player controlling the single richest seat wins; seats are not combined", () => { + // Player A: seats 1 and 3 hold $9,000 and $1,000 ($10,000 combined). + // Player B: seats 2 and 4 hold $8,000 and $8,500 ($16,500 combined) but no single richer seat. + const state = scenario({ + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + cash: [9000, 8000, 1000, 8500], + options: FOUR_HANDS, + }); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.equal(state.ended, true); + assert.deepEqual(wrapper.scores(state), [9000, 8500]); + assert.deepEqual(wrapper.rankings(state), [1, 2]); +}); + +test("§15 fourHands: equal richest seats share the victory", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + cash: [7000, 7000, 1000, 2000], + options: FOUR_HANDS, + }); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.deepEqual(wrapper.rankings(state), [1, 1]); +}); + +test("§16 fourHands: a dropping player loses both seats; one player is left, so the game ends", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + activeSeat: 1, + cash: [9000, 3000, 9500, 2000], + options: FOUR_HANDS, + }); + wrapper.dropPlayer(state, 0); + assert.deepEqual( + state.seats.map((seat) => seat.dropped), + [true, false, true, false] + ); + assert.equal(state.ended, true); + assert.deepEqual(wrapper.scores(state), [9500, 3000]); + assert.deepEqual(wrapper.rankings(state), [2, 1], "§16 the dropped player ranks last despite the richest seat"); + checkInvariants(state); +}); diff --git a/packages/engine/src/hidden.spec.ts b/packages/engine/src/hidden.spec.ts new file mode 100644 index 0000000..0105b17 --- /dev/null +++ b/packages/engine/src/hidden.spec.ts @@ -0,0 +1,285 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CHAIN_IDS } from "./config.js"; +import { legalMoves } from "./legal.js"; +import { applyMove, currentSeat } from "./moves.js"; +import { initGame } from "./setup.js"; +import { parseTile } from "./tiles.js"; +import { chainAt, scenario } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; +import { simpleLine } from "./simple.js"; +import { HIDDEN, seatsOf } from "./view.js"; +import * as wrapper from "../wrapper.js"; + +const OPTION_SETS: Record[] = [ + {}, + { publicHoldings: true }, + { teamPlay: true }, + { twoPlayerMode: "fourHands" }, + { twoPlayerMode: "fourHands", publicHoldings: true }, +]; + +function lcg(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (Math.imul(s, 1664525) + 1013904223) >>> 0; + return s / 2 ** 32; + }; +} + +/** + * Plays a random game, calling `inspect` on the starting state, after every `every`-th move, + * and on the final state. + */ +function randomGame( + players: number, + options: Record, + seed: string, + inspect: (state: GameState) => void, + every = 1 +) { + const state = initGame(players, options, seed); + const random = lcg(seed.length * 7919 + players); + inspect(state); + for (let moveCount = 1; !state.ended; moveCount++) { + const moves = legalMoves(state); + // Announce rarely so games run long enough to reach mergers and late-game positions. + const pool = random() < 0.05 ? moves : moves.filter((move) => move.type !== "announce"); + const move = (pool.length > 0 ? pool : moves)[Math.floor(random() * (pool.length || moves.length))]!; + applyMove(state, move, currentSeat(state)!); + if (moveCount % every === 0 || state.ended) { + inspect(state); + } + } + return state; +} + +function viewers(state: GameState): (number | undefined)[] { + return [...Array.from({ length: state.players }, (_, player) => player), undefined]; +} + +/** The state with every field the viewer may not see replaced by a fixed marker, for comparison. */ +function withoutSecrets(state: GameState, player: number | undefined): unknown { + const own = seatsOf(state, player); + const holdingsPublic = state.options.publicHoldings || state.ended; + return { + ...state, + seed: "", + rngCounter: 0, + pool: state.pool.length, + seats: state.seats.map((seat, index) => + own.includes(index) + ? seat + : { + ...seat, + hand: seat.hand.length, + ...(holdingsPublic ? {} : { cash: "hidden", shares: "hidden" }), + } + ), + }; +} + +test("§13 each viewer's state hides exactly the private fields and passes everything else through", () => { + for (let players = 2; players <= 6; players++) { + for (const options of OPTION_SETS) { + randomGame( + players, + options, + `view-${players}-${JSON.stringify(options)}`, + (state) => { + const before = structuredClone(state); + for (const player of viewers(state)) { + const view = wrapper.stripSecret(state, player); + const own = seatsOf(state, player); + const holdingsPublic = state.options.publicHoldings || state.ended; + + assert.equal(view.seed, "", "§13 the seed (which fixes the pool order) is never sent"); + assert.equal(view.rngCounter, 0); + assert.equal(view.pool.length, state.pool.length); + assert.ok( + view.pool.every((tile) => tile === HIDDEN), + "§13 the pool order is always private" + ); + + view.seats.forEach((seat, index) => { + if (own.includes(index)) { + assert.deepEqual(seat, state.seats[index], "a player sees all of their own seat"); + return; + } + assert.equal(seat.hand.length, state.seats[index]!.hand.length); + assert.ok( + seat.hand.every((tile) => tile === HIDDEN), + "§13 other players' hands are private" + ); + if (holdingsPublic) { + assert.equal(seat.cash, state.seats[index]!.cash); + assert.deepEqual(seat.shares, state.seats[index]!.shares); + } else { + assert.equal(seat.cash, HIDDEN, "§13 other players' cash is private"); + assert.ok( + CHAIN_IDS.every((chain) => seat.shares[chain] === HIDDEN), + "§13 other players' stock is private" + ); + } + }); + + const masked = withoutSecrets(view, player) as Record; + const expected = withoutSecrets(state, player) as Record; + assert.deepEqual(masked, expected, "§13 the board, chains, bank, merger and log stay public"); + } + assert.deepEqual(state, before, "stripSecret never changes the real state"); + }, + 3 + ); + } + } +}); + +test("§13 a viewer cannot tell apart games that differ only in what is hidden from them", () => { + for (let players = 2; players <= 6; players++) { + for (const options of OPTION_SETS) { + randomGame( + players, + options, + `indist-${players}-${JSON.stringify(options)}`, + (state) => { + for (const player of viewers(state)) { + const own = seatsOf(state, player); + const variant = structuredClone(state); + variant.seed = `${state.seed}-different`; + variant.rngCounter += 17; + variant.pool.reverse(); + const other = variant.seats.findIndex((seat, index) => !own.includes(index) && seat.hand.length > 0); + if (other >= 0 && variant.pool.length > 0) { + const opponent = variant.seats[other]!; + [opponent.hand[0], variant.pool[0]] = [variant.pool[0]!, opponent.hand[0]!]; + } + if (!state.options.publicHoldings && !state.ended) { + variant.seats.forEach((seat, index) => { + if (!own.includes(index)) { + seat.cash += 100; + seat.shares.tower += 1; + } + }); + } + assert.deepEqual( + JSON.stringify(wrapper.stripSecret(variant, player)), + JSON.stringify(wrapper.stripSecret(state, player)), + `viewer ${player} could distinguish hidden information` + ); + } + }, + 10 + ); + } + } +}); + +function loggedTiles(entry: LogEntry): number[] { + switch (entry.type) { + case "turnOrder": + case "discarded": + return entry.tiles; + case "merger": + case "bankTile": + return [entry.tile]; + case "bonuses": + return entry.bank?.tile != null ? [entry.bank.tile] : []; + case "move": + return entry.move.type === "place" ? [parseTile(entry.move.tile)!] : []; + default: + return []; + } +} + +test("§13 the log never names a tile that is still in the pool or in any hand", () => { + for (let players = 2; players <= 6; players++) { + for (const options of OPTION_SETS) { + randomGame(players, options, `log-${players}-${JSON.stringify(options)}`, (state) => { + const secret = new Set([...state.pool, ...state.seats.flatMap((seat) => seat.hand)]); + for (const entry of state.log) { + for (const tile of loggedTiles(entry)) { + assert.ok(!secret.has(tile), `${entry.type} names a private tile`); + } + if (entry.type === "drew") { + assert.deepEqual(Object.keys(entry).sort(), ["count", "seat", "type"], "§13 draws only show how many"); + } + } + const serialized = JSON.stringify(state.log); + assert.ok(!serialized.includes(state.seed), "§13 the seed never appears in the log"); + }); + } + } +}); + +const TILE_LABEL = /\b(?:1[0-2]|[1-9])[A-I]\b/g; + +test("§13 simple lines never name a tile still in the pool or a hand, or reveal a private holding", () => { + for (let players = 2; players <= 6; players++) { + for (const options of OPTION_SETS) { + let checked = 0; + randomGame(players, options, `simple-${players}-${JSON.stringify(options)}`, (state) => { + const secret = new Set([...state.pool, ...state.seats.flatMap((seat) => seat.hand)]); + // A tile only ever leaves the pool and hands, so each entry is checked once, as soon + // as it exists. + const entries = wrapper.logSlice(state, { start: checked }).log; + checked = state.log.length; + for (const entry of entries) { + const line = entry.simple; + assert.ok(line && !/^[[{"]/.test(line), `${entry.type} has a plain-text simple line`); + for (const label of line.match(TILE_LABEL) ?? []) { + assert.ok(!secret.has(parseTile(label)!), `§13 "${line}" names a private tile`); + } + if (entry.type === "drew") { + assert.equal(line.match(TILE_LABEL), null, "§13 draws only show how many"); + } + assert.ok(!line.includes(state.seed), "§13 the seed never appears in a simple line"); + if (entry.type === "disposed" && !state.options.publicHoldings) { + const { simple: _, ...stored } = entry; + assert.equal( + simpleLine(state, { ...stored, held: stored.held + 7 }), + line, + `§13 "${line}" reveals how many shares were kept` + ); + } + } + }); + } + } +}); + +test("§13 logSlice is the same for every player and spectator", () => { + const state = randomGame(4, {}, "log-same", () => {}); + const spectator = wrapper.logSlice(state, {}); + for (const player of [0, 1, 2, 3]) { + assert.deepEqual(wrapper.logSlice(state, { player }), spectator); + } +}); + +test("§13 after the game ends, holdings and cash become public but hands and the pool stay private", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A", "3A", "4A", "5A", "6A", "7A", "8A", "9A", "10A", "11A"]), + hands: [["9G"], ["9I", "12A"], ["11G"]], + shares: [{}, { luxor: 3 }], + cash: [6000, 4100, 6000], + }); + assert.equal(wrapper.stripSecret(state, 0).seats[1]!.cash, HIDDEN); + applyMove(state, { type: "announce" }, 0); + applyMove(state, { type: "place", tile: "9G" }, 0); + applyMove(state, { type: "buy", shares: {} }, 0); + assert.equal(state.ended, true); + const view = wrapper.stripSecret(state, 0); + assert.equal(view.seats[1]!.cash, 4100); + assert.equal(view.seats[1]!.shares.luxor, 3); + assert.deepEqual(view.seats[1]!.hand, [HIDDEN, HIDDEN]); + assert.ok(view.pool.every((tile) => tile === HIDDEN)); +}); + +test("§13 the engine asks BGS to hash the seed before init, since it fixes hidden tile order", () => { + assert.equal(wrapper.hashSeed, true); +}); + +test("§13 an unknown player index is treated as a spectator", () => { + const state = initGame(3, {}, "unknown-viewer"); + assert.deepEqual(wrapper.stripSecret(state, 9), wrapper.stripSecret(state, undefined)); +}); diff --git a/packages/engine/src/legal.ts b/packages/engine/src/legal.ts new file mode 100644 index 0000000..832d52c --- /dev/null +++ b/packages/engine/src/legal.ts @@ -0,0 +1,92 @@ +import { activeChains } from "./board.js"; +import { CHAIN_IDS, MAX_BUY, type ChainId } from "./config.js"; +import { merger } from "./merger.js"; +import { currentSeat, sanitizeMove } from "./moves.js"; +import { tileLabel } from "./tiles.js"; +import type { GameState, Move, Shares } from "./types.js"; + +function buyCombinations(chains: ChainId[]): Partial[] { + const result: Partial[] = []; + const visit = (from: number, remaining: number, current: Partial) => { + result.push({ ...current }); + if (remaining === 0) { + return; + } + for (let i = from; i < chains.length; i++) { + const chain = chains[i]!; + current[chain] = (current[chain] ?? 0) + 1; + visit(i, remaining - 1, current); + current[chain]! -= 1; + if (current[chain] === 0) { + delete current[chain]; + } + } + }; + visit(0, MAX_BUY, {}); + return result; +} + +function permutations(items: T[]): T[][] { + if (items.length <= 1) { + return [items]; + } + return items.flatMap((item, i) => + permutations([...items.slice(0, i), ...items.slice(i + 1)]).map((rest) => [item, ...rest]) + ); +} + +function candidates(state: GameState): Move[] { + const announce: Move[] = state.phase === "place" || state.phase === "buy" ? [{ type: "announce" }] : []; + return [...announce, ...phaseCandidates(state)]; +} + +function phaseCandidates(state: GameState): Move[] { + switch (state.phase) { + case "place": + return [ + { type: "pass" }, + ...state.seats[state.activeSeat]!.hand.map((tile): Move => ({ type: "place", tile: tileLabel(tile) })), + ]; + case "found": + return CHAIN_IDS.map((chain) => ({ type: "found", chain })); + case "survivor": + return CHAIN_IDS.map((chain) => ({ type: "survivor", chain })); + case "defunctOrder": + return permutations( + CHAIN_IDS.filter((chain) => { + const m = merger(state); + return m.sizes[chain] !== undefined && chain !== m.survivor; + }) + ).map((chains) => ({ type: "defunctOrder", chains })); + case "dispose": { + const m = merger(state); + const held = state.seats[currentSeat(state)!]!.shares[m.current!]; + const moves: Move[] = []; + for (let trade = 0; trade <= held; trade += 2) { + for (let sell = 0; sell + trade <= held; sell++) { + moves.push({ type: "dispose", sell, trade }); + } + } + return moves; + } + case "buy": + return buyCombinations(activeChains(state.board)).map((shares) => ({ type: "buy", shares })); + default: + return []; + } +} + +/** Every move the current seat may make, each one accepted by sanitizeMove. */ +export function legalMoves(state: GameState): Move[] { + if (state.ended) { + return []; + } + return candidates(state).filter((move) => { + try { + sanitizeMove(state, move, currentSeat(state)!); + return true; + } catch { + return false; + } + }); +} diff --git a/packages/engine/src/merger.spec.ts b/packages/engine/src/merger.spec.ts new file mode 100644 index 0000000..bcda09f --- /dev/null +++ b/packages/engine/src/merger.spec.ts @@ -0,0 +1,401 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { activeChains, chainSize } from "./board.js"; +import { applyMove, currentSeat } from "./moves.js"; +import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +const place = (tile: string) => ({ type: "place", tile }); +const dispose = (sell: number, trade: number) => ({ type: "dispose", sell, trade }); +const OTHER_HANDS = [["12I"], ["12G"], ["10I"]]; + +function hands(seat: number, tile: string): string[][] { + return OTHER_HANDS.map((hand, i) => (i === seat ? [tile] : hand)); +} + +function entries(state: GameState, type: T): Extract[] { + return state.log.filter((e): e is Extract => e.type === type); +} + +// tower 1A-3A (3) and luxor 5A-6A (2); 4A merges them. +const TWO_CHAINS = { ...chainAt("tower", ["1A", "2A", "3A"]), ...chainAt("luxor", ["5A", "6A"]) }; + +// Around 5E: tower 1E-4E (4), luxor 6E-8E (3), festival 5F-5G (2), imperial 5C-5D (2). +const AROUND_5E = { + ...chainAt("tower", row("E", 1, 4)), + ...chainAt("luxor", row("E", 6, 8)), + ...chainAt("festival", ["5F", "5G"]), +}; + +test("§7.1 the largest chain survives without a choice", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A") }); + play(state, 0, place("4A")); + assert.deepEqual(entries(state, "mergerPlan"), [{ type: "mergerPlan", survivor: "tower", defunct: ["luxor"] }]); + assert.deepEqual(activeChains(state.board), ["tower"]); + assert.equal(chainSize(state.board, "tower"), 6); + assert.equal(state.phase, "buy"); +}); + +test("§7.1.1 chain sizes are measured before the merging tile is placed", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A") }); + play(state, 0, place("4A")); + assert.deepEqual(entries(state, "merger")[0]?.sizes, { tower: 3, luxor: 2 }); +}); + +test("§7.1.3 tied survivors: mergermaker chooses", () => { + const board = { ...chainAt("tower", ["1A", "2A"]), ...chainAt("luxor", ["4A", "5A"]) }; + const state = scenario({ board, hands: hands(1, "3A"), activeSeat: 1 }); + play(state, 1, place("3A")); + assert.equal(state.phase, "survivor"); + assert.equal(currentSeat(state), 1); + assert.throws(() => applyMove(state, { type: "survivor", chain: "festival" }, 1), /largest/); + play(state, 1, { type: "survivor", chain: "luxor" }); + assert.deepEqual(activeChains(state.board), ["luxor"]); + assert.equal(chainSize(state.board, "luxor"), 5); +}); + +test("§7.1.4 a safe chain takes over an open chain", () => { + const board = { ...chainAt("tower", row("A", 1, 11)), ...chainAt("luxor", ["1C", "2C"]) }; + const state = scenario({ board, hands: hands(0, "1B") }); + play(state, 0, place("1B")); + assert.deepEqual(activeChains(state.board), ["tower"]); + assert.equal(chainSize(state.board, "tower"), 14); +}); + +test("§7.2.1 majority bonuses for the defunct chain use its pre-merger size", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 3 }, { luxor: 1 }] }); + play(state, 0, place("4A")); + assert.deepEqual(entries(state, "bonuses"), [ + { + type: "bonuses", + chain: "luxor", + size: 2, + payouts: [ + { seat: 1, amount: 2000 }, + { seat: 2, amount: 1000 }, + ], + }, + ]); + assert.equal(state.seats[1]!.cash, 8000); + assert.equal(state.seats[2]!.cash, 7000); +}); + +test("§7.2.2 disposal starts with the mergermaker, goes clockwise, and skips players without stock", () => { + const state = scenario({ + seats: 4, + board: TWO_CHAINS, + hands: [["12I"], ["12G"], ["4A"], ["10I"]], + activeSeat: 2, + shares: [{ luxor: 1 }, {}, { luxor: 2 }, { luxor: 1 }], + }); + play(state, 2, place("4A")); + assert.equal(state.phase, "dispose"); + const order: number[] = []; + while (state.phase === "dispose") { + const seat = currentSeat(state)!; + order.push(seat); + play(state, seat, dispose(0, 0)); + } + assert.deepEqual(order, [2, 3, 0]); + assert.equal(state.activeSeat, 2); + assert.equal(state.phase, "buy"); +}); + +test("§7.2.2 only the player who must dispose may move", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 2 }] }); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 1); + assert.throws(() => applyMove(state, dispose(0, 0), 0), /not your turn/); +}); + +test("§7.2.2 selling pays the defunct chain's pre-merger share price", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 3 }, { luxor: 1 }] }); + play(state, 0, place("4A")); + play(state, 1, dispose(3, 0)); + assert.equal(state.seats[1]!.shares.luxor, 0); + assert.equal(state.seats[1]!.cash, 6000 + 2000 + 3 * 200); + assert.equal(state.bank.luxor, 25 - 1); +}); + +test("§7.2.2 trading gives one survivor share for every two defunct shares", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 5 }] }); + play(state, 0, place("4A")); + assert.throws(() => applyMove(state, dispose(0, 3), 1), /two for one/); + play(state, 1, dispose(1, 4)); + assert.equal(state.seats[1]!.shares.tower, 2); + assert.equal(state.seats[1]!.shares.luxor, 0); + assert.equal(state.bank.tower, 23); + assert.equal(state.bank.luxor, 25); +}); + +test("§7.2.2 held shares stay with the player after the chain is gone", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 5 }] }); + play(state, 0, place("4A")); + play(state, 1, dispose(1, 2)); + assert.equal(state.seats[1]!.shares.luxor, 2); + assert.deepEqual(entries(state, "disposed"), [ + { type: "disposed", seat: 1, chain: "luxor", sold: 1, traded: 2, held: 2, proceeds: 200 }, + ]); +}); + +test("§7.2.2 a player cannot dispose of more shares than they hold", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A"), shares: [{}, { luxor: 3 }] }); + play(state, 0, place("4A")); + assert.throws(() => applyMove(state, dispose(2, 2), 1), /do not hold/); + assert.throws(() => applyMove(state, dispose(-1, 0), 1), /non-negative/); +}); + +test("§7.2.2 trades are limited by the survivor shares left in the bank", () => { + const state = scenario({ + board: TWO_CHAINS, + hands: hands(0, "4A"), + shares: [{ tower: 22, luxor: 2 }, { luxor: 6 }], + activeSeat: 0, + }); + play(state, 0, place("4A")); + assert.equal(currentSeat(state), 0); + play(state, 0, dispose(0, 2)); + assert.equal(state.bank.tower, 2); + assert.equal(currentSeat(state), 1); + assert.throws(() => applyMove(state, dispose(0, 6), 1), /enough survivor shares/); + play(state, 1, dispose(0, 4)); + assert.equal(state.bank.tower, 0); + assert.equal(state.seats[1]!.shares.tower, 2); +}); + +test("§7.3 the survivor absorbs defunct tiles, the merging tile and loose tiles connected to it", () => { + const state = scenario({ + board: { ...TWO_CHAINS, "4B": "loose", "4C": "loose", "9C": "loose" }, + hands: hands(0, "4A"), + }); + play(state, 0, place("4A")); + assert.ok(["4A", "4B", "4C", "5A", "6A"].every((label) => state.board[t(label)] === "tower")); + assert.equal(state.board[t("9C")], "loose"); + assert.equal(chainSize(state.board, "tower"), 8); +}); + +test("§7.3 defunct chain names become available again", () => { + const state = scenario({ board: { ...TWO_CHAINS, "9C": "loose" }, hands: [["4A"], ["9D"], ["12I"]] }); + play(state, 0, place("4A")); + play(state, 0, { type: "buy", shares: {} }); + play(state, 1, place("9D")); + play(state, 1, { type: "found", chain: "luxor" }); + assert.equal(chainSize(state.board, "luxor"), 2); +}); + +test("§7.2 defunct chains are resolved largest first", () => { + const state = scenario({ board: AROUND_5E, hands: hands(0, "5E"), shares: [{}, { luxor: 2, festival: 2 }] }); + play(state, 0, place("5E")); + assert.deepEqual(entries(state, "mergerPlan"), [ + { type: "mergerPlan", survivor: "tower", defunct: ["luxor", "festival"] }, + ]); + assert.deepEqual( + entries(state, "bonuses").map((e) => e.chain), + ["luxor"] + ); + play(state, 1, dispose(0, 0)); + assert.deepEqual( + entries(state, "bonuses").map((e) => e.chain), + ["luxor", "festival"] + ); +}); + +test("§7.3 one defunct chain's disposal is completed by all players before the next chain's bonuses", () => { + const state = scenario({ + board: AROUND_5E, + hands: hands(0, "5E"), + shares: [{ luxor: 1, festival: 1 }, { luxor: 2 }, { festival: 3 }], + }); + play(state, 0, place("5E")); + play(state, 0, dispose(1, 0)); + assert.equal(entries(state, "bonuses").length, 1); + play(state, 1, dispose(2, 0)); + const bonusChains = entries(state, "bonuses").map((e) => e.chain); + assert.deepEqual(bonusChains, ["luxor", "festival"]); + const lastLuxorDisposal = Math.max( + ...state.log.flatMap((e, i) => (e.type === "disposed" && e.chain === "luxor" ? [i] : [])) + ); + const festivalBonus = state.log.findIndex((e) => e.type === "bonuses" && e.chain === "festival"); + assert.ok(lastLuxorDisposal < festivalBonus); + assert.equal(currentSeat(state), 0); + play(state, 0, dispose(1, 0)); + assert.equal(currentSeat(state), 2); + play(state, 2, dispose(3, 0)); + assert.deepEqual(activeChains(state.board), ["tower"]); + assert.equal(chainSize(state.board, "tower"), 4 + 3 + 2 + 1); +}); + +test("§7.2 tied defunct chains: the mergermaker chooses their order", () => { + const board = { + ...chainAt("tower", row("E", 1, 4)), + ...chainAt("luxor", ["6E", "7E"]), + ...chainAt("festival", ["5F", "5G"]), + }; + const state = scenario({ board, hands: hands(0, "5E") }); + play(state, 0, place("5E")); + assert.equal(state.phase, "defunctOrder"); + assert.equal(currentSeat(state), 0); + assert.throws(() => applyMove(state, { type: "defunctOrder", chains: ["festival"] }, 0), /every defunct/); + assert.throws(() => applyMove(state, { type: "defunctOrder", chains: ["tower", "festival"] }, 0), /every defunct/); + play(state, 0, { type: "defunctOrder", chains: ["festival", "luxor"] }); + assert.deepEqual(entries(state, "mergerPlan")[0]?.defunct, ["festival", "luxor"]); +}); + +test("§7.2 a tied defunct order must still put larger chains first", () => { + const board = { + ...chainAt("tower", row("E", 1, 4)), + ...chainAt("luxor", row("E", 6, 8)), + ...chainAt("festival", ["5F", "5G"]), + ...chainAt("imperial", ["5C", "5D"]), + }; + const state = scenario({ board, hands: hands(0, "5E") }); + play(state, 0, place("5E")); + assert.equal(state.phase, "defunctOrder"); + assert.throws(() => applyMove(state, { type: "defunctOrder", chains: ["festival", "luxor", "imperial"] }, 0)); + play(state, 0, { type: "defunctOrder", chains: ["luxor", "imperial", "festival"] }); + assert.equal(chainSize(state.board, "tower"), 4 + 3 + 2 + 2 + 1); +}); + +test("§7.1/§7.2 a four-way tie: the mergermaker picks the survivor, then the defunct order", () => { + const board = { + ...chainAt("tower", ["3E", "4E"]), + ...chainAt("luxor", ["6E", "7E"]), + ...chainAt("festival", ["5F", "5G"]), + ...chainAt("imperial", ["5C", "5D"]), + }; + const state = scenario({ board, hands: hands(0, "5E") }); + play(state, 0, place("5E")); + assert.equal(state.phase, "survivor"); + play(state, 0, { type: "survivor", chain: "imperial" }); + assert.equal(state.phase, "defunctOrder"); + play(state, 0, { type: "defunctOrder", chains: ["luxor", "tower", "festival"] }); + assert.deepEqual(activeChains(state.board), ["imperial"]); + assert.equal(chainSize(state.board, "imperial"), 9); +}); + +test("§9.3 after a merger, shares are bought at the survivor's new size", () => { + const state = scenario({ board: TWO_CHAINS, hands: hands(0, "4A") }); + play(state, 0, place("4A")); + play(state, 0, { type: "buy", shares: { tower: 1 } }); + assert.equal(state.seats[0]!.cash, 6000 - 600); +}); + +test("§7/§10 four-way merger: survivor tie, tied defunct order, and the survivor's bank shares running out", () => { + // Around 5E: tower 2E-4E (3) and luxor 6E-8E (3) tie for largest; imperial 5C-5D (2) and + // festival 5F-5G (2) tie as defunct chains. The bank has only 3 luxor shares left. + const board = { + ...chainAt("tower", row("E", 2, 4)), + ...chainAt("luxor", row("E", 6, 8)), + ...chainAt("imperial", ["5C", "5D"]), + ...chainAt("festival", ["5F", "5G"]), + }; + const state = scenario({ + seats: 4, + board, + hands: [["12I"], ["5E"], ["12G"], ["10I"]], + activeSeat: 1, + shares: [ + { luxor: 22, imperial: 3 }, + { tower: 4 }, + { tower: 2, imperial: 3 }, + { tower: 2, imperial: 2, festival: 2 }, + ], + }); + assert.equal(state.bank.luxor, 3); + + play(state, 1, place("5E")); + assert.equal(state.phase, "survivor"); + assert.equal(currentSeat(state), 1); + play(state, 1, { type: "survivor", chain: "luxor" }); + assert.equal(state.phase, "defunctOrder"); + assert.throws(() => applyMove(state, { type: "defunctOrder", chains: ["imperial", "tower", "festival"] }, 1)); + play(state, 1, { type: "defunctOrder", chains: ["tower", "imperial", "festival"] }); + + // Tower (minor, size 3: $300, bonuses $3,000 / $1,500): seat 1 first, seats 2 and 3 tie for second. + assert.equal(currentSeat(state), 1); + play(state, 1, dispose(2, 2)); + play(state, 2, dispose(0, 0)); + play(state, 3, dispose(0, 2)); + assert.equal(state.bank.luxor, 1); + + // Imperial (major, size 2: $400, bonuses $4,000 / $2,000): seats 0 and 2 tie for first. + // Seat 1 holds none and is skipped; seat 2's trade takes the last luxor share. + assert.equal(currentSeat(state), 2); + play(state, 2, dispose(1, 2)); + assert.equal(state.bank.luxor, 0); + assert.throws(() => applyMove(state, dispose(0, 2), 3), /enough survivor shares/); + play(state, 3, dispose(2, 0)); + assert.throws(() => applyMove(state, dispose(0, 2), 0), /enough survivor shares/); + play(state, 0, dispose(0, 0)); + + // Festival (medium, size 2: $300, bonuses $3,000 / $1,500): seat 3 is the single holder. + assert.throws(() => applyMove(state, dispose(0, 2), 3), /enough survivor shares/); + play(state, 3, dispose(2, 0)); + + assert.deepEqual( + entries(state, "bonuses").map(({ chain, size, payouts }) => ({ chain, size, payouts })), + [ + { + chain: "tower", + size: 3, + payouts: [ + { seat: 1, amount: 3000 }, + { seat: 2, amount: 800 }, + { seat: 3, amount: 800 }, + ], + }, + { + chain: "imperial", + size: 2, + payouts: [ + { seat: 0, amount: 3000 }, + { seat: 2, amount: 3000 }, + ], + }, + { chain: "festival", size: 2, payouts: [{ seat: 3, amount: 4500 }] }, + ] + ); + assert.deepEqual( + entries(state, "disposed").map(({ seat, chain }) => [chain, seat]), + [ + ["tower", 1], + ["tower", 2], + ["tower", 3], + ["imperial", 2], + ["imperial", 3], + ["imperial", 0], + ["festival", 3], + ] + ); + + assert.deepEqual( + state.seats.map((seat) => seat.cash), + [6000 + 3000, 6000 + 3000 + 600, 6000 + 800 + 3000 + 400, 6000 + 800 + 800 + 4500 + 600] + ); + const holdings = state.seats.map(({ shares }) => ({ + tower: shares.tower, + luxor: shares.luxor, + imperial: shares.imperial, + festival: shares.festival, + })); + assert.deepEqual(holdings, [ + { tower: 0, luxor: 22, imperial: 3, festival: 0 }, + { tower: 0, luxor: 1, imperial: 0, festival: 0 }, + { tower: 2, luxor: 1, imperial: 0, festival: 0 }, + { tower: 0, luxor: 1, imperial: 0, festival: 0 }, + ]); + assert.deepEqual( + { tower: state.bank.tower, luxor: state.bank.luxor, imperial: state.bank.imperial, festival: state.bank.festival }, + { tower: 23, luxor: 0, imperial: 22, festival: 25 } + ); + + assert.deepEqual(activeChains(state.board), ["luxor"]); + assert.equal(chainSize(state.board, "luxor"), 3 + 3 + 2 + 2 + 1); + assert.equal(state.activeSeat, 1); +}); diff --git a/packages/engine/src/merger.ts b/packages/engine/src/merger.ts new file mode 100644 index 0000000..d9f97ff --- /dev/null +++ b/packages/engine/src/merger.ts @@ -0,0 +1,169 @@ +import { bankHolding, placeNextBankTile } from "./bank.js"; +import { chainSize, connectedLoose } from "./board.js"; +import { computeBonuses } from "./bonuses.js"; +import { CHAIN_IDS, type ChainId } from "./config.js"; +import { majorityBonus, minorityBonus, sharePrice } from "./prices.js"; +import type { Tile } from "./tiles.js"; +import type { GameState, MergerState } from "./types.js"; + +export function merger(state: GameState): MergerState { + if (!state.merger) { + throw new Error("No merger is in progress"); + } + return state.merger; +} + +/** rules.md §7.1: the largest chains by pre-merger size; more than one means a tie. */ +export function survivorCandidates(m: MergerState): ChainId[] { + const chains = CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined); + const largest = Math.max(...chains.map((chain) => m.sizes[chain]!)); + return chains.filter((chain) => m.sizes[chain] === largest); +} + +/** rules.md §7.2: defunct chains must be resolved largest first; only ties are a choice. */ +export function isValidDefunctOrder(m: MergerState, order: ChainId[]): boolean { + const expected = CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined && chain !== m.survivor); + if (order.length !== expected.length || new Set(order).size !== order.length) { + return false; + } + if (!order.every((chain) => expected.includes(chain))) { + return false; + } + return order.every((chain, i) => i === 0 || m.sizes[order[i - 1]!]! >= m.sizes[chain]!); +} + +/** Starts a merger for a tile already on the board as a loose tile, placed by a player or the bank. */ +export function startMerger(state: GameState, tile: Tile, chains: ChainId[], byBank = false): void { + const sizes = Object.fromEntries(chains.map((chain) => [chain, chainSize(state.board, chain)])); + state.merger = { + tile, + mergermaker: state.activeSeat, + sizes, + survivor: null, + defunct: [], + current: null, + disposers: [], + }; + state.log.push({ type: "merger", seat: state.activeSeat, tile, sizes, ...(byBank ? { byBank: true as const } : {}) }); + const candidates = survivorCandidates(state.merger); + if (candidates.length > 1) { + state.phase = "survivor"; + return; + } + setSurvivor(state, candidates[0]!); +} + +export function setSurvivor(state: GameState, survivor: ChainId): void { + const m = merger(state); + m.survivor = survivor; + const defunct = CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined && chain !== survivor).sort( + (a, b) => m.sizes[b]! - m.sizes[a]! + ); + const sizes = defunct.map((chain) => m.sizes[chain]!); + if (new Set(sizes).size !== sizes.length) { + state.phase = "defunctOrder"; + return; + } + setDefunctOrder(state, defunct); +} + +export function setDefunctOrder(state: GameState, order: ChainId[]): void { + const m = merger(state); + m.defunct = [...order]; + state.log.push({ type: "mergerPlan", survivor: m.survivor!, defunct: [...order] }); + resolveNextDefunct(state); +} + +/** rules.md §7.2: pay bonuses for the next defunct chain, then start its stock disposal. */ +function resolveNextDefunct(state: GameState): void { + const m = merger(state); + for (;;) { + const chain = m.defunct.shift(); + if (chain === undefined) { + completeMerger(state); + return; + } + m.current = chain; + payBonuses(state, chain, m.sizes[chain]!, "wait"); + const seats = state.seats.length; + m.disposers = Array.from({ length: seats }, (_, i) => (m.mergermaker + i) % seats).filter( + (seat) => state.seats[seat]!.shares[chain] > 0 + ); + if (m.disposers.length > 0) { + state.phase = "dispose"; + return; + } + } +} + +/** + * rules.md §10, plus §12.1.1-2 in two-player bank mode: the bank draws a tile and competes as a + * shareholder, and whatever it wins is not paid out. The drawn tile waits to be placed (§12.1.4). + */ +export function payBonuses(state: GameState, chain: ChainId, size: number, bankTileFate: "wait" | "setAside"): void { + const bank = bankHolding(state, bankTileFate); + const holdings = state.seats.map((seat) => seat.shares[chain]); + const amounts = computeBonuses( + bank ? [...holdings, bank.shares] : holdings, + majorityBonus(chain, size), + minorityBonus(chain, size) + ); + const payouts = holdings.flatMap((_, seat) => (amounts[seat]! > 0 ? [{ seat, amount: amounts[seat]! }] : [])); + for (const { seat, amount } of payouts) { + state.seats[seat]!.cash += amount; + } + state.log.push({ + type: "bonuses", + chain, + size, + payouts, + ...(bank ? { bank: { ...bank, amount: amounts[holdings.length]! } } : {}), + }); +} + +/** The most defunct shares `seat` may trade in now (§7.2: 2-for-1, limited by the bank). */ +export function maxTrade(state: GameState, seat: number): number { + const m = merger(state); + const held = state.seats[seat]!.shares[m.current!]; + const byBank = state.bank[m.survivor!] * 2; + const limit = Math.min(held, byBank); + return limit - (limit % 2); +} + +export function dispose(state: GameState, seat: number, sell: number, trade: number): void { + const m = merger(state); + const chain = m.current!; + const survivor = m.survivor!; + const player = state.seats[seat]!; + const held = player.shares[chain] - sell - trade; + const proceeds = sell * sharePrice(chain, m.sizes[chain]!); + player.shares[chain] -= sell + trade; + state.bank[chain] += sell + trade; + player.cash += proceeds; + player.shares[survivor] += trade / 2; + state.bank[survivor] -= trade / 2; + state.log.push({ type: "disposed", seat, chain, sold: sell, traded: trade, held, proceeds }); + m.disposers.shift(); + if (m.disposers.length > 0) { + return; + } + resolveNextDefunct(state); +} + +/** rules.md §7.3: the survivor absorbs the defunct chains, the merging tile and connected loose tiles. */ +function completeMerger(state: GameState): void { + const m = merger(state); + const survivor = m.survivor!; + for (let tile = 0; tile < state.board.length; tile++) { + const cell = state.board[tile] ?? null; + if (cell !== null && cell !== "loose" && cell !== survivor && m.sizes[cell] !== undefined) { + state.board[tile] = survivor; + } + } + for (const tile of connectedLoose(state.board, m.tile)) { + state.board[tile] = survivor; + } + state.log.push({ type: "merged", survivor, size: chainSize(state.board, survivor) }); + state.merger = null; + placeNextBankTile(state); +} diff --git a/packages/engine/src/moves.ts b/packages/engine/src/moves.ts new file mode 100644 index 0000000..032559b --- /dev/null +++ b/packages/engine/src/moves.ts @@ -0,0 +1,316 @@ +import { activeChains, chainSize, connectedLoose, placementEffect, playableTiles, tileLegality } from "./board.js"; +import { defaultMove } from "./autoplay.js"; +import { AUTO_MOVE_LIMIT, CHAIN_IDS, MAX_BUY, isChainId, type ChainId } from "./config.js"; +import { + dispose, + isValidDefunctOrder, + maxTrade, + merger, + setDefunctOrder, + setSurvivor, + startMerger, + survivorCandidates, +} from "./merger.js"; +import { sharePrice } from "./prices.js"; +import { canAnnounce, endGame } from "./scoring.js"; +import { parseTile, tileLabel, type Tile } from "./tiles.js"; +import { endTurn, enterBuyPhase } from "./turn.js"; +import type { GameState, Move, Shares } from "./types.js"; + +export function currentSeat(state: GameState): number | undefined { + if (state.ended) { + return undefined; + } + // During stock disposal the player who must act is often not the one whose turn it is. + return state.phase === "dispose" ? merger(state).disposers[0] : state.activeSeat; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Validates an untrusted move against the current state and rebuilds it from whitelisted + * fields only. Throws before anything is mutated. + */ +export function sanitizeMove(state: GameState, raw: unknown, seat: number): Move { + if (state.ended) { + throw new Error("The game has ended"); + } + if (seat !== currentSeat(state)) { + throw new Error("It is not your turn"); + } + if (!isRecord(raw)) { + throw new Error("A move must be an object"); + } + if (raw.type === "announce") { + // rules.md §4/§11.1: before placing or during the buy step, checked at this moment. + if (state.phase !== "place" && state.phase !== "buy") { + throw new Error("The end can only be announced before placing a tile or while buying"); + } + if (!canAnnounce(state)) { + throw new Error("The game cannot be ended now"); + } + return { type: "announce" }; + } + if (state.phase === "place" && raw.type === "pass") { + // Only reachable at an announcement point (rules.md §4) with nothing to place. + if (playableTiles(state, seat).length > 0) { + throw new Error("You must place a tile"); + } + return { type: "pass" }; + } + if (raw.type !== state.phase) { + throw new Error(`Expected a "${state.phase}" move`); + } + switch (state.phase) { + case "place": { + const tile = parseTile(raw.tile); + if (tile === undefined) { + throw new Error("Choose a tile such as 5C"); + } + if (!state.seats[seat]!.hand.includes(tile)) { + throw new Error(`Tile ${tileLabel(tile)} is not in your hand`); + } + if (tileLegality(state.board, tile) !== "playable") { + throw new Error(`Tile ${tileLabel(tile)} cannot be played now`); + } + return { type: "place", tile: tileLabel(tile) }; + } + case "found": { + if (!isChainId(raw.chain)) { + throw new Error("Choose a chain to found"); + } + if (activeChains(state.board).includes(raw.chain)) { + throw new Error("That chain is already on the board"); + } + return { type: "found", chain: raw.chain }; + } + case "survivor": { + if (!isChainId(raw.chain) || !survivorCandidates(merger(state)).includes(raw.chain)) { + throw new Error("Choose one of the largest chains as the survivor"); + } + return { type: "survivor", chain: raw.chain }; + } + case "defunctOrder": { + const chains = raw.chains; + if (!Array.isArray(chains) || !chains.every(isChainId) || !isValidDefunctOrder(merger(state), chains)) { + throw new Error("List every defunct chain, largest first"); + } + return { type: "defunctOrder", chains: [...chains] }; + } + case "dispose": { + const { sell, trade } = raw; + if (!Number.isInteger(sell) || !Number.isInteger(trade) || (sell as number) < 0 || (trade as number) < 0) { + throw new Error("Sell and trade must be non-negative integers"); + } + const held = state.seats[seat]!.shares[merger(state).current!]; + if ((sell as number) + (trade as number) > held) { + throw new Error("You do not hold that many shares"); + } + if ((trade as number) % 2 !== 0) { + throw new Error("Shares are traded two for one"); + } + if ((trade as number) > maxTrade(state, seat)) { + throw new Error("The bank does not have enough survivor shares for that trade"); + } + return { type: "dispose", sell: sell as number, trade: trade as number }; + } + case "buy": { + if (!isRecord(raw.shares)) { + throw new Error("Shares must be an object of chain counts"); + } + const shares: Partial = {}; + let total = 0; + let cost = 0; + const active = activeChains(state.board); + for (const [key, count] of Object.entries(raw.shares)) { + if (!isChainId(key)) { + throw new Error(`Unknown chain ${key}`); + } + if (!Number.isInteger(count) || (count as number) < 0) { + throw new Error("Share counts must be non-negative integers"); + } + const n = count as number; + if (n === 0) { + continue; + } + if (!active.includes(key)) { + throw new Error("You can only buy shares in chains on the board"); + } + if (state.bank[key] < n) { + throw new Error("The bank does not have that many shares"); + } + shares[key] = n; + total += n; + cost += n * sharePrice(key, chainSize(state.board, key)); + } + if (total > MAX_BUY) { + throw new Error(`You can buy at most ${MAX_BUY} shares per turn`); + } + if (cost > state.seats[seat]!.cash) { + throw new Error("You cannot afford those shares"); + } + return { type: "buy", shares }; + } + default: + throw new Error("No move is expected now"); + } +} + +/** Applies a move by `seat`, mutating and returning the state. */ +export function applyMove(state: GameState, raw: unknown, seat: number): GameState { + const move = sanitizeMove(state, raw, seat); + perform(state, move, seat, false); + autoPlayDropped(state); + return state; +} + +/** Real players with at least one seat that has not dropped. */ +export function remainingPlayers(state: GameState): number { + return new Set(state.seatOwner.filter((_, seat) => !state.seats[seat]!.dropped)).size; +} + +/** + * rules.md §16: drops all of a real player's seats at once. If that leaves one player or + * none, the game ends and is scored immediately; otherwise dropped seats are played + * automatically whenever they must act. + */ +export function dropPlayerSeats(state: GameState, player: number): GameState { + const seats = state.seatOwner.flatMap((owner, seat) => (owner === player ? [seat] : [])); + if (seats.length === 0) { + throw new Error(`Unknown player ${player}`); + } + if (state.ended || seats.every((seat) => state.seats[seat]!.dropped)) { + return state; + } + for (const seat of seats) { + state.seats[seat]!.dropped = true; + state.log.push({ type: "dropped", seat }); + } + if (remainingPlayers(state) <= 1) { + abandonTurn(state); + endGame(state, "dropped"); + return state; + } + autoPlayDropped(state); + return state; +} + +/** rules.md §16: an unfinished merger is abandoned and waiting bank tiles leave the game. */ +function abandonTurn(state: GameState): void { + state.merger = null; + state.pendingTile = null; + if (state.bankTiles.length > 0) { + state.removed.push(...state.bankTiles); + state.bankTiles = []; + } +} + +/** + * Plays default moves (rules.md §16) for as long as the seat that must act has dropped. That + * seat is often not the active one, e.g. a dropped holder during merger disposal. With every + * seat dropped this plays the game to its end. + */ +function autoPlayDropped(state: GameState): void { + for (let moves = 0; ; moves++) { + const seat = currentSeat(state); + if (seat === undefined || !state.seats[seat]!.dropped) { + return; + } + if (moves >= AUTO_MOVE_LIMIT) { + throw new Error(`Deadlock: ${AUTO_MOVE_LIMIT} moves were auto-played without the game ending`); + } + perform(state, sanitizeMove(state, defaultMove(state, seat), seat), seat, true); + } +} + +function perform(state: GameState, move: Move, seat: number, auto: boolean): void { + state.log.push({ type: "move", seat, move, ...(auto ? { auto: true as const } : {}) }); + switch (move.type) { + case "place": + placeTile(state, parseTile(move.tile)!); + break; + case "announce": + state.endAnnounced = seat; + state.log.push({ type: "announced", seat }); + break; + case "pass": + state.log.push({ type: "skipPlace", seat }); + enterBuyPhase(state); + break; + case "found": + foundChain(state, move.chain); + enterBuyPhase(state); + break; + case "survivor": + setSurvivor(state, move.chain); + break; + case "defunctOrder": + setDefunctOrder(state, move.chains); + break; + case "dispose": + dispose(state, seat, move.sell, move.trade); + break; + case "buy": + buyShares(state, move.shares); + endTurn(state); + break; + } +} + +function placeTile(state: GameState, tile: Tile): void { + const seat = state.seats[state.activeSeat]!; + const effect = placementEffect(state.board, tile); + seat.hand = seat.hand.filter((t) => t !== tile); + state.board[tile] = "loose"; + state.placedThisTurn = true; + if (effect.kind === "merge") { + startMerger(state, tile, effect.chains); + return; + } + if (effect.kind === "grow") { + for (const t of connectedLoose(state.board, tile)) { + state.board[t] = effect.chain; + } + state.log.push({ type: "grew", chain: effect.chain, size: chainSize(state.board, effect.chain) }); + } + if (effect.kind === "found") { + state.pendingTile = tile; + const available = CHAIN_IDS.filter((chain) => !activeChains(state.board).includes(chain)); + if (available.length > 1) { + state.phase = "found"; + return; + } + foundChain(state, available[0]!); + } + enterBuyPhase(state); +} + +/** rules.md §6. */ +function foundChain(state: GameState, chain: ChainId): void { + const tile = state.pendingTile!; + for (const t of connectedLoose(state.board, tile)) { + state.board[t] = chain; + } + state.pendingTile = null; + const bonus = state.bank[chain] > 0; + if (bonus) { + state.bank[chain] -= 1; + state.seats[state.activeSeat]!.shares[chain] += 1; + } + state.log.push({ type: "founded", seat: state.activeSeat, chain, size: chainSize(state.board, chain), bonus }); +} + +/** rules.md §9: prices are fixed for the whole buy phase. */ +function buyShares(state: GameState, shares: Partial): void { + const seat = state.seats[state.activeSeat]!; + let cost = 0; + for (const [chain, count] of Object.entries(shares) as [ChainId, number][]) { + cost += count * sharePrice(chain, chainSize(state.board, chain)); + state.bank[chain] -= count; + seat.shares[chain] += count; + } + seat.cash -= cost; + state.log.push({ type: "bought", seat: state.activeSeat, shares, cost }); +} diff --git a/packages/engine/src/options.spec.ts b/packages/engine/src/options.spec.ts new file mode 100644 index 0000000..8a6100e --- /dev/null +++ b/packages/engine/src/options.spec.ts @@ -0,0 +1,208 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { endConditionHolds } from "./board.js"; +import { applyMove } from "./moves.js"; +import { DEFAULT_OPTIONS, normalizeOptions } from "./options.js"; +import { sharePrice } from "./prices.js"; +import { initGame } from "./setup.js"; +import { chainAt, checkInvariants, row, scenario } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +function ignoredLog(state: GameState): Extract[] { + return state.log.filter((e): e is Extract => e.type === "optionIgnored"); +} + +const place = (tile: string) => ({ type: "place", tile }); +const buy = { type: "buy", shares: {} }; + +test("§15 defaults reproduce the standard game", () => { + assert.deepEqual(DEFAULT_OPTIONS, { + publicHoldings: false, + teamPlay: false, + twoPlayerMode: "bank", + autoEnd: false, + endSize: 41, + }); + for (let players = 2; players <= 6; players++) { + const state = initGame(players, {}, "defaults"); + assert.deepEqual(state.options, DEFAULT_OPTIONS); + assert.deepEqual(ignoredLog(state), []); + } +}); + +test("§15 BGS option values are read as sent: ticked checkboxes, selects as strings", () => { + const { options, ignored } = normalizeOptions(2, { + publicHoldings: true, + autoEnd: true, + twoPlayerMode: "fourHands", + endSize: "31", + }); + assert.deepEqual(options, { + publicHoldings: true, + teamPlay: false, + twoPlayerMode: "fourHands", + autoEnd: true, + endSize: 31, + }); + assert.deepEqual(ignored, []); +}); + +test("§15 an option that does not apply to the player count is ignored and logged", () => { + const five = initGame(5, { teamPlay: true }, "team5"); + assert.equal(five.options.teamPlay, false); + assert.deepEqual(ignoredLog(five), [ + { type: "optionIgnored", option: "teamPlay", value: true, reason: "only applies with exactly 4 players" }, + ]); + const three = initGame(3, { twoPlayerMode: "fourHands" }, "four3"); + assert.equal(three.options.twoPlayerMode, "bank"); + assert.equal(three.seats.length, 3); + assert.deepEqual(ignoredLog(three), [ + { + type: "optionIgnored", + option: "twoPlayerMode", + value: "fourHands", + reason: "only applies with exactly 2 players", + }, + ]); + assert.equal(initGame(4, { teamPlay: true }, "team4").options.teamPlay, true); +}); + +test("§15 the always-sent default twoPlayerMode is not logged as ignored", () => { + for (const players of [3, 4, 5, 6]) { + assert.deepEqual(ignoredLog(initGame(players, { twoPlayerMode: "bank" }, "bank-default")), []); + } +}); + +test("§3.5 options are never rejected: unknown values are ignored and logged", () => { + const state = initGame(4, { twoPlayerMode: "solo", endSize: "50", teamPlay: "yes", mystery: 1 }, "junk"); + assert.deepEqual(state.options, { ...DEFAULT_OPTIONS }); + assert.deepEqual( + ignoredLog(state).map((e) => [e.option, e.value]), + [ + ["twoPlayerMode", "solo"], + ["endSize", "50"], + ] + ); + assert.doesNotThrow(() => wrapper.init(2, [], { teamPlay: true, twoPlayerMode: "fourHands", endSize: 7 }, "x")); +}); + +test("§15 endSize 31: a 31-tile chain meets the end condition; safe size and prices are unchanged", () => { + const tiles = [...row("A", 1, 12), ...row("B", 1, 12), ...row("C", 1, 7)]; + const board = scenario({ board: chainAt("tower", tiles), hands: [["9I"]] }).board; + const open = scenario({ + board: { ...chainAt("tower", tiles), ...chainAt("luxor", ["1G", "2G"]) }, + hands: [["9I"]], + }).board; + assert.equal(tiles.length, 31); + assert.equal(endConditionHolds(open, 41), false); + assert.equal(endConditionHolds(open, 31), true); + assert.equal(endConditionHolds(board, 31), true); + const short = scenario({ + board: { ...chainAt("tower", tiles), ...chainAt("luxor", ["1G", "2G"]) }, + hands: [["9I"]], + options: { endSize: "31" }, + }); + assert.doesNotThrow(() => applyMove(short, { type: "announce" }, 0)); + const standard = scenario({ + board: { ...chainAt("tower", tiles), ...chainAt("luxor", ["1G", "2G"]) }, + hands: [["9I"]], + }); + assert.throws(() => applyMove(standard, { type: "announce" }, 0), /cannot be ended/); + const tenTiles = scenario({ board: chainAt("tower", row("A", 1, 10)), hands: [["9I"]], options: { endSize: "31" } }); + assert.throws( + () => applyMove(tenTiles, { type: "announce" }, 0), + /cannot be ended/, + "a 10-tile chain is still not safe" + ); + assert.equal(sharePrice("tower", 31), 900); +}); + +test("§15 autoEnd: the game ends at the end of the turn in which an end condition first holds", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 10)), + hands: [["11A"], ["9I"]], + options: { autoEnd: true }, + }); + assert.throws(() => applyMove(state, { type: "announce" }, 0), /cannot be ended/); + play(state, 0, place("11A")); + assert.equal(state.ended, false, "the turn is finished first"); + assert.throws(() => applyMove(state, { type: "announce" }, 0), /cannot be ended/, "there is nothing to announce"); + play(state, 0, buy); + assert.equal(state.ended, true); + assert.deepEqual( + state.log.filter((e) => e.type === "gameEnd"), + [{ type: "gameEnd", reason: "condition" }] + ); +}); + +test("§15 without autoEnd the same turn does not end the game", () => { + const state = scenario({ board: chainAt("tower", row("A", 1, 10)), hands: [["11A"], ["9I"]] }); + play(state, 0, place("11A")); + play(state, 0, buy); + assert.equal(state.ended, false); +}); + +test("§15 teamPlay: seats 1+3 and 2+4 combine their cash at final scoring", () => { + const state = scenario({ + seats: 4, + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + cash: [5000, 9000, 6000, 1000], + options: { teamPlay: true }, + }); + assert.deepEqual(wrapper.scores(state), [0, 0, 0, 0]); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.deepEqual(wrapper.scores(state), [11000, 10000, 11000, 10000]); + assert.deepEqual(wrapper.rankings(state), [1, 2, 1, 2], "seat 2 is richest alone, but its team loses"); +}); + +test("§15 teamPlay: tied teams share the victory", () => { + const state = scenario({ + seats: 4, + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + cash: [5000, 4000, 5000, 6000], + options: { teamPlay: true }, + }); + play(state, 0, { type: "announce" }); + play(state, 0, place("9G")); + play(state, 0, buy); + assert.deepEqual(wrapper.rankings(state), [1, 1, 1, 1]); +}); + +test("§15 teamPlay with private holdings: teammates cannot see each other's holdings", () => { + const state = scenario({ + seats: 4, + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["9I"], ["11I"], ["12G"]], + shares: [{ tower: 1 }, {}, { tower: 3 }], + options: { teamPlay: true }, + }); + const view = wrapper.stripSecret(state, 0); + assert.equal(view.seats[2]!.cash, -1); + assert.equal(view.seats[2]!.shares.tower, -1); + assert.deepEqual(view.seats[2]!.hand, [-1]); + assert.equal(view.seats[0]!.shares.tower, 1); +}); + +test("§15 publicHoldings: everyone's cash and stock are visible, hands are not", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["9I"], ["11I"]], + shares: [{}, { tower: 2 }], + options: { publicHoldings: true }, + }); + const view = wrapper.stripSecret(state, 0); + assert.equal(view.seats[1]!.cash, 6000); + assert.equal(view.seats[1]!.shares.tower, 2); + assert.deepEqual(view.seats[1]!.hand, [-1]); +}); diff --git a/packages/engine/src/options.ts b/packages/engine/src/options.ts new file mode 100644 index 0000000..21d7f83 --- /dev/null +++ b/packages/engine/src/options.ts @@ -0,0 +1,81 @@ +import { END_SIZE } from "./config.js"; + +/** rules.md §15, after normalisation against the player count. */ +export interface GameOptions { + publicHoldings: boolean; + teamPlay: boolean; + twoPlayerMode: "bank" | "fourHands"; + autoEnd: boolean; + endSize: number; +} + +export interface IgnoredOption { + option: string; + value: unknown; + reason: string; +} + +export const DEFAULT_OPTIONS: GameOptions = { + publicHoldings: false, + teamPlay: false, + twoPlayerMode: "bank", + autoEnd: false, + endSize: END_SIZE, +}; + +const END_SIZES = [41, 31]; + +/** + * Reads the creator's options defensively. BGS omits unticked checkboxes and always sends + * selects (as strings), so a missing checkbox means false. Options are never rejected + * (rules.md §3.5/§15): anything that does not apply, or has an unknown value, is ignored + * and reported so the log can say so. + */ +export function normalizeOptions( + players: number, + raw: Record +): { options: GameOptions; ignored: IgnoredOption[] } { + const options: GameOptions = { ...DEFAULT_OPTIONS }; + const ignored: IgnoredOption[] = []; + + options.publicHoldings = raw.publicHoldings === true; + options.autoEnd = raw.autoEnd === true; + + if (raw.teamPlay === true) { + if (players === 4) { + options.teamPlay = true; + } else { + ignored.push({ option: "teamPlay", value: true, reason: "only applies with exactly 4 players" }); + } + } + + if (raw.twoPlayerMode === "fourHands") { + if (players === 2) { + options.twoPlayerMode = "fourHands"; + } else { + ignored.push({ option: "twoPlayerMode", value: "fourHands", reason: "only applies with exactly 2 players" }); + } + } else if (raw.twoPlayerMode !== undefined && raw.twoPlayerMode !== "bank") { + ignored.push({ option: "twoPlayerMode", value: raw.twoPlayerMode, reason: "unknown value" }); + } + + if (raw.endSize !== undefined) { + const size = Number(raw.endSize); + if (END_SIZES.includes(size)) { + options.endSize = size; + } else { + ignored.push({ option: "endSize", value: raw.endSize, reason: "unknown value" }); + } + } + + return { options, ignored }; +} + +/** Internal seats per real player: fourHands gives each of the 2 players two seats. */ +export function seatOwners(players: number, options: GameOptions): number[] { + if (players === 2 && options.twoPlayerMode === "fourHands") { + // rules.md §15: player A has seats 1 and 3, player B seats 2 and 4. + return [0, 1, 0, 1]; + } + return Array.from({ length: players }, (_, seat) => seat); +} diff --git a/packages/engine/src/position.spec.ts b/packages/engine/src/position.spec.ts new file mode 100644 index 0000000..1445498 --- /dev/null +++ b/packages/engine/src/position.spec.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { legalMoves } from "./legal.js"; +import { applyMove, currentSeat, dropPlayerSeats } from "./moves.js"; +import { positionAt } from "./position.js"; +import { replayGame } from "./replay.js"; +import { initGame } from "./setup.js"; +import { viewFor } from "./view.js"; + +const OPTIONS: [number, Record][] = [ + [2, {}], + [2, { twoPlayerMode: "fourHands" }], + [3, { publicHoldings: true }], + [4, { teamPlay: true }], + [5, { endSize: "31" }], + [6, { autoEnd: true }], +]; + +test("replay positions rebuilt from the public log match the seeded replay at every move", () => { + for (const [players, options] of OPTIONS) { + const state = initGame(players, options, `position-${players}-${JSON.stringify(options)}`); + const boundaries = [state.log.length]; + for (let step = 1; !state.ended; step++) { + if (players >= 3 && step === 90) { + dropPlayerSeats(state, 1); + } else { + const moves = legalMoves(state).filter((move) => move.type !== "announce" || step > 250); + applyMove(state, moves[(step * 7919) % moves.length]!, currentSeat(state)!); + } + boundaries.push(state.log.length); + } + // A stripped view carries no seed, so the replay controls must work from it alone. + const view = viewFor(state, 0); + for (const to of boundaries) { + const expected = replayGame(state, to); + const position = positionAt(view, to); + const label = `${players} players ${JSON.stringify(options)}, log position ${to}`; + assert.deepEqual(position.board, expected.board, `${label}: board`); + assert.deepEqual(position.bank, expected.bank, `${label}: bank shares`); + assert.deepEqual( + position.seats, + expected.seats.map(({ cash, shares, hand }) => ({ cash, shares, tiles: hand.length })), + `${label}: cash, stock and tile counts` + ); + } + } +}); diff --git a/packages/engine/src/position.ts b/packages/engine/src/position.ts new file mode 100644 index 0000000..e611d04 --- /dev/null +++ b/packages/engine/src/position.ts @@ -0,0 +1,131 @@ +import { connectedLoose, placementEffect } from "./board.js"; +import { CHAIN_IDS, HAND_SIZE, SHARES_PER_CHAIN, STARTING_CASH, type ChainId } from "./config.js"; +import { parseTile, type Tile } from "./tiles.js"; +import type { Cell, GameState, Shares } from "./types.js"; + +/** The public position at a point in the log: what a replay shows (no hands, no pool). */ +export interface PublicPosition { + board: Cell[]; + bank: Shares; + /** Each seat's cash, stock and number of tiles in hand (not which tiles). */ + seats: { cash: number; shares: Shares; tiles: number }[]; +} + +function sharesOf(count: number): Shares { + return Object.fromEntries(CHAIN_IDS.map((chain) => [chain, count])) as Shares; +} + +/** + * Rebuilds the public position after the first `to` log entries from the log alone, so it + * works on a stripped state (no seed needed). + */ +export function positionAt(state: GameState, to: number): PublicPosition { + const board: Cell[] = state.board.map(() => null); + const bank = sharesOf(SHARES_PER_CHAIN); + let seats: PublicPosition["seats"] = []; + let lastTile: Tile | undefined; + let merger: { tile: Tile; chains: ChainId[]; survivor?: ChainId } | undefined; + + const place = (tile: Tile) => { + const effect = placementEffect(board, tile); + board[tile] = "loose"; + lastTile = tile; + if (effect.kind === "grow") { + for (const t of connectedLoose(board, tile)) { + board[t] = effect.chain; + } + } + }; + + for (const entry of state.log.slice(0, Math.max(0, to))) { + switch (entry.type) { + case "init": + seats = Array.from({ length: entry.seats }, () => ({ cash: STARTING_CASH, shares: sharesOf(0), tiles: 0 })); + break; + case "turnOrder": + for (const tile of entry.tiles) { + board[tile] = "loose"; + } + // rules.md §3.4: every seat then draws a full hand, which is not logged as a draw. + for (const seat of seats) { + seat.tiles = HAND_SIZE; + } + break; + case "move": + if (entry.move.type === "place") { + place(parseTile(entry.move.tile)!); + seats[entry.seat]!.tiles -= 1; + } + break; + case "drew": + seats[entry.seat]!.tiles += entry.count; + break; + case "discarded": + seats[entry.seat]!.tiles -= entry.tiles.length; + break; + case "founded": + for (const t of connectedLoose(board, lastTile!)) { + board[t] = entry.chain; + } + if (entry.bonus) { + bank[entry.chain] -= 1; + seats[entry.seat]!.shares[entry.chain] += 1; + } + break; + case "bankTile": + if (entry.result !== "removed") { + place(entry.tile); + } + break; + case "merger": + merger = { tile: entry.tile, chains: Object.keys(entry.sizes) as ChainId[] }; + break; + case "mergerPlan": + merger!.survivor = entry.survivor; + break; + case "merged": + for (let tile = 0; tile < board.length; tile++) { + const cell = board[tile] ?? null; + if (cell !== null && cell !== "loose" && merger!.chains.includes(cell)) { + board[tile] = entry.survivor; + } + } + for (const t of connectedLoose(board, merger!.tile)) { + board[t] = entry.survivor; + } + merger = undefined; + break; + case "bonuses": + for (const { seat, amount } of entry.payouts) { + seats[seat]!.cash += amount; + } + break; + case "disposed": { + const seat = seats[entry.seat]!; + seat.cash += entry.proceeds; + seat.shares[entry.chain] -= entry.sold + entry.traded; + bank[entry.chain] += entry.sold + entry.traded; + seat.shares[merger!.survivor!] += entry.traded / 2; + bank[merger!.survivor!] -= entry.traded / 2; + break; + } + case "bought": { + const seat = seats[entry.seat]!; + seat.cash -= entry.cost; + for (const [chain, count] of Object.entries(entry.shares) as [ChainId, number][]) { + seat.shares[chain] += count; + bank[chain] -= count; + } + break; + } + case "finalSale": + seats[entry.seat]!.cash += entry.proceeds; + seats[entry.seat]!.shares[entry.chain] -= entry.shares; + bank[entry.chain] += entry.shares; + break; + default: + break; + } + } + return { board, bank, seats }; +} diff --git a/packages/engine/src/prices.spec.ts b/packages/engine/src/prices.spec.ts new file mode 100644 index 0000000..459ac7c --- /dev/null +++ b/packages/engine/src/prices.spec.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { ChainId } from "./config.js"; +import { majorityBonus, minorityBonus, sharePrice } from "./prices.js"; + +// rules.md §8, transcribed row by row: [minor sizes, medium sizes, major sizes, price, 1st, 2nd]. +type Band = [number, number] | null; +const TABLE: [Band, Band, Band, number, number, number][] = [ + [[2, 2], null, null, 200, 2000, 1000], + [[3, 3], [2, 2], null, 300, 3000, 1500], + [[4, 4], [3, 3], [2, 2], 400, 4000, 2000], + [[5, 5], [4, 4], [3, 3], 500, 5000, 2500], + [[6, 10], [5, 5], [4, 4], 600, 6000, 3000], + [[11, 20], [6, 10], [5, 5], 700, 7000, 3500], + [[21, 30], [11, 20], [6, 10], 800, 8000, 4000], + [[31, 40], [21, 30], [11, 20], 900, 9000, 4500], + [[41, 108], [31, 40], [21, 30], 1000, 10000, 5000], + [null, [41, 108], [31, 40], 1100, 11000, 5500], + [null, null, [41, 108], 1200, 12000, 6000], +]; + +const TIER_CHAINS: ChainId[][] = [ + ["tower", "luxor"], + ["worldwide", "american", "festival"], + ["imperial", "continental"], +]; + +TABLE.forEach((row, index) => { + const [, , , price, first, second] = row; + test(`§8 price table row ${index + 1}: $${price} share, $${first} / $${second} bonuses`, () => { + for (let tier = 0; tier < 3; tier++) { + const band = row[tier] as Band; + if (!band) { + continue; + } + for (let size = band[0]; size <= band[1]; size++) { + for (const chain of TIER_CHAINS[tier]!) { + assert.equal(sharePrice(chain, size), price, `${chain} size ${size} price`); + assert.equal(majorityBonus(chain, size), first, `${chain} size ${size} 1st bonus`); + assert.equal(minorityBonus(chain, size), second, `${chain} size ${size} 2nd bonus`); + } + } + } + }); +}); + +test("§8 every chain size from 2 to 108 is covered by exactly one table row per tier", () => { + for (let tier = 0; tier < 3; tier++) { + for (let size = 2; size <= 108; size++) { + const rows = TABLE.filter((row) => { + const band = row[tier] as Band; + return band !== null && size >= band[0] && size <= band[1]; + }); + assert.equal(rows.length, 1, `tier ${tier} size ${size}`); + } + } +}); + +test("§8 prices are not defined below chain size 2", () => { + assert.throws(() => sharePrice("tower", 1)); +}); diff --git a/packages/engine/src/prices.ts b/packages/engine/src/prices.ts new file mode 100644 index 0000000..fbee9e2 --- /dev/null +++ b/packages/engine/src/prices.ts @@ -0,0 +1,32 @@ +import { chainTier, type ChainId, type Tier } from "./config.js"; + +const TIER_OFFSET: Record = { minor: 0, medium: 100, major: 200 }; + +// rules.md §8: price of a minor-tier chain by size; medium adds $100, major adds $200. +function minorPrice(size: number): number { + if (size <= 5) { + return size * 100; + } + if (size <= 10) { + return 600; + } + if (size <= 40) { + return 700 + Math.floor((size - 11) / 10) * 100; + } + return 1000; +} + +export function sharePrice(chain: ChainId, size: number): number { + if (!Number.isInteger(size) || size < 2) { + throw new Error(`A chain has at least 2 tiles, got ${size}`); + } + return minorPrice(size) + TIER_OFFSET[chainTier(chain)]; +} + +export function majorityBonus(chain: ChainId, size: number): number { + return sharePrice(chain, size) * 10; +} + +export function minorityBonus(chain: ChainId, size: number): number { + return sharePrice(chain, size) * 5; +} diff --git a/packages/engine/src/prng.ts b/packages/engine/src/prng.ts new file mode 100644 index 0000000..61c4d91 --- /dev/null +++ b/packages/engine/src/prng.ts @@ -0,0 +1,26 @@ +import seedrandom from "seedrandom"; +import type { GameState } from "./types.js"; + +// All randomness is derived from the game seed plus a counter stored in the state, +// so draws stay deterministic across save/load and replay without persisting PRNG internals. + +export function nextRandom(state: GameState): number { + const rng = seedrandom(`${state.seed}:${state.rngCounter}`); + state.rngCounter += 1; + return rng(); +} + +export function nextInt(state: GameState, maxExclusive: number): number { + return Math.floor(nextRandom(state) * maxExclusive); +} + +/** Fisher-Yates shuffle in place, driven by the state PRNG. */ +export function shuffle(state: GameState, items: T[]): T[] { + for (let i = items.length - 1; i > 0; i--) { + const j = nextInt(state, i + 1); + const a = items[i] as T; + items[i] = items[j] as T; + items[j] = a; + } + return items; +} diff --git a/packages/engine/src/replay.spec.ts b/packages/engine/src/replay.spec.ts new file mode 100644 index 0000000..1609c3c --- /dev/null +++ b/packages/engine/src/replay.spec.ts @@ -0,0 +1,68 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { legalMoves } from "./legal.js"; +import { initGame } from "./setup.js"; +import type { GameState } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +/** A few hundred deterministic moves, with a drop part-way through. */ +function playedGame(): { state: GameState; boundaries: number[] } { + const state = initGame(4, { teamPlay: true, endSize: "31" }, "replay-unit"); + wrapper.setPlayerMetaData(state, 2, { name: "Ada" }); + const boundaries = [wrapper.logLength(state)]; + for (let step = 1; !state.ended && step < 400; step++) { + if (step === 60) { + wrapper.dropPlayer(state, 3); + } else { + const moves = legalMoves(state).filter((move) => move.type !== "announce"); + wrapper.move(state, moves[(step * 7919) % moves.length]!, wrapper.currentPlayer(state)!); + } + boundaries.push(wrapper.logLength(state)); + } + return { state, boundaries }; +} + +test("replay without `to` rebuilds the current state, keeping player names", () => { + const { state } = playedGame(); + const replayed = wrapper.replay(structuredClone(state)); + assert.deepEqual(replayed, state); + assert.equal(replayed.seats[2]!.name, "Ada"); +}); + +test("replay to a move boundary returns exactly that log length (BGS undo and analysis check this)", () => { + const { state, boundaries } = playedGame(); + for (const to of [boundaries[0]!, boundaries[1]!, boundaries[60]!, boundaries[61]!, boundaries.at(-2)!]) { + assert.equal(wrapper.logLength(wrapper.replay(state, { to })), to); + } +}); + +test("replay rejects positions that are not between two moves", () => { + const { state, boundaries } = playedGame(); + const inside = boundaries.find((to, i) => i > 0 && to - boundaries[i - 1]! > 1)! - 1; + assert.throws(() => wrapper.replay(state, { to: inside }), /not between two moves/); + assert.throws(() => wrapper.replay(state, { to: 1 }), /not between two moves/); + assert.throws(() => wrapper.replay(state, { to: state.log.length + 1 }), /Cannot replay/); + assert.throws(() => wrapper.replay(state, { to: -1 }), /Cannot replay/); +}); + +test("replay refuses a stripped state, which has no seed", () => { + const { state } = playedGame(); + assert.throws(() => wrapper.replay(wrapper.stripSecret(state, 0)), /full game state/); +}); + +test("replay throws rather than rewriting history when the log does not match", () => { + const { state } = playedGame(); + const tampered = structuredClone(state); + const index = tampered.log.findIndex((entry) => entry.type === "bought" && entry.cost > 0); + const entry = tampered.log[index]!; + assert.ok(entry.type === "bought"); + entry.cost += 100; + assert.throws(() => wrapper.replay(tampered), new RegExp(`diverged at log entry ${index}`)); +}); + +test("replay does not change the state it is given", () => { + const { state, boundaries } = playedGame(); + const before = structuredClone(state); + wrapper.replay(state, { to: boundaries[30]! }); + assert.deepEqual(state, before); +}); diff --git a/packages/engine/src/replay.ts b/packages/engine/src/replay.ts new file mode 100644 index 0000000..d6f4684 --- /dev/null +++ b/packages/engine/src/replay.ts @@ -0,0 +1,47 @@ +import { applyMove, dropPlayerSeats } from "./moves.js"; +import { initGame } from "./setup.js"; +import type { GameState } from "./types.js"; + +/** + * Rebuilds the game from its seed by re-applying the logged decisions and drops up to log + * length `to`. Automatic steps are regenerated and must match the log exactly, or this throws. + * Player names are not logged, so they come from the given state. + */ +export function replayGame(data: GameState, to: number = data.log.length): GameState { + if (!Number.isInteger(to) || to < 0 || to > data.log.length) { + throw new Error(`Cannot replay to position ${to}`); + } + const first = data.log[0]; + if (!data.seed || first?.type !== "init") { + throw new Error("Replay needs the full game state, including the seed"); + } + const state = initGame(first.players, first.rawOptions, data.seed); + checkLog(state, data, 0); + while (state.log.length < to) { + const checked = state.log.length; + const entry = data.log[checked]!; + if (entry.type === "move" && entry.auto !== true) { + applyMove(state, entry.move, entry.seat); + } else if (entry.type === "dropped") { + dropPlayerSeats(state, state.seatOwner[entry.seat]!); + } else { + throw new Error(`Replay diverged: log entry ${checked} (${entry.type}) is not a player action`); + } + checkLog(state, data, checked); + } + if (state.log.length !== to) { + throw new Error(`Position ${to} is not between two moves`); + } + state.seats.forEach((seat, index) => { + seat.name = data.seats[index]!.name; + }); + return state; +} + +function checkLog(state: GameState, data: GameState, from: number): void { + for (let i = from; i < state.log.length; i++) { + if (JSON.stringify(state.log[i]) !== JSON.stringify(data.log[i])) { + throw new Error(`Replay diverged at log entry ${i}`); + } + } +} diff --git a/packages/engine/src/scoring.ts b/packages/engine/src/scoring.ts new file mode 100644 index 0000000..cbeb443 --- /dev/null +++ b/packages/engine/src/scoring.ts @@ -0,0 +1,86 @@ +import { activeChains, chainSize, endConditionHolds } from "./board.js"; +import { payBonuses } from "./merger.js"; +import { sharePrice } from "./prices.js"; +import type { GameState } from "./types.js"; + +export type EndReason = "announced" | "condition" | "stall" | "dropped"; + +export function endConditionMet(state: GameState): boolean { + return endConditionHolds(state.board, state.options.endSize); +} + +/** + * rules.md §11.1: the active player may announce once a condition holds, and only once. With + * autoEnd (§15) the game ends by itself instead, so there is nothing to announce. + */ +export function canAnnounce(state: GameState): boolean { + return !state.options.autoEnd && state.endAnnounced === null && endConditionMet(state); +} + +/** rules.md §11.2. */ +export function endGame(state: GameState, reason: EndReason): void { + state.log.push({ type: "gameEnd", reason }); + const chains = activeChains(state.board); + for (const chain of chains) { + payBonuses(state, chain, chainSize(state.board, chain), "setAside"); + } + state.seats.forEach((seat, index) => { + for (const chain of chains) { + const shares = seat.shares[chain]; + if (shares === 0) { + continue; + } + const proceeds = shares * sharePrice(chain, chainSize(state.board, chain)); + seat.cash += proceeds; + seat.shares[chain] = 0; + state.bank[chain] += shares; + state.log.push({ type: "finalSale", seat: index, chain, shares, proceeds }); + } + }); + state.log.push({ type: "result", cash: state.seats.map((seat) => seat.cash), ranks: playerRankings(state) }); + state.phase = "ended"; + state.ended = true; +} + +/** + * What each real player is ranked by: their cash; with teamPlay at the end, their team's + * combined cash (seats 1+3 and 2+4); in fourHands, the single richest seat they control. + */ +function playerValues(state: GameState): number[] { + const cash = state.seats.map((seat) => seat.cash); + if (state.options.teamPlay && state.ended) { + return cash.map((_, seat) => cash[seat % 2]! + cash[(seat % 2) + 2]!); + } + return Array.from({ length: state.players }, (_, player) => + Math.max(...cash.filter((_, seat) => state.seatOwner[seat] === player)) + ); +} + +function hasDropped(state: GameState, player: number): boolean { + return state.seatOwner.every((owner, seat) => owner !== player || state.seats[seat]!.dropped); +} + +/** + * rules.md §11.2.4: most money wins; equal values share the rank. Rank 1 is best. + * rules.md §16: players who dropped rank below everyone who did not, sharing the next rank. + */ +export function playerRankings(state: GameState): number[] { + const values = playerValues(state); + const players = values.map((_, player) => player); + const stayed = players.filter((player) => !hasDropped(state, player)); + // With teams, places are counted per team (players 1 and 2 stand for the two teams), so the + // losing team comes second rather than third. + const competitors = + state.options.teamPlay && state.ended ? values.slice(0, 2) : stayed.map((player) => values[player]!); + const ranks = players.map((player) => 1 + competitors.filter((other) => other > values[player]!).length); + const lastStayed = Math.max(0, ...stayed.map((player) => ranks[player]!)); + return players.map((player) => (hasDropped(state, player) ? lastStayed + 1 : ranks[player]!)); +} + +/** rules.md §13: scores stay 0 during play while holdings are private. */ +export function playerScores(state: GameState): number[] { + if (!state.ended && !state.options.publicHoldings) { + return Array.from({ length: state.players }, () => 0); + } + return playerValues(state); +} diff --git a/packages/engine/src/setup.spec.ts b/packages/engine/src/setup.spec.ts new file mode 100644 index 0000000..9e862ac --- /dev/null +++ b/packages/engine/src/setup.spec.ts @@ -0,0 +1,66 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { activeChains } from "./board.js"; +import { CHAIN_IDS } from "./config.js"; +import { initGame } from "./setup.js"; +import { neighbours } from "./tiles.js"; +import { checkInvariants } from "./test/helpers.js"; + +test("§1/§3 each player starts with $6,000, 6 tiles and no stock; the bank holds 25 of each chain", () => { + for (let seats = 2; seats <= 6; seats++) { + const state = initGame(seats, {}, `setup-${seats}`); + for (const seat of state.seats) { + assert.equal(seat.cash, 6000); + assert.equal(seat.hand.length, 6); + assert.ok(CHAIN_IDS.every((chain) => seat.shares[chain] === 0)); + } + assert.ok(CHAIN_IDS.every((chain) => state.bank[chain] === 25)); + assert.equal(state.pool.length, 108 - seats - 6 * seats); + checkInvariants(state); + } +}); + +test("§3.2 turn-order tiles stay on the board as loose tiles and never form a chain", () => { + for (let seats = 2; seats <= 6; seats++) { + const state = initGame(seats, {}, `order-${seats}`); + assert.equal(state.board.filter((cell) => cell === "loose").length, seats); + assert.deepEqual(activeChains(state.board), []); + } +}); + +test("§3.2 turn-order tiles stay loose even when two of them are adjacent", () => { + let found = false; + for (let i = 0; i < 2000 && !found; i++) { + const state = initGame(6, {}, `adjacent-${i}`); + const entry = state.log.find((e) => e.type === "turnOrder"); + assert.ok(entry?.type === "turnOrder"); + const adjacent = entry.tiles.some((tile) => neighbours(tile).some((n) => entry.tiles.includes(n))); + if (adjacent) { + found = true; + assert.deepEqual(activeChains(state.board), []); + assert.ok(entry.tiles.every((tile) => state.board[tile] === "loose")); + } + } + assert.ok(found, "expected some seed to draw adjacent turn-order tiles"); +}); + +test("§3.3 the player who drew the lowest tile goes first", () => { + for (let i = 0; i < 50; i++) { + const state = initGame(2 + (i % 5), {}, `first-${i}`); + const entry = state.log.find((e) => e.type === "turnOrder"); + assert.ok(entry?.type === "turnOrder"); + const lowest = entry.tiles.indexOf(Math.min(...entry.tiles)); + assert.equal(entry.first, lowest); + assert.equal(state.activeSeat, lowest); + } +}); + +test("§3.1 the tile pool is shuffled deterministically from the seed", () => { + assert.deepEqual(initGame(4, {}, "same"), initGame(4, {}, "same")); + assert.notDeepEqual(initGame(4, {}, "one").pool, initGame(4, {}, "two").pool); +}); + +test("§1 player counts outside 2-6 are rejected", () => { + assert.throws(() => initGame(1, {}, "x")); + assert.throws(() => initGame(7, {}, "x")); +}); diff --git a/packages/engine/src/setup.ts b/packages/engine/src/setup.ts new file mode 100644 index 0000000..2d5f682 --- /dev/null +++ b/packages/engine/src/setup.ts @@ -0,0 +1,71 @@ +import { CHAIN_IDS, HAND_SIZE, MAX_PLAYERS, MIN_PLAYERS, SHARES_PER_CHAIN, STARTING_CASH } from "./config.js"; +import { normalizeOptions, seatOwners } from "./options.js"; +import { shuffle } from "./prng.js"; +import { allTiles } from "./tiles.js"; +import { drawTile, startTurn } from "./turn.js"; +import type { GameState, Shares } from "./types.js"; + +function sharesOf(count: number): Shares { + return Object.fromEntries(CHAIN_IDS.map((chain) => [chain, count])) as Shares; +} + +/** Creates a game for `players` real players; fourHands gives each of them two seats. */ +export function initGame(players: number, rawOptions: Record, seed: string): GameState { + if (!Number.isInteger(players) || players < MIN_PLAYERS || players > MAX_PLAYERS) { + throw new Error(`Acquire needs ${MIN_PLAYERS} to ${MAX_PLAYERS} players`); + } + const { options, ignored } = normalizeOptions(players, rawOptions); + const seatOwner = seatOwners(players, options); + const seats = seatOwner.length; + const state: GameState = { + seed, + rngCounter: 0, + options, + players, + seatOwner, + seats: Array.from({ length: seats }, (_, seat) => ({ + name: `Player ${seat + 1}`, + cash: STARTING_CASH, + shares: sharesOf(0), + hand: [], + dropped: false, + })), + board: allTiles().map(() => null), + pool: [], + removed: [], + bank: sharesOf(SHARES_PER_CHAIN), + activeSeat: 0, + phase: "place", + pendingTile: null, + merger: null, + bankTiles: [], + endAnnounced: null, + placedThisTurn: false, + turnsWithoutPlacement: 0, + turn: 0, + log: [{ type: "init", players, seats, options: { ...options }, rawOptions: structuredClone(rawOptions) }], + ended: false, + }; + for (const entry of ignored) { + state.log.push({ type: "optionIgnored", ...entry }); + } + state.pool = shuffle(state, allTiles()); + + // rules.md §3.2-3.3: one tile each, placed as loose tiles; the lowest tile goes first. + const orderTiles = state.seats.map(() => drawTile(state)!); + for (const tile of orderTiles) { + state.board[tile] = "loose"; + } + const first = orderTiles.indexOf(Math.min(...orderTiles)); + state.log.push({ type: "turnOrder", tiles: orderTiles, first }); + + for (const seat of state.seats) { + for (let i = 0; i < HAND_SIZE; i++) { + seat.hand.push(drawTile(state)!); + } + } + + state.activeSeat = first; + startTurn(state); + return state; +} diff --git a/packages/engine/src/sim.spec.ts b/packages/engine/src/sim.spec.ts new file mode 100644 index 0000000..0e75ec2 --- /dev/null +++ b/packages/engine/src/sim.spec.ts @@ -0,0 +1,138 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { legalMoves } from "./legal.js"; +import { remainingPlayers } from "./moves.js"; +import { checkInvariants } from "./test/helpers.js"; +import type { GameState } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +function lcg(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (Math.imul(s, 1664525) + 1013904223) >>> 0; + return s / 2 ** 32; + }; +} + +/** + * Every valid rules.md §15 combination for a player count, in the shape BGS sends: unticked + * checkboxes are absent, selects are always present as strings. teamPlay only applies with 4 + * players and twoPlayerMode only with 2, so other counts get the default for those. + */ +function optionCombinations(players: number): Record[] { + const combos: Record[] = []; + for (const publicHoldings of [false, true]) { + for (const autoEnd of [false, true]) { + for (const endSize of ["41", "31"]) { + for (const twoPlayerMode of players === 2 ? ["bank", "fourHands"] : ["bank"]) { + for (const teamPlay of players === 4 ? [false, true] : [false]) { + combos.push({ + ...(publicHoldings ? { publicHoldings } : {}), + ...(autoEnd ? { autoEnd } : {}), + ...(teamPlay ? { teamPlay } : {}), + twoPlayerMode, + endSize, + }); + } + } + } + } + } + return combos; +} + +const MOVE_LIMIT = 5000; +const REPLAY_SAMPLES = 6; + +interface Boundary { + logLength: number; + state: GameState; +} + +/** + * Plays one random game to the end through the BGS wrapper, round-tripping the state through + * JSON between calls as BGS storage does. With `drops`, players occasionally drop out. + */ +function simulate(players: number, options: Record, seed: string, drops: boolean) { + const random = lcg([...seed].reduce((sum, ch) => sum * 31 + ch.charCodeAt(0), 7) >>> 0); + let state = wrapper.init(players, [], options, seed); + checkInvariants(state); + const boundaries: Boundary[] = [{ logLength: wrapper.logLength(state), state: structuredClone(state) }]; + let actions = 0; + while (!wrapper.ended(state)) { + assert.ok(actions++ < MOVE_LIMIT, `§14.8 ${seed} did not finish`); + if (drops && random() < 0.01) { + const candidates = Array.from({ length: players }, (_, p) => p).filter((p) => + state.seatOwner.some((owner, seat) => owner === p && !state.seats[seat]!.dropped) + ); + const before = remainingPlayers(state); + wrapper.dropPlayer(state, candidates[Math.floor(random() * candidates.length)]!); + assert.equal(state.ended, before - 1 <= 1, "§16 the game ends exactly when one player or none remains"); + } else { + const player = wrapper.currentPlayer(state); + assert.notEqual(player, undefined, "an unfinished game always has a player to act"); + const moves = legalMoves(state); + assert.ok(moves.length > 0, `${seed}: the acting player always has a legal move`); + const announce = moves.filter((move) => move.type === "announce"); + const others = moves.filter((move) => move.type !== "announce"); + const choices = announce.length > 0 && (others.length === 0 || random() < 0.1) ? announce : others; + wrapper.move(state, choices[Math.floor(random() * choices.length)]!, player!); + } + state = JSON.parse(JSON.stringify(state)) as GameState; + checkInvariants(state); + boundaries.push({ logLength: wrapper.logLength(state), state: structuredClone(state) }); + } + assert.equal(wrapper.currentPlayer(state), undefined); + assert.equal(wrapper.scores(state).length, players); + assert.equal(wrapper.rankings(state).length, players); + return { state, boundaries, random }; +} + +function checkReplay(seed: string, final: GameState, boundaries: Boundary[], random: () => number): void { + assert.deepEqual(wrapper.replay(final), final, `§14.7 ${seed}: replaying the whole log rebuilds the final state`); + const picks = new Set([0, boundaries.length - 1]); + while (picks.size < Math.min(REPLAY_SAMPLES + 2, boundaries.length)) { + picks.add(Math.floor(random() * boundaries.length)); + } + for (const index of picks) { + const { logLength, state } = boundaries[index]!; + const replayed = wrapper.replay(final, { to: logLength }); + assert.equal(wrapper.logLength(replayed), logLength); + assert.deepEqual(replayed, state, `§14.7 ${seed}: replay to ${logLength} rebuilds the state at that point`); + } +} + +for (let players = 2; players <= 6; players++) { + test(`§14 simulation: ${players} players, every valid option combination, with and without drops`, () => { + const seen = { drops: 0, autoMoves: 0, autoDisposals: 0 }; + for (const options of optionCombinations(players)) { + for (const drops of [false, true]) { + const seed = `sim-${players}-${drops ? "drops" : "full"}-${JSON.stringify(options)}`; + const { state, boundaries, random } = simulate(players, options, seed, drops); + checkReplay(seed, state, boundaries, random); + for (const entry of state.log) { + seen.drops += entry.type === "dropped" ? 1 : 0; + if (entry.type === "move" && entry.auto === true) { + seen.autoMoves++; + seen.autoDisposals += entry.move.type === "dispose" ? 1 : 0; + } + } + } + } + assert.ok(seen.drops > 0, "the simulation includes drops"); + if (players >= 3) { + // With two players any drop ends the game, so only larger games auto-play. + assert.ok( + seen.autoMoves > 0 && seen.autoDisposals > 0, + "the simulation includes auto-played moves and disposals" + ); + } + }); +} + +test("§15 the simulation covers every valid option combination", () => { + assert.deepEqual( + [2, 3, 4, 5, 6].map((players) => optionCombinations(players).length), + [16, 8, 16, 8, 8] + ); +}); diff --git a/packages/engine/src/simple.spec.ts b/packages/engine/src/simple.spec.ts new file mode 100644 index 0000000..a2cc61d --- /dev/null +++ b/packages/engine/src/simple.spec.ts @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { initGame } from "./setup.js"; +import { simpleLine, turnSummary } from "./simple.js"; +import { t } from "./test/helpers.js"; +import type { GameState, LogEntry } from "./types.js"; +import * as wrapper from "../wrapper.js"; + +function named(players: number, options: Record = {}): GameState { + const state = initGame(players, options, "simple"); + ["Ann", "Bo", "Cy", "Di"] + .slice(0, players) + .forEach((name, player) => wrapper.setPlayerMetaData(state, player, { name })); + return state; +} + +const disposed: LogEntry = { type: "disposed", seat: 1, chain: "luxor", sold: 2, traded: 4, held: 3, proceeds: 1200 }; + +test("simple lines read as plain English sentences", () => { + const state = named(3); + assert.equal(simpleLine(state, { type: "move", seat: 0, move: { type: "place", tile: "5C" } }), "Ann placed 5C"); + assert.equal( + simpleLine(state, { type: "bought", seat: 2, shares: { tower: 2, continental: 1 }, cost: 1500 }), + "Cy bought 2 Tower and 1 Continental for $1,500" + ); + assert.equal(simpleLine(state, { type: "drew", seat: 1, count: 1 }), "Bo drew a tile"); + assert.equal( + simpleLine(state, { type: "bonuses", chain: "imperial", size: 12, payouts: [{ seat: 0, amount: 10500 }] }), + "Imperial bonuses at size 12: Ann $10,500" + ); + assert.equal( + simpleLine(state, { type: "gameEnd", reason: "stall" }), + "Game over: a full round passed with no tile placed" + ); +}); + +test("§13 simple lines leave out how many shares were kept while holdings are private", () => { + assert.equal(simpleLine(named(3), disposed), "Bo sold 2 Luxor for $1,200 and traded 4 Luxor for 2 of the survivor"); + assert.equal(simpleLine(named(3), { ...disposed, sold: 0, traded: 0, proceeds: 0 }), "Bo kept their Luxor shares"); + assert.equal( + simpleLine(named(3, { publicHoldings: true }), disposed), + "Bo sold 2 Luxor for $1,200, traded 4 Luxor for 2 of the survivor and kept 3 Luxor" + ); +}); + +test("simple lines name the seat when a player controls two (§15 fourHands)", () => { + const state = named(2, { twoPlayerMode: "fourHands" }); + assert.equal(simpleLine(state, { type: "drew", seat: 2, count: 1 }), "Ann (seat 3) drew a tile"); +}); + +test("simple lines describe bank tiles (§12)", () => { + const state = named(2); + assert.equal( + simpleLine(state, { type: "merger", seat: 0, tile: t("9F"), sizes: { tower: 3, luxor: 2 }, byBank: true }), + "The bank's tile 9F merges Tower (3) and Luxor (2)" + ); +}); + +test("logSlice gives every entry a simple line, using the current player names", () => { + const state = named(4); + const { log } = wrapper.logSlice(state, {}); + assert.equal(log.length, state.log.length); + for (const entry of log) { + assert.ok(entry.simple.length > 0, entry.type); + } + assert.match(log.find((entry) => entry.type === "turnOrder")!.simple, /goes first$/); + assert.ok(!("simple" in state.log[0]!), "simple lines are not stored in the game state"); +}); + +const merger: LogEntry[] = [ + { type: "turn", seat: 0 }, + { type: "move", seat: 0, move: { type: "place", tile: "6E" } }, + { type: "merger", seat: 0, tile: t("6E"), sizes: { luxor: 2, tower: 4 } }, + { type: "mergerPlan", survivor: "tower", defunct: ["luxor"] }, + { type: "bonuses", chain: "luxor", size: 2, payouts: [{ seat: 1, amount: 3000 }] }, + { type: "disposed", seat: 1, chain: "luxor", sold: 1, traded: 0, held: 0, proceeds: 200 }, + { type: "merged", survivor: "tower", size: 7 }, + { type: "move", seat: 0, move: { type: "buy", shares: { tower: 2 } } }, + { type: "bought", seat: 0, shares: { tower: 2 }, cost: 1400 }, + { type: "drew", seat: 0, count: 1 }, + { type: "turn", seat: 1 }, +]; + +test("the next turn's line sums up the turn that just finished, placement first", () => { + const state = named(3); + state.log = merger; + assert.equal(turnSummary(state, 10), "Ann merged Luxor into Tower, bought 2 Tower"); + assert.equal(wrapper.logSlice(state, { start: 7 }).log.at(-1)!.simple, "Ann merged Luxor into Tower, bought 2 Tower"); + assert.equal(turnSummary(state, 0), "The game started"); +}); + +test("turn summaries cover founding, no placement and announcing", () => { + const state = named(3); + state.log = [ + { type: "turn", seat: 1 }, + { type: "move", seat: 1, move: { type: "place", tile: "3B" } }, + { type: "founded", seat: 1, chain: "imperial", size: 2, bonus: true }, + { type: "move", seat: 1, move: { type: "buy", shares: {} } }, + { type: "bought", seat: 1, shares: {}, cost: 0 }, + { type: "turn", seat: 2 }, + { type: "skipPlace", seat: 2 }, + { type: "move", seat: 2, move: { type: "announce" } }, + { type: "announced", seat: 2 }, + { type: "turn", seat: 0 }, + ]; + assert.equal(turnSummary(state, 5), "Bo founded Imperial"); + assert.equal(turnSummary(state, 9), "Cy placed no tile, announced the end"); +}); diff --git a/packages/engine/src/simple.ts b/packages/engine/src/simple.ts new file mode 100644 index 0000000..0cff69f --- /dev/null +++ b/packages/engine/src/simple.ts @@ -0,0 +1,199 @@ +// English one-line summaries of log entries, shown by BGS as a game's last move. BGS uses the +// last line a move wrote; after a full turn that is the next "turn" entry, so its line sums up +// the turn that just ended. Kept defunct shares are left out while holdings are private. +import { CHAINS, type ChainId } from "./config.js"; +import { tileLabel, type Tile } from "./tiles.js"; +import type { GameState, LogEntry } from "./types.js"; + +const chainName = (chain: ChainId) => CHAINS.find((c) => c.id === chain)!.name; + +function money(amount: number): string { + return `$${String(amount).replace(/\B(?=(\d{3})+$)/g, ",")}`; +} + +function list(items: string[]): string { + return items.length < 2 ? (items[0] ?? "") : `${items.slice(0, -1).join(", ")} and ${items.at(-1)}`; +} + +function count(n: number, noun: string): string { + return `${n} ${noun}${n === 1 ? "" : "s"}`; +} + +function shareList(shares: Partial>): string { + return list(Object.entries(shares).map(([chain, n]) => `${n} ${chainName(chain as ChainId)}`)); +} + +const tiles = (labels: Tile[]) => list(labels.map(tileLabel)); + +const BANK_TILE = { + loose: "stays loose", + joined: "joins a chain", + merger: "causes a merger", + removed: "cannot be played and is removed", +} as const; + +const GAME_END = { + announced: "the end was announced", + condition: "an end condition was met", + stall: "a full round passed with no tile placed", + dropped: "only one player remained", +} as const; + +function seatName(state: GameState, index: number): string { + const name = state.seats[index]?.name ?? `Seat ${index + 1}`; + return state.players === state.seats.length ? name : `${name} (seat ${index + 1})`; +} + +/** The line for the log entry at `index`: a "turn" entry sums up the turn before it. */ +export function simpleLineAt(state: GameState, index: number): string { + const entry = state.log[index]!; + return entry.type === "turn" ? turnSummary(state, index) : simpleLine(state, entry); +} + +/** + * The turn that ended just before the "turn" entry at `index`, most important first: the + * placement (or the founding or merger it caused), then purchases, then an announcement. + * For example "Ann merged Luxor into Tower, bought 2 Tower". + */ +export function turnSummary(state: GameState, index: number): string { + let start = index - 1; + while (start >= 0 && state.log[start]!.type !== "turn") { + start--; + } + if (start < 0) { + return "The game started"; + } + const seat = (state.log[start] as Extract).seat; + let placement = "placed no tile"; + let bankMerger = false; + const parts: string[] = []; + for (const entry of state.log.slice(start + 1, index)) { + if (entry.type === "move" && entry.move.type === "place") { + placement = `placed ${entry.move.tile}`; + } else if (entry.type === "founded") { + placement = `founded ${chainName(entry.chain)}`; + } else if (entry.type === "merger") { + bankMerger = entry.byBank === true; + } else if (entry.type === "mergerPlan" && !bankMerger && !placement.startsWith("merged")) { + placement = `merged ${list(entry.defunct.map(chainName))} into ${chainName(entry.survivor)}`; + } else if (entry.type === "bought" && Object.keys(entry.shares).length > 0) { + parts.push(`bought ${shareList(entry.shares)}`); + } else if (entry.type === "announced") { + parts.push("announced the end"); + } else if (entry.type === "dropped" && entry.seat === seat) { + parts.push("left the game"); + } + } + return `${seatName(state, seat)} ${[placement, ...parts].join(", ")}`; +} + +export function simpleLine(state: GameState, entry: LogEntry): string { + const seat = (index: number) => seatName(state, index); + switch (entry.type) { + case "init": + return `New game for ${count(entry.players, "player")}`; + case "optionIgnored": + return `Option ${entry.option} was ignored: ${entry.reason}`; + case "turnOrder": + return `Turn order tiles: ${list(entry.tiles.map((tile, i) => `${seat(i)} ${tileLabel(tile)}`))}. ${seat(entry.first)} goes first`; + case "turn": + return `${seat(entry.seat)}'s turn`; + case "move": { + const name = seat(entry.seat); + const auto = entry.auto ? " (automatic)" : ""; + const move = entry.move; + switch (move.type) { + case "place": + return `${name} placed ${move.tile}${auto}`; + case "pass": + return `${name} placed no tile${auto}`; + case "announce": + return `${name} announced the end of the game`; + case "found": + return `${name} named the new chain ${chainName(move.chain)}${auto}`; + case "survivor": + return `${name} chose ${chainName(move.chain)} to survive${auto}`; + case "defunctOrder": + return `${name} chose the order ${list(move.chains.map(chainName))}${auto}`; + case "dispose": + return `${name} sold ${move.sell} and traded ${move.trade}${auto}`; + case "buy": { + const bought = shareList(move.shares); + return bought ? `${name} bought ${bought}${auto}` : `${name} bought nothing${auto}`; + } + } + break; + } + case "skipPlace": + return `${seat(entry.seat)} placed no tile`; + case "founded": + return `${seat(entry.seat)} founded ${chainName(entry.chain)} (${count(entry.size, "tile")})${entry.bonus ? " and received a free share" : "; no free share was left"}`; + case "grew": + return `${chainName(entry.chain)} grew to ${count(entry.size, "tile")}`; + case "merger": { + const chains = list( + Object.entries(entry.sizes).map(([chain, size]) => `${chainName(chain as ChainId)} (${size})`) + ); + const tile = tileLabel(entry.tile); + return entry.byBank + ? `The bank's tile ${tile} merges ${chains}` + : `${seat(entry.seat)}'s ${tile} merges ${chains}`; + } + case "mergerPlan": + return `${chainName(entry.survivor)} survives and takes over ${list(entry.defunct.map(chainName))}`; + case "bonuses": { + const paid = entry.payouts.map((payout) => `${seat(payout.seat)} ${money(payout.amount)}`); + let line = `${chainName(entry.chain)} bonuses at size ${entry.size}: ${paid.length > 0 ? list(paid) : "nobody paid"}`; + if (entry.bank) { + line += + entry.bank.tile === null + ? "; the bank held 0 shares (empty pool)" + : `; the bank held ${count(entry.bank.shares, "share")} (drew ${tileLabel(entry.bank.tile)})`; + if (entry.bank.amount > 0) { + line += ` and kept ${money(entry.bank.amount)}`; + } + } + return line; + } + case "disposed": { + const chain = chainName(entry.chain); + // Even "kept some" vs "kept none" reveals a holding, so ignore `held` when private. + const actions = [ + entry.sold > 0 ? `sold ${entry.sold} ${chain} for ${money(entry.proceeds)}` : "", + entry.traded > 0 ? `traded ${entry.traded} ${chain} for ${entry.traded / 2} of the survivor` : "", + entry.held > 0 && state.options.publicHoldings ? `kept ${entry.held} ${chain}` : "", + ].filter(Boolean); + if (actions.length > 0) { + return `${seat(entry.seat)} ${list(actions)}`; + } + return state.options.publicHoldings && entry.held === 0 + ? `${seat(entry.seat)} had nothing to dispose of` + : `${seat(entry.seat)} kept their ${chain} shares`; + } + case "merged": + return `${chainName(entry.survivor)} now has ${count(entry.size, "tile")}`; + case "bankTile": + return `The bank's tile ${tileLabel(entry.tile)} ${BANK_TILE[entry.result]}`; + case "bought": { + const bought = shareList(entry.shares); + return bought + ? `${seat(entry.seat)} bought ${bought} for ${money(entry.cost)}` + : `${seat(entry.seat)} bought no shares`; + } + case "discarded": + return `${seat(entry.seat)} discarded unplayable ${tiles(entry.tiles)}`; + case "drew": + return entry.count === 1 ? `${seat(entry.seat)} drew a tile` : `${seat(entry.seat)} drew ${entry.count} tiles`; + case "dropped": + return `${seat(entry.seat)} left the game`; + case "announced": + return `${seat(entry.seat)} announced the end of the game`; + case "gameEnd": + return `Game over: ${GAME_END[entry.reason]}`; + case "finalSale": + return `${seat(entry.seat)} sold ${entry.shares} ${chainName(entry.chain)} for ${money(entry.proceeds)}`; + case "result": + return `Final cash: ${list(entry.cash.map((cash, s) => `${seat(s)} ${money(cash)}`))}`; + } + return ""; +} diff --git a/packages/engine/src/test/helpers.ts b/packages/engine/src/test/helpers.ts new file mode 100644 index 0000000..d21c2e3 --- /dev/null +++ b/packages/engine/src/test/helpers.ts @@ -0,0 +1,137 @@ +import assert from "node:assert/strict"; +import { activeChains } from "../board.js"; +import { CHAIN_IDS, SHARES_PER_CHAIN, TILE_COUNT, type ChainId } from "../config.js"; +import { initGame } from "../setup.js"; +import { allTiles, neighbours, parseTile, type Tile } from "../tiles.js"; +import { startTurn } from "../turn.js"; +import type { Cell, GameState, Shares } from "../types.js"; + +export function t(label: string): Tile { + const tile = parseTile(label); + assert.notEqual(tile, undefined, `bad tile label ${label}`); + return tile!; +} + +export interface Scenario { + seats?: number; + /** Board contents by tile label; unlisted squares are empty. */ + board?: Record>; + /** Hands by seat, as tile labels. */ + hands?: string[][]; + /** The next tiles to be drawn, in draw order. All other free tiles sit beneath them. */ + poolTop?: string[]; + /** Tiles removed from the game. */ + removed?: string[]; + /** When set, the pool holds only poolTop (all other free tiles are removed from the game). */ + poolOnly?: boolean; + cash?: number[]; + shares?: Partial[]; + activeSeat?: number; + options?: Record; +} + +/** + * Builds a game in an exact position and starts the active seat's turn. Every tile stays in + * exactly one place, so the rules.md §14 invariants hold for the constructed state. + */ +export function scenario(spec: Scenario): GameState { + const fourHands = spec.options?.twoPlayerMode === "fourHands"; + const state = initGame(fourHands ? 2 : (spec.seats ?? 3), spec.options ?? {}, "scenario"); + state.log = []; + state.turn = 0; + state.board = allTiles().map(() => null); + for (const [label, cell] of Object.entries(spec.board ?? {})) { + state.board[t(label)] = cell; + } + state.seats.forEach((seat, i) => { + seat.hand = (spec.hands?.[i] ?? []).map(t); + seat.cash = spec.cash?.[i] ?? seat.cash; + for (const chain of CHAIN_IDS) { + seat.shares[chain] = spec.shares?.[i]?.[chain] ?? 0; + } + }); + for (const chain of CHAIN_IDS) { + state.bank[chain] = SHARES_PER_CHAIN - state.seats.reduce((sum, seat) => sum + seat.shares[chain], 0); + } + state.bankTiles = []; + state.removed = (spec.removed ?? []).map(t); + const top = (spec.poolTop ?? []).map(t); + const used = new Set([ + ...top, + ...state.removed, + ...state.bankTiles, + ...state.seats.flatMap((seat) => seat.hand), + ...allTiles().filter((tile) => state.board[tile] !== null), + ]); + const rest = allTiles().filter((tile) => !used.has(tile)); + if (spec.poolOnly) { + state.removed.push(...rest); + state.pool = [...top].reverse(); + } else { + state.pool = [...rest, ...[...top].reverse()]; + } + state.activeSeat = spec.activeSeat ?? 0; + state.pendingTile = null; + state.endAnnounced = null; + state.turnsWithoutPlacement = 0; + startTurn(state); + return state; +} + +/** Tiles of one chain, as a board spec fragment. */ +export function chainAt(chain: ChainId, labels: string[]): Record { + return Object.fromEntries(labels.map((label) => [label, chain])); +} + +/** A straight run of tiles in one row, e.g. row("A", 1, 4) = 1A..4A. */ +export function row(letter: string, from: number, to: number): string[] { + return Array.from({ length: to - from + 1 }, (_, i) => `${from + i}${letter}`); +} + +/** rules.md §14 invariants 1-6. */ +export function checkInvariants(state: GameState): void { + for (const chain of CHAIN_IDS) { + const held = state.seats.reduce((sum, seat) => sum + seat.shares[chain], 0); + assert.equal(state.bank[chain] + held, SHARES_PER_CHAIN, `§14.1 shares of ${chain}`); + assert.ok(state.bank[chain] >= 0, `§14.1 bank shares of ${chain} non-negative`); + } + for (const seat of state.seats) { + assert.ok(Number.isInteger(seat.cash) && seat.cash >= 0 && seat.cash % 100 === 0, `§14.2 cash ${seat.cash}`); + } + const places = [ + ...state.pool, + ...state.removed, + ...state.bankTiles, + ...state.seats.flatMap((seat) => seat.hand), + ...allTiles().filter((tile) => state.board[tile] !== null), + ]; + assert.equal(places.length, TILE_COUNT, "§14.3 every tile is somewhere"); + assert.equal(new Set(places).size, TILE_COUNT, "§14.3 no tile is in two places"); + + const chains = activeChains(state.board); + assert.ok(chains.length <= CHAIN_IDS.length, "§14.5 at most 7 chains"); + for (const chain of chains) { + const tiles = allTiles().filter((tile) => state.board[tile] === chain); + assert.ok(tiles.length >= 2, `§14.4 ${chain} has at least 2 tiles`); + const reached = new Set([tiles[0]!]); + const frontier = [tiles[0]!]; + while (frontier.length > 0) { + for (const next of neighbours(frontier.pop()!)) { + if (state.board[next] === chain && !reached.has(next)) { + reached.add(next); + frontier.push(next); + } + } + } + assert.equal(reached.size, tiles.length, `§14.4 ${chain} is connected`); + for (const tile of tiles) { + for (const next of neighbours(tile)) { + const cell = state.board[next]; + if (cell !== null && cell !== "loose") { + assert.equal(cell, chain, `§14.4 ${chain} touches ${cell}`); + } + } + } + } + assert.deepEqual(JSON.parse(JSON.stringify(state)), state, "§14.6 state is JSON-serializable"); +} diff --git a/packages/engine/src/tiles.spec.ts b/packages/engine/src/tiles.spec.ts new file mode 100644 index 0000000..415d04d --- /dev/null +++ b/packages/engine/src/tiles.spec.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { allTiles, neighbours, parseTile, sortTiles, tileLabel } from "./tiles.js"; + +test("§1 board has 108 squares from 1A to 12I, each with a unique label", () => { + const labels = allTiles().map(tileLabel); + assert.equal(labels.length, 108); + assert.equal(new Set(labels).size, 108); + assert.equal(labels[0], "1A"); + assert.equal(labels.at(-1), "12I"); + for (const label of labels) { + assert.equal(tileLabel(parseTile(label)!), label); + } +}); + +test("§1 malformed tile labels are rejected", () => { + for (const bad of ["", "0A", "13A", "1J", "A1", "1a", "01A", 5, null, undefined]) { + assert.equal(parseTile(bad), undefined, String(bad)); + } +}); + +test("§2 adjacency is edge-sharing only, never diagonal", () => { + const label = (tiles: number[]) => sortTiles(tiles).map(tileLabel); + assert.deepEqual(label(neighbours(parseTile("5E")!)), ["4E", "5D", "5F", "6E"]); + assert.deepEqual(label(neighbours(parseTile("1A")!)), ["1B", "2A"]); + assert.deepEqual(label(neighbours(parseTile("12I")!)), ["11I", "12H"]); + assert.deepEqual(label(neighbours(parseTile("1I")!)), ["1H", "2I"]); +}); + +test("§3.3 tile order compares number first, then letter", () => { + const order = ["2B", "2E", "3A", "10A", "1I"].map((l) => parseTile(l)!); + assert.deepEqual(sortTiles(order).map(tileLabel), ["1I", "2B", "2E", "3A", "10A"]); +}); diff --git a/packages/engine/src/tiles.ts b/packages/engine/src/tiles.ts new file mode 100644 index 0000000..6a8e0a6 --- /dev/null +++ b/packages/engine/src/tiles.ts @@ -0,0 +1,61 @@ +import { BOARD_COLUMNS, BOARD_ROWS, TILE_COUNT } from "./config.js"; + +// A tile is its square's index: (column - 1) * 9 + row. Ascending index is the rules.md §3.3 +// board order (by number, then letter), so "lowest tile" is the smallest index. +export type Tile = number; + +const ROW_LETTERS = "ABCDEFGHI"; + +export function tileColumn(tile: Tile): number { + return Math.floor(tile / BOARD_ROWS) + 1; +} + +export function tileRow(tile: Tile): number { + return tile % BOARD_ROWS; +} + +export function tileLabel(tile: Tile): string { + return `${tileColumn(tile)}${ROW_LETTERS[tileRow(tile)]}`; +} + +export function parseTile(label: unknown): Tile | undefined { + if (typeof label !== "string") { + return undefined; + } + const match = /^([1-9]|1[0-2])([A-I])$/.exec(label); + if (!match) { + return undefined; + } + return (Number(match[1]) - 1) * BOARD_ROWS + ROW_LETTERS.indexOf(match[2]!); +} + +export function isTile(value: unknown): value is Tile { + return Number.isInteger(value) && (value as number) >= 0 && (value as number) < TILE_COUNT; +} + +export function neighbours(tile: Tile): Tile[] { + const column = tileColumn(tile); + const row = tileRow(tile); + const result: Tile[] = []; + if (column > 1) { + result.push(tile - BOARD_ROWS); + } + if (column < BOARD_COLUMNS) { + result.push(tile + BOARD_ROWS); + } + if (row > 0) { + result.push(tile - 1); + } + if (row < BOARD_ROWS - 1) { + result.push(tile + 1); + } + return result; +} + +export function allTiles(): Tile[] { + return Array.from({ length: TILE_COUNT }, (_, tile) => tile); +} + +export function sortTiles(tiles: Tile[]): Tile[] { + return tiles.sort((a, b) => a - b); +} diff --git a/packages/engine/src/turn.spec.ts b/packages/engine/src/turn.spec.ts new file mode 100644 index 0000000..514bacb --- /dev/null +++ b/packages/engine/src/turn.spec.ts @@ -0,0 +1,335 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { activeChains, chainSize } from "./board.js"; +import { applyMove } from "./moves.js"; +import { tileLabel } from "./tiles.js"; +import { chainAt, checkInvariants, row, scenario, t } from "./test/helpers.js"; +import type { GameState } from "./types.js"; + +const SIX_CHAINS = { + ...chainAt("tower", ["1A", "2A"]), + ...chainAt("luxor", ["4A", "5A"]), + ...chainAt("worldwide", ["7A", "8A"]), + ...chainAt("american", ["10A", "11A"]), + ...chainAt("festival", ["1C", "2C"]), + ...chainAt("imperial", ["4C", "5C"]), +}; +const SEVEN_CHAINS = { ...SIX_CHAINS, ...chainAt("continental", ["7C", "8C"]) }; +const SAFE_PAIR = { ...chainAt("tower", row("A", 1, 11)), ...chainAt("luxor", row("C", 1, 11)) }; + +function play(state: GameState, seat: number, move: unknown): GameState { + applyMove(state, move, seat); + checkInvariants(state); + return state; +} + +const place = (tile: string) => ({ type: "place", tile }); +const buy = (shares: Record = {}) => ({ type: "buy", shares }); + +test("§5.1 a tile with no neighbours becomes loose and the turn passes clockwise", () => { + const state = scenario({ hands: [["5E"], ["9G"], ["11G"]] }); + play(state, 0, place("5E")); + assert.equal(state.board[t("5E")], "loose"); + assert.equal(state.activeSeat, 1); + assert.equal(state.phase, "place"); +}); + +test("§3.3 play proceeds in ascending seat order and wraps around", () => { + const state = scenario({ hands: [["9G"], ["11G"], ["5E"]], activeSeat: 2 }); + play(state, 2, place("5E")); + assert.equal(state.activeSeat, 0); +}); + +test("§6.1 founding: the founder chooses any chain not on the board", () => { + const state = scenario({ board: { "5D": "loose", ...chainAt("tower", ["1A", "2A"]) }, hands: [["5E"]] }); + play(state, 0, place("5E")); + assert.equal(state.phase, "found"); + assert.equal(state.activeSeat, 0); + assert.throws(() => applyMove(state, { type: "found", chain: "tower" }, 0), /already on the board/); + play(state, 0, { type: "found", chain: "imperial" }); + assert.equal(state.board[t("5D")], "imperial"); + assert.equal(state.board[t("5E")], "imperial"); + assert.equal(state.phase, "buy"); +}); + +test("§6.2 the new chain includes all loose tiles connected to the placed tile", () => { + const state = scenario({ + board: { "5C": "loose", "5D": "loose", "6E": "loose", "7E": "loose", "9A": "loose" }, + hands: [["5E"]], + }); + play(state, 0, place("5E")); + play(state, 0, { type: "found", chain: "tower" }); + assert.equal(chainSize(state.board, "tower"), 5); + assert.equal(state.board[t("9A")], "loose"); +}); + +test("§6.3 the founder receives one free share", () => { + const state = scenario({ board: { "5D": "loose" }, hands: [["5E"]] }); + play(state, 0, place("5E")); + play(state, 0, { type: "found", chain: "luxor" }); + assert.equal(state.seats[0]!.shares.luxor, 1); + assert.equal(state.bank.luxor, 24); + assert.equal(state.seats[0]!.cash, 6000); +}); + +test("§6.3 no founder's bonus when the bank has no shares left in that chain", () => { + const state = scenario({ board: { "5D": "loose" }, hands: [["5E"]], shares: [{}, { tower: 25 }] }); + play(state, 0, place("5E")); + play(state, 0, { type: "found", chain: "tower" }); + assert.equal(state.seats[0]!.shares.tower, 0); + assert.equal(state.bank.tower, 0); + assert.deepEqual( + state.log.find((e) => e.type === "founded"), + { type: "founded", seat: 0, chain: "tower", size: 2, bonus: false } + ); +}); + +test("§6.4 stock held from an earlier merger counts once the chain is founded again", () => { + const state = scenario({ board: { "5D": "loose" }, hands: [["5E"]], shares: [{}, { festival: 4 }] }); + play(state, 0, place("5E")); + play(state, 0, { type: "found", chain: "festival" }); + assert.equal(state.seats[1]!.shares.festival, 4); + assert.equal(state.bank.festival, 20); +}); + +test("§6.1 the only remaining chain is named automatically", () => { + const state = scenario({ board: { ...SIX_CHAINS, "1G": "loose" }, hands: [["1H"]] }); + play(state, 0, place("1H")); + assert.equal(state.board[t("1H")], "continental"); + assert.equal(state.board[t("1G")], "continental"); + assert.equal(state.seats[0]!.shares.continental, 1); + assert.equal(state.phase, "buy"); +}); + +test("§5.1 joining a chain also brings in all loose tiles connected to the placed tile", () => { + const state = scenario({ + board: { ...chainAt("tower", ["1A", "2A"]), "3B": "loose", "3C": "loose" }, + hands: [["3A"]], + }); + play(state, 0, place("3A")); + assert.equal(chainSize(state.board, "tower"), 5); + assert.ok(["3A", "3B", "3C"].every((label) => state.board[t(label)] === "tower")); +}); + +test("§5.2 with all 7 chains active, a tile touching a chain and loose tiles is playable and the loose tiles join that chain", () => { + const state = scenario({ board: { ...SEVEN_CHAINS, "10C": "loose", "10D": "loose" }, hands: [["9C"], ["12I"]] }); + assert.equal(state.phase, "place"); + play(state, 0, place("9C")); + assert.ok(["9C", "10C", "10D"].every((label) => state.board[t(label)] === "continental")); + assert.equal(chainSize(state.board, "continental"), 5); +}); + +test("§5.2 a temporarily unplayable tile cannot be placed", () => { + const state = scenario({ board: { ...SEVEN_CHAINS, "1G": "loose" }, hands: [["1H", "10G"]] }); + assert.throws(() => applyMove(state, place("1H"), 0), /cannot be played/); +}); + +test("§5.2 a permanently unplayable tile cannot be placed", () => { + const state = scenario({ board: SAFE_PAIR, hands: [["1B", "10G"]] }); + assert.throws(() => applyMove(state, place("1B"), 0), /cannot be played/); +}); + +test("§5.3 a player with no playable tile skips placement but may still buy", () => { + const state = scenario({ board: { ...SEVEN_CHAINS, "1G": "loose" }, hands: [["1H"]] }); + assert.equal(state.phase, "buy"); + assert.equal(state.activeSeat, 0); + assert.ok(state.log.some((e) => e.type === "skipPlace" && e.seat === 0)); +}); + +test("§5.3 permanently unplayable tiles are discarded and replaced at the end of the turn", () => { + const state = scenario({ board: SAFE_PAIR, hands: [["1B", "10G"], ["9G"]], poolTop: ["12I", "12H"] }); + play(state, 0, place("10G")); + play(state, 0, buy()); + assert.ok(state.removed.includes(t("1B"))); + assert.ok(!state.seats[0]!.hand.includes(t("1B"))); + assert.equal(state.seats[0]!.hand.length, 6); + assert.deepEqual( + state.log.find((e) => e.type === "discarded"), + { type: "discarded", seat: 0, tiles: [t("1B")] } + ); +}); + +test("§5.3 temporarily unplayable tiles are never replaced", () => { + const state = scenario({ board: { ...SEVEN_CHAINS, "1G": "loose" }, hands: [["1H", "10G"], ["9G"]] }); + play(state, 0, place("10G")); + play(state, 0, buy()); + assert.ok(state.seats[0]!.hand.includes(t("1H"))); + assert.equal(state.removed.length, 0); +}); + +test("§4.5 after placing, the player draws one tile from the pool to get back to 6", () => { + const hand = ["5E", "9G", "11G", "3I", "6I", "9I"]; + const state = scenario({ hands: [hand, ["12A"]], poolTop: ["12C", "12E"] }); + play(state, 0, place("5E")); + assert.equal(state.seats[0]!.hand.length, 6); + assert.ok(state.seats[0]!.hand.includes(t("12C"))); + assert.ok(!state.seats[0]!.hand.includes(t("12E"))); +}); + +test("§5.3 with an empty pool nothing is drawn and hands shrink", () => { + const hand = ["5E", "9G", "11G", "3I", "6I", "9I"]; + const state = scenario({ hands: [hand, ["12A"]], poolOnly: true }); + play(state, 0, place("5E")); + assert.equal(state.seats[0]!.hand.length, 5); + assert.equal( + state.log.some((e) => e.type === "drew"), + false + ); +}); + +test("§9.1 a player may buy up to 3 shares across several chains", () => { + const board = { ...chainAt("tower", ["1A", "2A"]), ...chainAt("luxor", ["4A", "5A"]) }; + const state = scenario({ board, hands: [["9G"], ["11G"]] }); + play(state, 0, place("9G")); + assert.throws(() => applyMove(state, buy({ tower: 2, luxor: 2 }), 0), /at most 3/); + play(state, 0, buy({ tower: 2, luxor: 1 })); + assert.equal(state.seats[0]!.shares.tower, 2); + assert.equal(state.seats[0]!.shares.luxor, 1); + assert.equal(state.seats[0]!.cash, 6000 - 3 * 200); + assert.equal(state.activeSeat, 1); +}); + +test("§9.1 buying nothing ends the turn", () => { + const state = scenario({ board: chainAt("tower", ["1A", "2A"]), hands: [["9G"], ["11G"]] }); + play(state, 0, place("9G")); + play(state, 0, buy()); + assert.equal(state.activeSeat, 1); + assert.equal(state.seats[0]!.cash, 6000); +}); + +test("§9.2 shares can only be bought in chains on the board", () => { + const state = scenario({ board: chainAt("tower", ["1A", "2A"]), hands: [["9G"], ["11G"]] }); + play(state, 0, place("9G")); + assert.throws(() => applyMove(state, buy({ luxor: 1 }), 0), /on the board/); + assert.throws(() => applyMove(state, buy({ nope: 1 }), 0), /Unknown chain/); +}); + +test("§9.2 shares can only be bought while the bank has them", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["11G"]], + shares: [{}, { tower: 24 }], + }); + play(state, 0, place("9G")); + assert.throws(() => applyMove(state, buy({ tower: 2 }), 0), /bank does not have/); + play(state, 0, buy({ tower: 1 })); + assert.equal(state.bank.tower, 0); +}); + +test("§9.3 the price is based on the chain's size after this turn's placement", () => { + const state = scenario({ board: chainAt("tower", ["1A", "2A"]), hands: [["3A"], ["11G"]] }); + play(state, 0, place("3A")); + play(state, 0, buy({ tower: 3 })); + assert.equal(state.seats[0]!.cash, 6000 - 3 * 300); +}); + +test("§9.4 a player cannot buy shares they cannot afford", () => { + const state = scenario({ board: chainAt("imperial", ["1A", "2A"]), hands: [["9G"], ["11G"]], cash: [700] }); + play(state, 0, place("9G")); + assert.throws(() => applyMove(state, buy({ imperial: 2 }), 0), /cannot afford/); + play(state, 0, buy({ imperial: 1 })); + assert.equal(state.seats[0]!.cash, 300); +}); + +test("§9.6 with private holdings the buy step is not skipped for lack of cash", () => { + const state = scenario({ board: chainAt("tower", ["1A", "2A"]), hands: [["9G"], ["11G"]], cash: [100] }); + play(state, 0, place("9G")); + assert.equal(state.activeSeat, 0); + assert.equal(state.phase, "buy"); + assert.throws(() => applyMove(state, buy({ tower: 1 }), 0), /cannot afford/); + play(state, 0, buy()); + assert.equal(state.activeSeat, 1); +}); + +test("§9.6 with public holdings the buy step is skipped when the player cannot afford any share", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["11G"]], + cash: [100], + options: { publicHoldings: true }, + }); + play(state, 0, place("9G")); + assert.equal(state.activeSeat, 1); + assert.equal(state.phase, "place"); +}); + +test("§9.6 the buy step is skipped when no chain is on the board", () => { + const state = scenario({ hands: [["9G"], ["11G"]] }); + play(state, 0, place("9G")); + assert.equal(state.activeSeat, 1); +}); + +test("§9.6 the buy step is skipped when the bank has no shares in any active chain", () => { + const state = scenario({ + board: chainAt("tower", ["1A", "2A"]), + hands: [["9G"], ["11G"]], + shares: [{}, { tower: 25 }], + }); + play(state, 0, place("9G")); + assert.equal(state.activeSeat, 1); +}); + +test("§4 an end condition keeps the placement step even with no playable tile", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 11)), + hands: [[], ["11G"]], + shares: [{}, { tower: 25 }], + }); + assert.equal(state.activeSeat, 0); + assert.equal(state.phase, "place"); + play(state, 0, { type: "pass" }); + assert.equal(state.activeSeat, 0, "§4 the buy step is kept too, though nothing can be bought"); + assert.equal(state.phase, "buy"); + play(state, 0, buy()); + assert.equal(state.activeSeat, 1); +}); + +test("§4 without an end condition the same empty turn is skipped entirely", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 10)), + hands: [[], ["11G"]], + shares: [{}, { tower: 25 }], + }); + assert.equal(state.activeSeat, 1); + assert.ok(state.log.some((e) => e.type === "skipPlace" && e.seat === 0)); +}); + +test("§4 an end condition keeps the buy step after placing even when nothing can be bought", () => { + const state = scenario({ + board: chainAt("tower", row("A", 1, 11)), + hands: [["9G"], ["11G"]], + shares: [{}, { tower: 25 }], + }); + play(state, 0, place("9G")); + assert.equal(state.phase, "buy"); + assert.equal(state.activeSeat, 0); +}); + +test("§4 passing is only allowed when no tile is playable", () => { + const state = scenario({ board: chainAt("tower", row("A", 1, 11)), hands: [["9G"], ["11G"]] }); + assert.throws(() => applyMove(state, { type: "pass" }, 0), /must place/); +}); + +test("moves are validated: wrong seat, wrong phase and malformed input are rejected without changes", () => { + const state = scenario({ board: { "5D": "loose" }, hands: [["5E", "9G"], ["11G"]] }); + const before = structuredClone(state); + for (const [seat, move] of [ + [1, place("11G")], + [0, buy()], + [0, place("11G")], + [0, place("5e")], + [0, null], + [0, "place"], + [0, { type: "found", chain: "tower" }], + ] as const) { + assert.throws(() => applyMove(state, move, seat)); + assert.deepEqual(state, before); + } +}); + +test("§5.2 placing a tile and founding never lets more than 7 chains exist", () => { + const state = scenario({ board: { ...SEVEN_CHAINS, "1G": "loose" }, hands: [["1H"], ["12I"]] }); + assert.equal(activeChains(state.board).length, 7); + assert.equal(state.phase, "buy"); + assert.equal(tileLabel(state.seats[0]!.hand[0]!), "1H"); +}); diff --git a/packages/engine/src/turn.ts b/packages/engine/src/turn.ts new file mode 100644 index 0000000..9ad0d9f --- /dev/null +++ b/packages/engine/src/turn.ts @@ -0,0 +1,107 @@ +import { activeChains, chainSize, playableTiles, tileLegality } from "./board.js"; +import { AUTO_TURN_LIMIT, HAND_SIZE } from "./config.js"; +import { sharePrice } from "./prices.js"; +import { canAnnounce, endConditionMet, endGame } from "./scoring.js"; +import type { Tile } from "./tiles.js"; +import type { GameState } from "./types.js"; + +export function drawTile(state: GameState): Tile | undefined { + return state.pool.pop(); +} + +/** + * rules.md §9.6: whether the buy step has anything to offer. Only public facts count unless + * holdings are public, so skipping the step never reveals a player's cash. + */ +export function buyStepAvailable(state: GameState): boolean { + const seat = state.seats[state.activeSeat]!; + const cashIsPublic = state.options.publicHoldings; + return activeChains(state.board).some( + (chain) => state.bank[chain] > 0 && (!cashIsPublic || sharePrice(chain, chainSize(state.board, chain)) <= seat.cash) + ); +} + +/** + * Advance from the start of the active seat's turn until a player has a decision to make. + * Placement is skipped when no tile is playable (rules.md §5.3) and buying when there is + * nothing to buy (§9.6), but never at an announcement point (§4). + */ +export function startTurn(state: GameState): void { + for (let advances = 0; ; advances++) { + if (advances >= AUTO_TURN_LIMIT) { + throw new Error(`Deadlock: ${AUTO_TURN_LIMIT} turns passed automatically with no player able to act`); + } + state.turn += 1; + state.placedThisTurn = false; + state.log.push({ type: "turn", seat: state.activeSeat }); + if (playableTiles(state, state.activeSeat).length > 0 || canAnnounce(state)) { + state.phase = "place"; + return; + } + state.log.push({ type: "skipPlace", seat: state.activeSeat }); + if (buyStepAvailable(state)) { + state.phase = "buy"; + return; + } + if (finishTurn(state)) { + return; + } + } +} + +/** Called once placement (and any founding or merger) is resolved. */ +export function enterBuyPhase(state: GameState): void { + if (buyStepAvailable(state) || canAnnounce(state)) { + state.phase = "buy"; + return; + } + endTurn(state); +} + +export function endTurn(state: GameState): void { + if (!finishTurn(state)) { + startTurn(state); + } +} + +/** + * rules.md §4.4-4.5: replace permanently unplayable tiles and refill the hand. Then either end + * the game (an announcement this turn, or the §11.1 stall rule) or pass the turn on. + * Returns whether the game ended. + */ +function finishTurn(state: GameState): boolean { + const seat = state.seats[state.activeSeat]!; + const dead = seat.hand.filter((tile) => tileLegality(state.board, tile) === "permanentlyUnplayable"); + if (dead.length > 0) { + seat.hand = seat.hand.filter((tile) => !dead.includes(tile)); + state.removed.push(...dead); + state.log.push({ type: "discarded", seat: state.activeSeat, tiles: dead }); + } + let drawn = 0; + while (seat.hand.length < HAND_SIZE) { + const tile = drawTile(state); + if (tile === undefined) { + break; + } + seat.hand.push(tile); + drawn++; + } + if (drawn > 0) { + state.log.push({ type: "drew", seat: state.activeSeat, count: drawn }); + } + state.turnsWithoutPlacement = state.placedThisTurn ? 0 : state.turnsWithoutPlacement + 1; + if (state.endAnnounced !== null) { + endGame(state, "announced"); + return true; + } + if (state.options.autoEnd && endConditionMet(state)) { + endGame(state, "condition"); + return true; + } + if (state.turnsWithoutPlacement >= state.seats.length) { + endGame(state, "stall"); + return true; + } + state.activeSeat = (state.activeSeat + 1) % state.seats.length; + return false; +} diff --git a/packages/engine/src/types.ts b/packages/engine/src/types.ts new file mode 100644 index 0000000..2da465a --- /dev/null +++ b/packages/engine/src/types.ts @@ -0,0 +1,103 @@ +import type { ChainId } from "./config.js"; +import type { GameOptions } from "./options.js"; +import type { Tile } from "./tiles.js"; + +/** An empty square, a loose tile, or a tile belonging to a chain. */ +export type Cell = null | "loose" | ChainId; + +export type Shares = Record; + +export interface SeatState { + name: string; + cash: number; + shares: Shares; + hand: Tile[]; + dropped: boolean; +} + +export type Phase = "place" | "found" | "survivor" | "defunctOrder" | "dispose" | "buy" | "ended"; + +export type Move = + | { type: "place"; tile: string } + | { type: "pass" } + | { type: "announce" } + | { type: "found"; chain: ChainId } + | { type: "survivor"; chain: ChainId } + | { type: "defunctOrder"; chains: ChainId[] } + | { type: "dispose"; sell: number; trade: number } + | { type: "buy"; shares: Partial }; + +export interface MergerState { + /** The merging tile; it sits on the board as a loose tile until the board update (§7.3). */ + tile: Tile; + mergermaker: number; + /** Pre-merger sizes of every chain the tile touches (§7.1.1). */ + sizes: Partial>; + survivor: ChainId | null; + /** Defunct chains still to resolve, in resolution order. */ + defunct: ChainId[]; + /** The defunct chain whose stock is being disposed of. */ + current: ChainId | null; + /** Seats still to dispose of `current`, in order; the first one is acting. */ + disposers: number[]; +} + +export type BonusPayout = { seat: number; amount: number }; + +/** The two-player bank's fictional holding for one bonus payout (rules.md §12). */ +export type BankHolding = { tile: Tile | null; shares: number; amount: number }; + +export type LogEntry = + | { type: "init"; players: number; seats: number; options: GameOptions; rawOptions: Record } + | { type: "optionIgnored"; option: string; value: unknown; reason: string } + | { type: "dropped"; seat: number } + | { type: "turnOrder"; tiles: Tile[]; first: number } + | { type: "move"; seat: number; move: Move; auto?: true } + | { type: "turn"; seat: number } + | { type: "skipPlace"; seat: number } + | { type: "founded"; seat: number; chain: ChainId; size: number; bonus: boolean } + | { type: "grew"; chain: ChainId; size: number } + | { type: "merger"; seat: number; tile: Tile; sizes: Partial>; byBank?: true } + | { type: "mergerPlan"; survivor: ChainId; defunct: ChainId[] } + | { type: "bonuses"; chain: ChainId; size: number; payouts: BonusPayout[]; bank?: BankHolding } + | { type: "bankTile"; tile: Tile; result: "loose" | "joined" | "merger" | "removed" } + | { type: "disposed"; seat: number; chain: ChainId; sold: number; traded: number; held: number; proceeds: number } + | { type: "merged"; survivor: ChainId; size: number } + | { type: "bought"; seat: number; shares: Partial; cost: number } + | { type: "discarded"; seat: number; tiles: Tile[] } + | { type: "drew"; seat: number; count: number } + | { type: "announced"; seat: number } + | { type: "gameEnd"; reason: "announced" | "condition" | "stall" | "dropped" } + | { type: "finalSale"; seat: number; chain: ChainId; shares: number; proceeds: number } + | { type: "result"; cash: number[]; ranks: number[] }; + +export interface GameState { + seed: string; + rngCounter: number; + options: GameOptions; + /** Real (BGS) players; differs from the seat count only in fourHands. */ + players: number; + /** The real player controlling each internal seat. */ + seatOwner: number[]; + seats: SeatState[]; + board: Cell[]; + /** Draw pool; the next tile drawn is the last element. */ + pool: Tile[]; + removed: Tile[]; + bank: Shares; + activeSeat: number; + phase: Phase; + /** The tile awaiting a chain name during the "found" phase. */ + pendingTile: Tile | null; + merger: MergerState | null; + /** Two-player bank mode: drawn bank tiles waiting to be placed, in draw order (§12.1.4). */ + bankTiles: Tile[]; + /** The seat that announced the end of the game this turn (§11.1). */ + endAnnounced: number | null; + placedThisTurn: boolean; + /** Consecutive completed turns in which no tile was placed (§11.1 stall rule). */ + turnsWithoutPlacement: number; + turn: number; + log: LogEntry[]; + ended: boolean; +} diff --git a/packages/engine/src/view.ts b/packages/engine/src/view.ts new file mode 100644 index 0000000..225f5c6 --- /dev/null +++ b/packages/engine/src/view.ts @@ -0,0 +1,39 @@ +import { CHAIN_IDS } from "./config.js"; +import type { GameState, Shares } from "./types.js"; + +/** Value sent in place of anything the viewer may not see. */ +export const HIDDEN = -1; + +const HIDDEN_SHARES = Object.fromEntries(CHAIN_IDS.map((chain) => [chain, HIDDEN])) as Shares; + +/** The internal seats a real player controls (two in fourHands); none for a spectator. */ +export function seatsOf(state: GameState, player: number | undefined): number[] { + return state.seatOwner.flatMap((owner, seat) => (owner === player ? [seat] : [])); +} + +/** + * rules.md §13: the state as `player` may see it (undefined for a spectator). Hidden numbers + * are replaced by HIDDEN so the shape stays the same. Hands and the pool order are always + * private; holdings and cash are private unless publicHoldings is on or the game has ended. + * The seed is removed because it determines the pool order. + */ +export function viewFor(state: GameState, player: number | undefined): GameState { + const own = seatsOf(state, player); + const holdingsPublic = state.options.publicHoldings || state.ended; + return { + ...structuredClone(state), + seed: "", + rngCounter: 0, + pool: state.pool.map(() => HIDDEN), + seats: state.seats.map((seat, index) => { + if (own.includes(index)) { + return structuredClone(seat); + } + return { + ...structuredClone(seat), + hand: seat.hand.map(() => HIDDEN), + ...(holdingsPublic ? {} : { cash: HIDDEN, shares: { ...HIDDEN_SHARES } }), + }; + }), + }; +} diff --git a/packages/engine/src/wrapper.spec.ts b/packages/engine/src/wrapper.spec.ts new file mode 100644 index 0000000..11f9bc2 --- /dev/null +++ b/packages/engine/src/wrapper.spec.ts @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { inspectEngine, type Engine } from "@boardgamers/protocol/engine"; +import * as wrapper from "../wrapper.js"; +import type { GameState } from "./types.js"; + +const engine: Engine = wrapper; + +test("wrapper: exports every required Engine API method", () => { + const report = inspectEngine(engine); + assert.equal(report.compatible, true); + assert.deepEqual(report.required.missing, []); +}); + +test("wrapper: init creates one seat per player and a fresh game", () => { + for (let players = 2; players <= 6; players++) { + const state = wrapper.init(players, [], {}, "seed"); + assert.equal(state.seats.length, players); + assert.equal(wrapper.ended(state), false); + assert.deepEqual(wrapper.scores(state), Array(players).fill(0)); + } +}); + +test("wrapper: init rejects player counts outside 2-6", () => { + assert.throws(() => wrapper.init(1, [], {}, "seed")); + assert.throws(() => wrapper.init(7, [], {}, "seed")); +}); + +test("wrapper: state is JSON-serializable", () => { + const state = wrapper.init(4, [], {}, "seed"); + assert.deepEqual(JSON.parse(JSON.stringify(state)), state); +}); + +test("wrapper: logSlice includes both endpoints", () => { + const state = wrapper.init(3, [], {}, "seed"); + const length = wrapper.logLength(state); + assert.ok(length >= 3); + assert.equal(wrapper.logSlice(state).log.length, length); + assert.equal(wrapper.logSlice(state, { start: 0, end: 0 }).log.length, 1); + assert.equal(wrapper.logSlice(state, { start: 1, end: 2 }).log.length, 2); + assert.equal(wrapper.logSlice(state, { start: length }).log.length, 0); +}); + +test("wrapper: setPlayerMetaData stores the player name", () => { + const state = wrapper.setPlayerMetaData(wrapper.init(2, [], {}, "seed"), 1, { name: "Ada" }); + assert.equal(state.seats[1]?.name, "Ada"); +}); diff --git a/packages/engine/tsconfig.build.json b/packages/engine/tsconfig.build.json new file mode 100644 index 0000000..237b2ed --- /dev/null +++ b/packages/engine/tsconfig.build.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": ".", + "declaration": true, + "sourceMap": false, + "types": ["node"] + }, + "include": ["src/**/*.ts", "wrapper.ts", "index.ts"], + "exclude": ["src/**/*.spec.ts", "src/test/**"] +} diff --git a/packages/engine/tsconfig.json b/packages/engine/tsconfig.json new file mode 100644 index 0000000..6b1ae96 --- /dev/null +++ b/packages/engine/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "wrapper.ts", "index.ts"] +} diff --git a/packages/engine/tsconfig.test.json b/packages/engine/tsconfig.test.json new file mode 100644 index 0000000..57cae75 --- /dev/null +++ b/packages/engine/tsconfig.test.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "dist-test", + "rootDir": ".", + "declaration": false, + "sourceMap": false, + "types": ["node"] + }, + "include": ["src/**/*.ts", "wrapper.ts", "index.ts"] +} diff --git a/packages/engine/wrapper.ts b/packages/engine/wrapper.ts new file mode 100644 index 0000000..2de3d54 --- /dev/null +++ b/packages/engine/wrapper.ts @@ -0,0 +1,93 @@ +import { applyMove, currentSeat, dropPlayerSeats } from "./src/moves.js"; +import { replayGame } from "./src/replay.js"; +import { playerRankings, playerScores } from "./src/scoring.js"; +import { initGame } from "./src/setup.js"; +import { simpleLineAt } from "./src/simple.js"; +import type { GameState, LogEntry } from "./src/types.js"; +import { seatsOf, viewFor } from "./src/view.js"; + +// The seed fixes the hidden tile order, so BGS must hash it before init (rules.md §13). +export const hashSeed = true; + +// BGS addresses real players; the engine works in internal seats. They are the same except in +// fourHands, where each of the 2 players controls two seats (state.seatOwner). + +export function init( + players: number, + _expansions: string[], + options: Record, + seed: string, + _creator?: number +): GameState { + return initGame(players, options ?? {}, seed); +} + +export function move(data: GameState, mv: unknown, player: number): GameState { + const seat = currentSeat(data); + if (seat === undefined || data.seatOwner[seat] !== player) { + throw new Error("It is not your turn"); + } + // mv is untrusted JSON from the network; applyMove validates it before any mutation. + return applyMove(data, mv, seat); +} + +export function ended(data: GameState): boolean { + return data.ended; +} + +export function scores(data: GameState): number[] { + return playerScores(data); +} + +export function rankings(data: GameState): number[] { + return playerRankings(data); +} + +export function dropPlayer(data: GameState, player: number): GameState { + return dropPlayerSeats(data, player); +} + +export function currentPlayer(data: GameState): number | undefined { + const seat = currentSeat(data); + return seat === undefined ? undefined : data.seatOwner[seat]; +} + +export function stripSecret(data: GameState, player?: number): GameState { + return viewFor(data, player); +} + +export function logLength(data: GameState): number { + return data.log.length; +} + +export interface LogSliceOptions { + player?: number; + start?: number; + end?: number; +} + +// Both endpoints are inclusive. The log is public (rules.md §13), so every viewer gets the same +// slice. Each entry gets a `simple` line for BGS's last-move display. +export function logSlice(data: GameState, options?: LogSliceOptions): { log: (LogEntry & { simple: string })[] } { + const start = Math.max(0, options?.start ?? 0); + const end = options?.end ?? data.log.length - 1; + return { + log: data.log.slice(start, end + 1).map((entry, i) => ({ ...entry, simple: simpleLineAt(data, start + i) })), + }; +} + +export function setPlayerMetaData(data: GameState, player: number, metaData: { name: string }): GameState { + for (const seat of seatsOf(data, player)) { + data.seats[seat]!.name = metaData.name; + } + return data; +} + +export function round(data: GameState): number { + return Math.ceil(data.turn / data.seats.length); +} + +/** BGS undo (games against bots) and analysis: `to` is a log length at a move boundary. */ +export function replay(data: GameState, options?: { to?: number }): GameState { + return replayGame(data, options?.to); +} diff --git a/packages/viewer/dev-badge.svg b/packages/viewer/dev-badge.svg new file mode 100644 index 0000000..4cc26f1 --- /dev/null +++ b/packages/viewer/dev-badge.svg @@ -0,0 +1 @@ + diff --git a/packages/viewer/index.html b/packages/viewer/index.html new file mode 100644 index 0000000..e2d5762 --- /dev/null +++ b/packages/viewer/index.html @@ -0,0 +1,16 @@ + + + + + + Acquire viewer - dev harness + + +
+
+ + + diff --git a/packages/viewer/package.json b/packages/viewer/package.json new file mode 100644 index 0000000..d7700aa --- /dev/null +++ b/packages/viewer/package.json @@ -0,0 +1,30 @@ +{ + "name": "acquire-viewer", + "version": "0.0.1", + "private": true, + "description": "Browser viewer for Acquire on boardgamers.space", + "license": "AGPL-3.0-only", + "type": "module", + "main": "dist/acquire-viewer.iife.js", + "scripts": { + "dev": "vite", + "build": "vite build", + "tsc": "svelte-check --tsconfig ./tsconfig.json", + "test": "node --test \"src/**/*.spec.ts\"" + }, + "dependencies": { + "@boardgamers/protocol": "0.10.0", + "acquire-engine": "workspace:*" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "7.2.0", + "@types/node": "24.10.1", + "svelte": "5.56.8", + "svelte-check": "4.7.4", + "typescript": "5.9.3", + "vite": "8.2.0" + }, + "engines": { + "node": ">=24" + } +} diff --git a/packages/viewer/src/App.svelte b/packages/viewer/src/App.svelte new file mode 100644 index 0000000..dc49578 --- /dev/null +++ b/packages/viewer/src/App.svelte @@ -0,0 +1,92 @@ + + +
+ {#if store.state} + {@const state = store.view!} +
+
+ + +
+
+ + store.selected !== undefined && store.send({ type: "place", tile: tileLabel(store.selected) })} + /> +
+ {#if store.seats.length > 0 && store.replayAt === undefined} +
+ {/if} +
+ + + + {#if !store.analysis} + + {/if} + +
+
+ {:else} +

{store.lang.t("loading")}

+ {/if} +
+ + diff --git a/packages/viewer/src/dev.ts b/packages/viewer/src/dev.ts new file mode 100644 index 0000000..7b30a42 --- /dev/null +++ b/packages/viewer/src/dev.ts @@ -0,0 +1,252 @@ +// Local dev harness (not part of the BGS bundle): runs the real engine in the page, plays +// random moves on request, and lets you view the game as any player or as a spectator. +// URL parameters: players=2..6, seed=..., view=N, hotseat=0, theme=light|dark, locale=de, and any game option, e.g. publicHoldings=1, +// twoPlayerMode=fourHands, teamPlay=1, autoEnd=1, endSize=31. For reproducible screenshots: moves=N plays N random moves, +// merger=1 then plays on to the next merger decision, bar=0 hides this toolbar. +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 players = Math.min(6, Math.max(2, Number(params.get("players") ?? 4))); +const seed = params.get("seed") ?? "dev"; +const options: Record = {}; +for (const key of ["publicHoldings", "teamPlay", "autoEnd"]) { + if (params.get(key) === "1") { + options[key] = true; + } +} +for (const key of ["twoPlayerMode", "endSize"]) { + const value = params.get(key); + if (value) { + options[key] = value; + } +} + +const NAMES = ["Ann", "Bo", "Cy", "Di", "Ed", "Flo"]; +let state: GameState = engine.init(players, [], options, seed); +NAMES.slice(0, players).forEach((name, player) => engine.setPlayerMetaData(state, player, { name })); +let viewAs: number | undefined = Number(params.get("view") ?? 0); +if (Number.isNaN(viewAs) || viewAs >= players) { + viewAs = undefined; +} + +const emitter = viewer.launch("#app"); + +let hotSeat = params.get("hotseat") !== "0"; + +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)}`; +} + +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) { + 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, + 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/ActionPanel.svelte b/packages/viewer/src/lib/ActionPanel.svelte new file mode 100644 index 0000000..2d8738e --- /dev/null +++ b/packages/viewer/src/lib/ActionPanel.svelte @@ -0,0 +1,376 @@ + + +{#if moves.length > 0 && !store.sending} +
+ {#if legal("announce")} +
+ {#if confirmAnnounce} +

{t("announce.ask")}

+ + + {:else} + + {/if} +
+ {/if} + + {#if game.phase === "place"} + {#if store.selected !== undefined} +

+ {t("place.effect", { + tile: tileLabel(store.selected), + effect: describePlacement(game, store.selected, lang), + })} +

+ + + {:else if legal("place")} +

{t("place.choose")}

+ {/if} + {#if legal("pass")} +

{t("place.none")}

+ + {/if} + {:else if game.phase === "found"} +

{t("found.prompt")}

+
+ {#each CHAIN_IDS as chain (chain)} + + {/each} +
+ {:else if game.phase === "survivor" && m} +

{t("survivor.prompt")}

+
+ {#each CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined) as chain (chain)} + + {/each} +
+ {:else if game.phase === "defunctOrder" && m} +

{t("order.prompt", { survivor: chainName(m.survivor!) })}

+
+ {#each CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined && chain !== m.survivor) as chain (chain)} + {@const position = order.indexOf(chain)} + + {/each} +
+ + + {:else if game.phase === "dispose" && disposing && m} +

+ +

+

+ {t("dispose.takenOver", { defunct: chainName(disposing), survivor: chainName(m.survivor!) })} + {t("dispose.holding", { count: held, chain: chainName(disposing) })} +

+
+ {t("dispose.sell", { price: money(sellPrice) })} + + {sell} + + +{money(sell * sellPrice)} + + {t("dispose.trade")} + + {trade} + + {t("dispose.receive", { count: trade / 2, chain: chainName(m.survivor!) })} + + {t("dispose.keep")} + + {held - sell - trade} + + {t("dispose.keepNote", { chain: chainName(disposing) })} +
+ + {:else if game.phase === "buy"} +

{t("buy.prompt")}

+ {#if buyable.length > 0} + + + + + + + + {#each buyable as chain (chain)} + {@const fewer = adjustShares(shares, chain, -1)} + {@const more = adjustShares(shares, chain, 1)} + + + + + + + {/each} + +
{t("buy.chain")}{t("buy.price")}{t("buy.bank")}{t("buy.buy")}
{money(price(chain))}{game.bank[chain]} + + {shares[chain] ?? 0} + +
+ {/if} +

+ {t("buy.total", { count: total, cost: money(cost), cash: money(game.seats[seat!]!.cash - cost) })} +

+ + {/if} +
+{:else if store.sending} +

{t("panel.sending")}

+{/if} + + diff --git a/packages/viewer/src/lib/Board.svelte b/packages/viewer/src/lib/Board.svelte new file mode 100644 index 0000000..807e91f --- /dev/null +++ b/packages/viewer/src/lib/Board.svelte @@ -0,0 +1,205 @@ + + +
+
+ + +
+ {#each rows as row (row)} + {#each columns as column (column)} + {@const tile = tileAt(row, column)} + {@const cell = state.board[tile] ?? null} + {@const label = tileLabel(tile)} + {#if tile === selected && cell === null} + + {:else if cell === null} +
+ {label} +
+ {:else if cell === "loose"} +
+ {label} +
+ {:else} + {@const style = CHAIN_STYLES[cell]} +
+ {#if store.colorBlind} + + + {style.letter} + {:else} + {label} + {style.letter} + {/if} +
+ {/if} + {/each} + {/each} +
+
+ + diff --git a/packages/viewer/src/lib/ChainMark.svelte b/packages/viewer/src/lib/ChainMark.svelte new file mode 100644 index 0000000..02868de --- /dev/null +++ b/packages/viewer/src/lib/ChainMark.svelte @@ -0,0 +1,82 @@ + + + + {#if patterned} + + + {:else} + + {/if} + {#if withName}{chainName(chain)}{:else}{chainName(chain)}{/if} + + + diff --git a/packages/viewer/src/lib/ChainTable.svelte b/packages/viewer/src/lib/ChainTable.svelte new file mode 100644 index 0000000..5452b91 --- /dev/null +++ b/packages/viewer/src/lib/ChainTable.svelte @@ -0,0 +1,63 @@ + + +
+

{t("chains.title")}

+ + + + + + + + {#if seats.length > 0}{/if} + + + + {#each rows as row (row.chain)} + + + + + + {#if seats.length > 0}{/if} + + {/each} + +
{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}
+
+ + diff --git a/packages/viewer/src/lib/Chat.svelte b/packages/viewer/src/lib/Chat.svelte new file mode 100644 index 0000000..c18e7bc --- /dev/null +++ b/packages/viewer/src/lib/Chat.svelte @@ -0,0 +1,54 @@ + + +
+
+
+ + diff --git a/packages/viewer/src/lib/Hand.svelte b/packages/viewer/src/lib/Hand.svelte new file mode 100644 index 0000000..6fb5037 --- /dev/null +++ b/packages/viewer/src/lib/Hand.svelte @@ -0,0 +1,111 @@ + + +{#each store.seats as seat (seat)} + + {@const hand = sortTiles(state.seats[seat]!.hand.filter((tile) => tile !== HIDDEN))} +
+

{store.seats.length > 1 ? t("hand.seat", { seat: seat + 1 }) : t("hand.yours")}

+
+ {#each hand as tile, index (index)} + {#if playable.has(tile)} + + {:else} + + {tileLabel(tile)} + {#if why(tile)}{why(tile)}{/if} + + {/if} + {:else} + {t("hand.none")} + {/each} +
+
+{/each} + + diff --git a/packages/viewer/src/lib/Log.svelte b/packages/viewer/src/lib/Log.svelte new file mode 100644 index 0000000..e0c1a69 --- /dev/null +++ b/packages/viewer/src/lib/Log.svelte @@ -0,0 +1,62 @@ + + +
+

{t("log.title")}

+
    + {#each showAll ? lines : lines.slice(0, RECENT) as line (line.index)} +
  1. {line.text}
  2. + {/each} +
+ {#if lines.length > RECENT} + + {/if} +
+ + diff --git a/packages/viewer/src/lib/PlayerName.svelte b/packages/viewer/src/lib/PlayerName.svelte new file mode 100644 index 0000000..dba00db --- /dev/null +++ b/packages/viewer/src/lib/PlayerName.svelte @@ -0,0 +1,59 @@ + + + + {#if avatar}{/if} + + {#if color}{/if} + + {#if symbol}{/if} + {playerOnly ? game.seats[seat]!.name : seatName(game, seat, store.lang)} + {#if badge}{badge.label}{/if} + + + diff --git a/packages/viewer/src/lib/Players.svelte b/packages/viewer/src/lib/Players.svelte new file mode 100644 index 0000000..ccbd8cc --- /dev/null +++ b/packages/viewer/src/lib/Players.svelte @@ -0,0 +1,90 @@ + + +
+

{t("players.title")}

+ + + + + + + + + + + {#each state.seats as seat, index (index)} + {@const held = CHAIN_IDS.filter((chain) => seat.shares[chain] !== 0)} + {@const hidden = seat.cash === HIDDEN} + + + + + + + {/each} + +
{t("players.player")}{t("players.cash")}{t("players.stock")}{t("players.tiles")}
+ {#if index === acting}▶{/if} + + {#if seats.includes(index)}{t("players.you")}{/if} + {#if index === state.activeSeat && index !== acting && !state.ended}{t("players.turn")}{/if} + {#if seat.dropped}{t("players.left")}{/if} + {store.lang.money(seat.cash)} + {#if hidden} + {t("hidden")} + {:else if held.length === 0} + {t("players.none")} + {:else} + + {#each held as chain (chain)} + {seat.shares[chain]} + {/each} + + {/if} + {seat.hand.length}
+
+ + diff --git a/packages/viewer/src/lib/PriceTable.svelte b/packages/viewer/src/lib/PriceTable.svelte new file mode 100644 index 0000000..d734a80 --- /dev/null +++ b/packages/viewer/src/lib/PriceTable.svelte @@ -0,0 +1,123 @@ + + +
+ + {#if open} + + + + {#each TIERS as tier (tier)} + + {/each} + + + + + + + {#each table as row, index (row.price)} + + {#each TIERS as tier (tier)} + {@const here = marks.filter((mark) => mark.tier === tier && mark.row === index)} + + {/each} + + + + + {/each} + +
+ {t(TIER_KEYS[tier])} + + {#each chainsInTier(tier) as chain (chain)}{/each} + + {t("prices.price")}{t("prices.first")}{t("prices.second")}
+ {rangeLabel(row.sizes[tier])} + {#if here.length > 0} + + {#each here as mark (mark.chain)}{/each} + + {/if} + {money(row.price)}{money(row.first)}{money(row.second)}
+

{t("prices.note")}

+ {/if} +
+ + diff --git a/packages/viewer/src/lib/Status.svelte b/packages/viewer/src/lib/Status.svelte new file mode 100644 index 0000000..2a45f87 --- /dev/null +++ b/packages/viewer/src/lib/Status.svelte @@ -0,0 +1,92 @@ + + +
+ {#if replaying} +

{t("status.replay", { turn: replayTurn })}

+

{t("status.replayNote")}

+ {:else} +

+ {pendingDecision(state, store.lang)}{#if yourMove}{t("status.yourDecision")}{/if} +

+ {/if} + {#if !replaying && state.endAnnounced !== null && !state.ended} +

{t("status.announced")}

+ {/if} + {#if !replaying && state.ended} +
    + {#each results as result (result.player)} +
  1. + {result.rank}. + + {store.lang.money(result.score)} +
  2. + {/each} +
+ {/if} +
+ + diff --git a/packages/viewer/src/lib/color.ts b/packages/viewer/src/lib/color.ts new file mode 100644 index 0000000..809b4e8 --- /dev/null +++ b/packages/viewer/src/lib/color.ts @@ -0,0 +1,134 @@ +// Colour maths for the palette test: colour-vision deficiency simulation, CIEDE2000 colour +// difference and WCAG contrast. Plain functions, no dependencies. + +export type Rgb = [number, number, number]; +export type Deficiency = "protanopia" | "deuteranopia" | "tritanopia"; + +export function hexToRgb(hex: string): Rgb { + const match = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex); + if (!match) { + throw new Error(`Not a #rrggbb colour: ${hex}`); + } + return [parseInt(match[1]!, 16) / 255, parseInt(match[2]!, 16) / 255, parseInt(match[3]!, 16) / 255]; +} + +function toLinear(c: number): number { + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; +} + +function toGamma(c: number): number { + const clamped = Math.min(1, Math.max(0, c)); + return clamped <= 0.0031308 ? clamped * 12.92 : 1.055 * clamped ** (1 / 2.4) - 0.055; +} + +// Machado, Oliveira & Fernandes (2009), "A Physiologically-based Model for Simulation of +// Color Vision Deficiency", severity 1.0 matrices, applied to linear RGB. +const MACHADO: Record = { + protanopia: [ + [0.152286, 1.052583, -0.204868], + [0.114503, 0.786281, 0.099216], + [-0.003882, -0.048116, 1.051998], + ], + deuteranopia: [ + [0.367322, 0.860646, -0.227968], + [0.280085, 0.672501, 0.047413], + [-0.01182, 0.04294, 0.968881], + ], + tritanopia: [ + [1.255528, -0.076749, -0.178779], + [-0.078411, 0.930809, 0.147602], + [0.004733, 0.691367, 0.3039], + ], +}; + +/** How an sRGB colour (0-1 channels) appears with a full colour-vision deficiency. */ +export function simulate(rgb: Rgb, deficiency: Deficiency): Rgb { + const linear = rgb.map(toLinear); + const m = MACHADO[deficiency]; + return m.map((row) => toGamma(row[0]! * linear[0]! + row[1]! * linear[1]! + row[2]! * linear[2]!)) as Rgb; +} + +/** sRGB (0-1) to CIE L*a*b* with a D65 white point. */ +export function rgbToLab(rgb: Rgb): Rgb { + const [r, g, b] = rgb.map(toLinear) as Rgb; + const x = (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047; + const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b; + const z = (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883; + const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : ((24389 / 27) * t + 16) / 116); + const [fx, fy, fz] = [f(x), f(y), f(z)]; + return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)]; +} + +const deg = (rad: number) => (rad * 180) / Math.PI; +const rad = (degrees: number) => (degrees * Math.PI) / 180; + +/** CIEDE2000 colour difference between two L*a*b* colours (Sharma, Wu & Dalal 2005). */ +export function deltaE2000(lab1: Rgb, lab2: Rgb): number { + const [l1, a1, b1] = lab1; + const [l2, a2, b2] = lab2; + const c1 = Math.hypot(a1, b1); + const c2 = Math.hypot(a2, b2); + const cBar7 = ((c1 + c2) / 2) ** 7; + const g = 0.5 * (1 - Math.sqrt(cBar7 / (cBar7 + 25 ** 7))); + const a1p = (1 + g) * a1; + const a2p = (1 + g) * a2; + const c1p = Math.hypot(a1p, b1); + const c2p = Math.hypot(a2p, b2); + const hue = (b: number, a: number) => (a === 0 && b === 0 ? 0 : (deg(Math.atan2(b, a)) + 360) % 360); + const h1p = hue(b1, a1p); + const h2p = hue(b2, a2p); + + const dLp = l2 - l1; + const dCp = c2p - c1p; + let dhp = 0; + if (c1p * c2p !== 0) { + dhp = h2p - h1p; + if (dhp > 180) { + dhp -= 360; + } else if (dhp < -180) { + dhp += 360; + } + } + const dHp = 2 * Math.sqrt(c1p * c2p) * Math.sin(rad(dhp / 2)); + + const lBarP = (l1 + l2) / 2; + const cBarP = (c1p + c2p) / 2; + let hBarP = h1p + h2p; + if (c1p * c2p !== 0) { + if (Math.abs(h1p - h2p) <= 180) { + hBarP = (h1p + h2p) / 2; + } else { + hBarP = h1p + h2p < 360 ? (h1p + h2p + 360) / 2 : (h1p + h2p - 360) / 2; + } + } + const t = + 1 - + 0.17 * Math.cos(rad(hBarP - 30)) + + 0.24 * Math.cos(rad(2 * hBarP)) + + 0.32 * Math.cos(rad(3 * hBarP + 6)) - + 0.2 * Math.cos(rad(4 * hBarP - 63)); + const dTheta = 30 * Math.exp(-(((hBarP - 275) / 25) ** 2)); + const cBarP7 = cBarP ** 7; + const rC = 2 * Math.sqrt(cBarP7 / (cBarP7 + 25 ** 7)); + const sL = 1 + (0.015 * (lBarP - 50) ** 2) / Math.sqrt(20 + (lBarP - 50) ** 2); + const sC = 1 + 0.045 * cBarP; + const sH = 1 + 0.015 * cBarP * t; + const rT = -Math.sin(rad(2 * dTheta)) * rC; + return Math.sqrt((dLp / sL) ** 2 + (dCp / sC) ** 2 + (dHp / sH) ** 2 + rT * (dCp / sC) * (dHp / sH)); +} + +/** CIEDE2000 difference between two hex colours, optionally as seen with a deficiency. */ +export function difference(hex1: string, hex2: string, deficiency?: Deficiency): number { + const see = (hex: string) => (deficiency ? simulate(hexToRgb(hex), deficiency) : hexToRgb(hex)); + return deltaE2000(rgbToLab(see(hex1)), rgbToLab(see(hex2))); +} + +/** WCAG 2 relative luminance and contrast ratio. */ +export function contrastRatio(hex1: string, hex2: string): number { + const luminance = (hex: string) => { + const [r, g, b] = hexToRgb(hex).map(toLinear) as Rgb; + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + }; + const [high, low] = [luminance(hex1), luminance(hex2)].sort((a, b) => b - a) as [number, number]; + return (high + 0.05) / (low + 0.05); +} diff --git a/packages/viewer/src/lib/decisions.spec.ts b/packages/viewer/src/lib/decisions.spec.ts new file mode 100644 index 0000000..6390191 --- /dev/null +++ b/packages/viewer/src/lib/decisions.spec.ts @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { applyMove, currentSeat, initGame, legalMoves, type GameState, type Move } from "acquire-engine"; +import { stripSecret } from "acquire-engine/wrapper.js"; +import { adjustShares, canBuy, canDispose, movesFor, nextDefunctChoices } from "./decisions.ts"; + +function playUntil(state: GameState, done: (state: GameState) => boolean): GameState { + for (let step = 0; !done(state); step++) { + assert.ok(!state.ended && step < 3000, "position not reached"); + const moves = legalMoves(state).filter((move) => move.type !== "announce"); + applyMove(state, moves[(step * 7919) % moves.length]!, currentSeat(state)!); + } + return state; +} + +test("the viewer only offers moves when one of its seats must act", () => { + const state = initGame(3, {}, "decisions"); + const acting = state.activeSeat; + const view = stripSecret(state, acting); + assert.deepEqual(movesFor(view, [acting]), legalMoves(state)); + assert.deepEqual(movesFor(stripSecret(state, (acting + 1) % 3), [(acting + 1) % 3]), []); +}); + +test("legal moves computed from a player's stripped view match the full state", () => { + const state = initGame(4, {}, "stripped"); + for (let i = 0; i < 400 && !state.ended; i++) { + const seat = currentSeat(state)!; + const fromView = movesFor(stripSecret(state, seat), [seat]); + assert.deepEqual(fromView, legalMoves(state), `move ${i}, phase ${state.phase}`); + const moves = fromView.filter((move) => move.type !== "announce"); + applyMove(state, moves[(i * 7919) % moves.length]!, seat); + } +}); + +test("buy choices: adding and removing shares follows the engine's legal buys", () => { + const state = playUntil( + initGame(3, {}, "buy-choices"), + (s) => s.phase === "buy" && s.board.some((c) => c !== null && c !== "loose") + ); + const moves = legalMoves(state); + assert.ok(canBuy(moves, {})); + const chain = ( + moves.find((m) => m.type === "buy" && Object.keys(m.shares).length > 0) as Extract + ).shares; + const [first] = Object.keys(chain) as (keyof typeof chain)[]; + const one = adjustShares({}, first!, 1); + assert.ok(canBuy(moves, one)); + assert.deepEqual(adjustShares(one, first!, -1), {}); + assert.equal( + canBuy( + moves, + adjustShares(adjustShares(adjustShares(adjustShares({}, first!, 1), first!, 1), first!, 1), first!, 1) + ), + false, + "never more than 3" + ); +}); + +test("disposal and defunct-order choices are looked up in the engine's legal moves", () => { + const moves: Move[] = [ + { type: "dispose", sell: 0, trade: 0 }, + { type: "dispose", sell: 1, trade: 0 }, + { type: "dispose", sell: 0, trade: 2 }, + { type: "defunctOrder", chains: ["luxor", "festival", "imperial"] }, + { type: "defunctOrder", chains: ["luxor", "imperial", "festival"] }, + ]; + assert.ok(canDispose(moves, 0, 2)); + assert.equal(canDispose(moves, 1, 2), false); + assert.deepEqual(nextDefunctChoices(moves, []), ["luxor"]); + assert.deepEqual(nextDefunctChoices(moves, ["luxor"]), ["festival", "imperial"]); + assert.deepEqual(nextDefunctChoices(moves, ["luxor", "imperial"]), ["festival"]); +}); diff --git a/packages/viewer/src/lib/decisions.ts b/packages/viewer/src/lib/decisions.ts new file mode 100644 index 0000000..5470a39 --- /dev/null +++ b/packages/viewer/src/lib/decisions.ts @@ -0,0 +1,78 @@ +// Which choices the viewer offers. Validity always comes from the engine: these helpers only +// filter and look up engine.legalMoves(), so no rule is re-implemented here. +import { + CHAIN_IDS, + chainSize, + currentSeat, + legalMoves, + placementEffect, + type ChainId, + type GameState, + type Move, + type Shares, + type Tile, +} from "acquire-engine"; +import { chainName, type Lang } from "./format.ts"; + +type MoveOf = Extract; + +/** The legal moves for the viewer, or none when another player must act. */ +export function movesFor(state: GameState, seats: number[]): Move[] { + const seat = currentSeat(state); + return seat !== undefined && seats.includes(seat) ? legalMoves(state) : []; +} + +export function ofType(moves: Move[], type: T): MoveOf[] { + return moves.filter((move): move is MoveOf => move.type === type); +} + +/** What placing `tile` would do, in words (rules.md §5.1). */ +export function describePlacement(state: GameState, tile: Tile, lang: Lang): string { + const effect = placementEffect(state.board, tile); + switch (effect.kind) { + case "loose": + return lang.t("place.loose"); + case "found": + return lang.t("place.found"); + case "grow": + return lang.t("place.joins", { chain: chainName(effect.chain) }); + case "merge": + return lang.t("place.merges", { + chains: lang.list(effect.chains.map((chain) => `${chainName(chain)} (${chainSize(state.board, chain)})`)), + }); + } +} + +function sameShares(a: Partial, b: Partial): boolean { + return CHAIN_IDS.every((chain) => (a[chain] ?? 0) === (b[chain] ?? 0)); +} + +/** Whether buying exactly `shares` is a legal buy move. */ +export function canBuy(moves: Move[], shares: Partial): boolean { + return ofType(moves, "buy").some((move) => sameShares(move.shares, shares)); +} + +/** `shares` with one more (or one fewer) share of `chain`, dropping zero counts. */ +export function adjustShares(shares: Partial, chain: ChainId, delta: number): Partial { + const next = { ...shares, [chain]: (shares[chain] ?? 0) + delta }; + if (next[chain] === 0) { + delete next[chain]; + } + return next; +} + +/** Whether disposing with this sell/trade split is legal. */ +export function canDispose(moves: Move[], sell: number, trade: number): boolean { + return ofType(moves, "dispose").some((move) => move.sell === sell && move.trade === trade); +} + +/** Chains that may come next after `prefix` in some legal defunct order. */ +export function nextDefunctChoices(moves: Move[], prefix: ChainId[]): ChainId[] { + const next = new Set(); + for (const move of ofType(moves, "defunctOrder")) { + if (prefix.every((chain, i) => move.chains[i] === chain) && move.chains.length > prefix.length) { + next.add(move.chains[prefix.length]!); + } + } + return CHAIN_IDS.filter((chain) => next.has(chain)); +} diff --git a/packages/viewer/src/lib/format.ts b/packages/viewer/src/lib/format.ts new file mode 100644 index 0000000..4a3d641 --- /dev/null +++ b/packages/viewer/src/lib/format.ts @@ -0,0 +1,193 @@ +import { + CHAINS, + HIDDEN, + currentSeat, + merger, + tileLabel, + type ChainId, + type GameState, + type LogEntry, +} from "acquire-engine"; +import { formatMoney, joinList, translate, type Locale, type MessageKey, type Params } from "./i18n.ts"; + +/** Text helpers for one language. Components get theirs from the store, so they follow BGS. */ +export interface Lang { + locale: Locale; + t: (key: MessageKey, params?: Params) => string; + list: (items: string[]) => string; + money: (amount: number) => string; + count: (value: number) => string; +} + +export function langFor(locale: Locale): Lang { + const t = (key: MessageKey, params?: Params) => translate(locale, key, params); + return { + locale, + t, + list: (items) => joinList(locale, items), + money: (amount) => (amount === HIDDEN ? t("hidden") : formatMoney(locale, amount)), + count: (value) => (value === HIDDEN ? t("hidden") : String(value)), + }; +} + +/** Chain names are proper nouns and stay in English in every language. */ +export function chainName(chain: ChainId): string { + return CHAINS.find((c) => c.id === chain)!.name; +} + +/** A seat's display name; in fourHands each player has two seats, so the seat number is added. */ +export function seatName(state: GameState, seat: number, lang: Lang): string { + const name = state.seats[seat]?.name ?? `${seat + 1}`; + return state.players === state.seats.length ? name : lang.t("seat.name", { name, seat: seat + 1 }); +} + +/** Who must act now and on what, in plain words. */ +export function pendingDecision(state: GameState, lang: Lang): string { + if (state.ended) { + return lang.t("status.gameOver"); + } + const seat = currentSeat(state); + if (seat === undefined) { + return ""; + } + const name = seatName(state, seat, lang); + switch (state.phase) { + case "place": + return lang.t("status.place", { name }); + case "found": + return lang.t("status.found", { name }); + case "survivor": + return lang.t("status.survivor", { name }); + case "defunctOrder": + return lang.t("status.defunctOrder", { name }); + case "dispose": + return lang.t("status.dispose", { name, chain: chainName(merger(state).current!) }); + case "buy": + return lang.t("status.buy", { name }); + default: + return ""; + } +} + +const BANK_TILE_KEYS = { + loose: "log.bankLoose", + joined: "log.bankJoined", + merger: "log.bankMerger", + removed: "log.bankRemoved", +} as const satisfies Record; + +/** One log line, or undefined for entries that another line already describes. */ +export function describeEntry(state: GameState, entry: LogEntry, lang: Lang): string | undefined { + const { t, list, money } = lang; + const seat = (index: number) => seatName(state, index, lang); + const tiles = (count: number) => t("tiles", { count }); + const shares = (count: number, chain: ChainId) => t("log.shares", { count, chain: chainName(chain) }); + switch (entry.type) { + case "init": + return t("log.init", { count: entry.players }); + case "optionIgnored": { + const count = entry.option === "teamPlay" ? 4 : entry.option === "twoPlayerMode" ? 2 : undefined; + return count !== undefined && entry.reason.startsWith("only applies") + ? t("log.optionIgnored.players", { option: entry.option, count }) + : t("log.optionIgnored.value", { option: entry.option }); + } + case "turnOrder": + return t("log.turnOrder", { + tiles: list(entry.tiles.map((tile, i) => `${seat(i)} ${tileLabel(tile)}`)), + name: seat(entry.first), + }); + case "turn": + return t("log.turn", { name: seat(entry.seat) }); + case "move": { + const name = seat(entry.seat); + switch (entry.move.type) { + case "place": + return t(entry.auto ? "log.placedAuto" : "log.placed", { name, tile: entry.move.tile }); + case "survivor": + return t(entry.auto ? "log.survivorAuto" : "log.survivor", { name, chain: chainName(entry.move.chain) }); + case "defunctOrder": + return t(entry.auto ? "log.orderAuto" : "log.order", { + name, + chains: list(entry.move.chains.map(chainName)), + }); + default: + return undefined; + } + } + case "skipPlace": + return t("log.skipPlace", { name: seat(entry.seat) }); + case "founded": + return t(entry.bonus ? "log.founded" : "log.foundedNoShare", { + name: seat(entry.seat), + chain: chainName(entry.chain), + tiles: tiles(entry.size), + }); + case "grew": + return t("log.grew", { chain: chainName(entry.chain), tiles: tiles(entry.size) }); + case "merger": { + const chains = list( + Object.entries(entry.sizes).map(([chain, size]) => `${chainName(chain as ChainId)} (${size})`) + ); + return entry.byBank + ? t("log.mergerBank", { tile: tileLabel(entry.tile), chains }) + : t("log.merger", { name: seat(entry.seat), tile: tileLabel(entry.tile), chains }); + } + case "mergerPlan": + return t("log.mergerPlan", { survivor: chainName(entry.survivor), chains: list(entry.defunct.map(chainName)) }); + case "bonuses": { + const params = { chain: chainName(entry.chain), size: entry.size }; + const paid = entry.payouts.map(({ seat: s, amount }) => `${seat(s)} ${money(amount)}`); + let line = + paid.length > 0 ? t("log.bonuses", { ...params, payouts: list(paid) }) : t("log.bonusesNobody", params); + if (entry.bank) { + line += + entry.bank.tile === null + ? t("log.bankHeldEmpty") + : t("log.bankHeld", { count: entry.bank.shares, tile: tileLabel(entry.bank.tile) }); + if (entry.bank.amount > 0) { + line += t("log.bankKept", { amount: money(entry.bank.amount) }); + } + } + return line; + } + case "disposed": { + const actions = [ + entry.sold > 0 ? t("log.sold", { shares: shares(entry.sold, entry.chain), amount: money(entry.proceeds) }) : "", + entry.traded > 0 ? t("log.traded", { shares: shares(entry.traded, entry.chain), count: entry.traded / 2 }) : "", + entry.held > 0 ? t("log.kept", { shares: shares(entry.held, entry.chain) }) : "", + ].filter(Boolean); + return actions.length > 0 + ? t("log.disposed", { name: seat(entry.seat), actions: list(actions) }) + : t("log.disposedNothing", { name: seat(entry.seat) }); + } + case "merged": + return t("log.merged", { chain: chainName(entry.survivor), tiles: tiles(entry.size) }); + case "bankTile": + return t(BANK_TILE_KEYS[entry.result], { tile: tileLabel(entry.tile) }); + case "bought": { + const bought = Object.entries(entry.shares).map(([chain, n]) => `${n} ${chainName(chain as ChainId)}`); + return bought.length > 0 + ? t("log.bought", { name: seat(entry.seat), shares: list(bought), cost: money(entry.cost) }) + : t("log.boughtNothing", { name: seat(entry.seat) }); + } + case "discarded": + return t("log.discarded", { name: seat(entry.seat), tiles: list(entry.tiles.map(tileLabel)) }); + case "drew": + return t("log.drew", { name: seat(entry.seat), count: entry.count }); + case "dropped": + return t("log.dropped", { name: seat(entry.seat) }); + case "announced": + return t("log.announced", { name: seat(entry.seat) }); + case "gameEnd": + return t(`log.end.${entry.reason}`); + case "finalSale": + return t("log.finalSale", { + name: seat(entry.seat), + count: entry.shares, + chain: chainName(entry.chain), + amount: money(entry.proceeds), + }); + case "result": + return t("log.result", { results: list(entry.cash.map((cash, s) => `${seat(s)} ${money(cash)}`)) }); + } +} diff --git a/packages/viewer/src/lib/i18n.spec.ts b/packages/viewer/src/lib/i18n.spec.ts new file mode 100644 index 0000000..a551e4f --- /dev/null +++ b/packages/viewer/src/lib/i18n.spec.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CHAINS } from "acquire-engine"; +import { CATALOGS, formatMoney, LOCALES, resolveLocale, translate, type Message } from "./i18n.ts"; +import { en } from "./locales/en.ts"; + +const forms = (message: Message): [string, string][] => + typeof message === "string" ? [["", message]] : Object.entries(message); + +const placeholders = (text: string): Set => new Set([...text.matchAll(/\{(\w+)\}/g)].map((m) => m[1]!)); + +test("every locale has exactly the English keys", () => { + const keys = Object.keys(en).sort(); + for (const locale of LOCALES) { + assert.deepEqual(Object.keys(CATALOGS[locale]).sort(), keys, locale); + } +}); + +test("every translation keeps the English placeholders", () => { + for (const locale of LOCALES) { + for (const [key, english] of Object.entries(en)) { + const allowed = new Set(forms(english).flatMap(([, text]) => [...placeholders(text)])); + const required = placeholders(forms(english).find(([form]) => form === "other" || form === "")![1]); + for (const [form, text] of forms(CATALOGS[locale][key as keyof typeof en])) { + const found = placeholders(text); + for (const name of found) { + assert.ok(allowed.has(name), `${locale} ${key} ${form}: unknown {${name}}`); + } + for (const name of required) { + // A singular form may spell out the number ("a tile") instead of using {count}. + if (name === "count" && form !== "other") { + continue; + } + assert.ok(found.has(name), `${locale} ${key} ${form}: missing {${name}}`); + } + } + } + } +}); + +test("plural messages use exactly the locale's plural categories", () => { + for (const locale of LOCALES) { + const categories = new Intl.PluralRules(locale).resolvedOptions().pluralCategories.slice().sort(); + for (const [key, message] of Object.entries(CATALOGS[locale])) { + if (typeof message === "string") { + assert.equal(typeof en[key as keyof typeof en], "string", `${locale} ${key} should be plural`); + continue; + } + assert.deepEqual(Object.keys(message).sort(), categories, `${locale} ${key}`); + } + } +}); + +test("plural forms follow the locale's rules", () => { + assert.equal(translate("en", "tiles", { count: 1 }), "1 tile"); + assert.equal(translate("en", "tiles", { count: 2 }), "2 tiles"); + assert.equal(translate("pl", "tiles", { count: 3 }), translate("pl", "tiles", { count: 23 }).replace("23", "3")); + assert.notEqual( + translate("pl", "tiles", { count: 5 }).replace("5", "#"), + translate("pl", "tiles", { count: 3 }).replace("3", "#") + ); + assert.notEqual( + translate("ru", "tiles", { count: 1 }).replace("1", "#"), + translate("ru", "tiles", { count: 5 }).replace("5", "#") + ); +}); + +test("chain names and tile coordinates are never translated", () => { + for (const locale of LOCALES) { + for (const chain of CHAINS) { + const text = translate(locale, "board.chain", { tile: "5C", chain: chain.name }); + assert.ok(text.includes(chain.name) && text.includes("5C"), `${locale}: ${text}`); + } + } +}); + +test("money is in dollars with Latin digits in every locale", () => { + for (const locale of LOCALES) { + assert.match(formatMoney(locale, 12000), /^\$12\D?000$/, locale); + } +}); + +test("BGS locale tags resolve to a bundled catalogue, else English", () => { + assert.equal(resolveLocale("de"), "de"); + assert.equal(resolveLocale("de-AT"), "de"); + assert.equal(resolveLocale("pt-BR"), "pt-BR"); + assert.equal(resolveLocale("pt-PT"), "pt-BR"); + assert.equal(resolveLocale("zh-TW"), "zh-TW"); + assert.equal(resolveLocale("zh-Hant-HK"), "zh-TW"); + assert.equal(resolveLocale("zh"), "zh-CN"); + assert.equal(resolveLocale("ZH-cn"), "zh-CN"); + assert.equal(resolveLocale("ja"), "en"); + assert.equal(resolveLocale(undefined), "en"); +}); diff --git a/packages/viewer/src/lib/i18n.ts b/packages/viewer/src/lib/i18n.ts new file mode 100644 index 0000000..ad4ea68 --- /dev/null +++ b/packages/viewer/src/lib/i18n.ts @@ -0,0 +1,117 @@ +// Viewer translations, bundled with the viewer. Follows BGS's preferences.locale live and falls +// back to English. Chain names and tile coordinates are never translated. +import { da } from "./locales/da.ts"; +import { de } from "./locales/de.ts"; +import { el } from "./locales/el.ts"; +import { en } from "./locales/en.ts"; +import { fa } from "./locales/fa.ts"; +import { fr } from "./locales/fr.ts"; +import { hi } from "./locales/hi.ts"; +import { it } from "./locales/it.ts"; +import { ko } from "./locales/ko.ts"; +import { nl } from "./locales/nl.ts"; +import { pl } from "./locales/pl.ts"; +import { ptBR } from "./locales/pt-BR.ts"; +import { ro } from "./locales/ro.ts"; +import { ru } from "./locales/ru.ts"; +import { vi } from "./locales/vi.ts"; +import { zhCN } from "./locales/zh-CN.ts"; +import { zhTW } from "./locales/zh-TW.ts"; + +export type MessageKey = keyof typeof en; +export type PluralMessage = Partial> & { other: string }; +export type Message = string | PluralMessage; +export type Catalog = Record; + +// The BGS interface languages (packages/models/locale.ts in the BGS repository). +export const LOCALES = [ + "en", + "de", + "fr", + "pl", + "ro", + "el", + "hi", + "ru", + "da", + "pt-BR", + "ko", + "zh-TW", + "zh-CN", + "vi", + "it", + "nl", + "fa", +] as const; +export type Locale = (typeof LOCALES)[number]; + +export const CATALOGS: Record = { + en, + de, + fr, + pl, + ro, + el, + hi, + ru, + da, + "pt-BR": ptBR, + ko, + "zh-TW": zhTW, + "zh-CN": zhCN, + vi, + it, + nl, + fa, +}; + +/** BGS sends a BCP-47 tag; match it exactly, then by language, else English. */ +export function resolveLocale(tag: unknown): Locale { + if (typeof tag !== "string") { + return "en"; + } + const exact = LOCALES.find((locale) => locale.toLowerCase() === tag.toLowerCase()); + if (exact) { + return exact; + } + const language = tag.split("-")[0]!.toLowerCase(); + if (language === "zh") { + return /hant|tw|hk|mo/i.test(tag) ? "zh-TW" : "zh-CN"; + } + if (language === "pt") { + return "pt-BR"; + } + return LOCALES.find((locale) => locale === language) ?? "en"; +} + +/** Persian is written right to left; the board and its coordinates stay left to right. */ +export function isRightToLeft(locale: Locale): boolean { + return locale === "fa"; +} + +export type Params = Record; + +export function translate(locale: Locale, key: MessageKey, params: Params = {}): string { + const message: Message = CATALOGS[locale][key] ?? en[key]; + let template: string; + if (typeof message === "string") { + template = message; + } else { + const count = Number(params.count ?? 0); + const category = new Intl.PluralRules(locale).select(count); + template = message[category] ?? message.other; + } + return template.replace(/\{(\w+)\}/g, (match, name: string) => + params[name] === undefined ? match : String(params[name]) + ); +} + +/** "A, B and C" in the locale's own words. */ +export function joinList(locale: Locale, items: string[]): string { + return new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(items); +} + +/** Dollars with the locale's digit grouping. Digits stay Latin to match coordinates and counts. */ +export function formatMoney(locale: Locale, amount: number): string { + return `$${new Intl.NumberFormat(locale, { numberingSystem: "latn" }).format(amount)}`; +} diff --git a/packages/viewer/src/lib/locales/da.ts b/packages/viewer/src/lib/locales/da.ts new file mode 100644 index 0000000..ce820f1 --- /dev/null +++ b/packages/viewer/src/lib/locales/da.ts @@ -0,0 +1,168 @@ +import type { Catalog } from "../i18n.ts"; + +export const da: Catalog = { + loading: "Indlæser spillet…", + "status.place": "{name} skal lægge en brik", + "status.found": "{name} skal navngive en ny kæde", + "status.survivor": "{name} skal vælge, hvilken kæde der overlever fusionen", + "status.defunctOrder": "{name} skal vælge rækkefølgen af de opslugte kæder", + "status.dispose": "{name} skal sælge, bytte eller beholde {chain}-aktier", + "status.buy": "{name} skal købe aktier", + "status.gameOver": "Spillet er slut", + "status.yourDecision": "din beslutning", + "status.announced": "Spillets afslutning er meldt; spillet slutter efter denne tur.", + "status.replay": "Genafspilning: tur {turn}", + "status.replayNote": "Du ser en tidligere stilling. Brikker på hånden vises ikke.", + "panel.label": "Din beslutning", + "panel.sending": "Sender…", + "announce.ask": "Afslut spillet efter denne tur? Det kan ikke fortrydes.", + "announce.confirm": "Meld afslutning", + "announce.cancel": "Spil videre", + "announce.open": "Meld afslutning…", + "place.effect": "{tile}: {effect}.", + "place.loose": "ligger alene (ingen nabobrikker)", + "place.found": "grundlægger en ny kæde", + "place.joins": "udvider {chain}", + "place.merges": "fusionerer {chains}", + "place.button": "Læg {tile}", + "place.another": "Vælg en anden", + "place.choose": "Vælg en brik fra din hånd.", + "place.none": "Ingen af dine brikker kan lægges.", + "place.pass": "Fortsæt uden at lægge", + "found.prompt": "Navngiv den nye kæde. Du får én gratis aktie.", + "survivor.prompt": "Disse kæder er lige store og størst. Vælg, hvilken der overlever.", + tiles: { one: "{count} brik", other: "{count} brikker" }, + "order.prompt": + "{survivor} overlever. Nogle opslugte kæder er lige store: vælg rækkefølgen, de afregnes i, fra første til sidste.", + "order.confirm": "Bekræft rækkefølge", + "order.reset": "Start forfra", + "dispose.takenOver": "{defunct} bliver opslugt af {survivor}.", + "dispose.holding": { one: "Du har {count} {chain}-aktie.", other: "Du har {count} {chain}-aktier." }, + "dispose.sell": "Sælg til {price}", + "dispose.trade": "Byt 2 for 1", + "dispose.keep": "Behold", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "værdiløse, medmindre {chain} grundlægges igen", + "dispose.sellFewer": "Sælg én færre", + "dispose.sellMore": "Sælg én mere", + "dispose.tradeFewer": "Byt to færre", + "dispose.tradeMore": "Byt to flere", + "dispose.confirm": "Bekræft", + "buy.prompt": "Køb op til 3 aktier. Priserne ligger fast i denne tur.", + "buy.chain": "Kæde", + "buy.price": "Pris", + "buy.bank": "Bank", + "buy.buy": "Køb", + "buy.fewer": "Én {chain}-aktie færre", + "buy.more": "Én {chain}-aktie mere", + "buy.total": "{count} af 3 aktier · pris {cost} · tilbage {cash}", + "buy.nothing": "Køb intet og afslut turen", + "buy.confirm": "Køb for {cost} og afslut turen", + "board.label": "Spilleplade", + "board.empty": "{tile} tom", + "board.loose": "{tile} enlig brik", + "board.chain": "{tile} {chain}", + "board.place": "Læg {tile}", + "hand.yours": "Dine brikker", + "hand.seat": "Brikker, plads {seat}", + "hand.of": "{name}s brikker", + "hand.none": "Ingen brikker", + "hand.dead": "død: ville fusionere sikre kæder", + "hand.eighth": "kan ikke grundlægge en 8. kæde", + "chains.label": "Hotelkæder", + "chains.title": "Kæder", + "chains.chain": "Kæde", + "chains.size": "Størrelse", + "chains.price": "Pris", + "chains.bank": "Bank", + "chains.yours": "Dine", + "chains.notOnBoard": "ikke på pladen", + "chains.safe": "sikker", + "prices.label": "Pristabel", + "prices.show": "Pristabel", + "prices.hide": "Skjul pristabel", + "prices.minor": "Små kæder:", + "prices.medium": "Mellemstore kæder:", + "prices.major": "Store kæder:", + "prices.price": "Pris", + "prices.first": "1.", + "prices.second": "2.", + "prices.note": "Størrelse er brikker pr. kæde. En kædes mærke viser, hvor den står nu.", + "players.label": "Spillere", + "players.title": "Spillere", + "players.player": "Spiller", + "players.cash": "Penge", + "players.stock": "Aktier", + "players.tiles": "Brikker", + "players.acting": "handler nu", + "players.you": "dig", + "players.turn": "tur", + "players.left": "forladt", + "players.none": "ingen", + hidden: "skjult", + "seat.name": "{name} (plads {seat})", + "log.label": "Spillets log", + "log.title": "Log", + "log.recent": "Vis kun de seneste linjer", + "log.all": { one: "Vis hele loggen ({count} mere)", other: "Vis hele loggen ({count} mere)" }, + "log.init": { one: "Nyt spil for {count} spiller", other: "Nyt spil for {count} spillere" }, + "log.optionIgnored.players": { + one: "Indstillingen {option} blev ignoreret: den gælder kun med præcis {count} spiller", + other: "Indstillingen {option} blev ignoreret: den gælder kun med præcis {count} spillere", + }, + "log.optionIgnored.value": "Indstillingen {option} blev ignoreret: ukendt værdi", + "log.turnOrder": "Brikker til turrækkefølgen: {tiles}. {name} begynder", + "log.turn": "{name}s tur", + "log.placed": "{name} lægger {tile}", + "log.placedAuto": "{name} lægger {tile} (automatisk)", + "log.survivor": "{name} vælger, at {chain} overlever", + "log.survivorAuto": "{name} vælger, at {chain} overlever (automatisk)", + "log.order": "{name} vælger rækkefølgen {chains}", + "log.orderAuto": "{name} vælger rækkefølgen {chains} (automatisk)", + "log.skipPlace": "{name} lægger ingen brik", + "log.founded": "{name} grundlægger {chain} ({tiles}) og får en gratis aktie", + "log.foundedNoShare": "{name} grundlægger {chain} ({tiles}); der var ingen gratis aktie tilbage", + "log.grew": "{chain} vokser til {tiles}", + "log.merger": "{name}s {tile} fusionerer {chains}", + "log.mergerBank": "Bankens brik {tile} fusionerer {chains}", + "log.mergerPlan": "{survivor} overlever og overtager {chains}", + "log.bonuses": "Bonusser for {chain} ved størrelse {size}: {payouts}", + "log.bonusesNobody": "Bonusser for {chain} ved størrelse {size}: ingen udbetaling", + "log.bankHeld": { + one: "; banken havde {count} aktie (trak {tile})", + other: "; banken havde {count} aktier (trak {tile})", + }, + "log.bankHeldEmpty": "; banken havde 0 aktier (bunken er tom)", + "log.bankKept": " og beholdt {amount}", + "log.shares": { one: "{count} {chain}-aktie", other: "{count} {chain}-aktier" }, + "log.sold": "sælger {shares} for {amount}", + "log.traded": "bytter {shares} til {count} i den overlevende kæde", + "log.kept": "beholder {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} havde intet at afregne", + "log.merged": "{chain} har nu {tiles}", + "log.bankLoose": "Bankens brik {tile} ligger alene", + "log.bankJoined": "Bankens brik {tile} udvider en kæde", + "log.bankMerger": "Bankens brik {tile} udløser en fusion", + "log.bankRemoved": "Bankens brik {tile} kan ikke lægges og fjernes", + "log.bought": "{name} køber {shares} for {cost}", + "log.boughtNothing": "{name} køber ingen aktier", + "log.discarded": "{name} smider ubrugelige brikker: {tiles}", + "log.drew": { one: "{name} trækker en brik", other: "{name} trækker {count} brikker" }, + "log.dropped": "{name} har forladt spillet", + "log.announced": "{name} melder spillets afslutning", + "log.end.announced": "Spillet er slut: afslutningen blev meldt", + "log.end.condition": "Spillet er slut: en slutbetingelse er opfyldt", + "log.end.stall": "Spillet er slut: en hel runde gik uden at nogen lagde en brik", + "log.end.dropped": "Spillet er slut: kun én spiller var tilbage", + "log.finalSale": "{name} sælger {count} {chain} for {amount}", + "log.result": "Penge til slut: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Besked", + "chat.placeholder": "Besked…", + "chat.send": "Send", + "chat.sending": "Sender…", + "chat.empty": "Ingen beskeder endnu.", + "chat.edited": "redigeret", +}; diff --git a/packages/viewer/src/lib/locales/de.ts b/packages/viewer/src/lib/locales/de.ts new file mode 100644 index 0000000..e876792 --- /dev/null +++ b/packages/viewer/src/lib/locales/de.ts @@ -0,0 +1,168 @@ +import type { Catalog } from "../i18n.ts"; + +export const de: Catalog = { + loading: "Spiel wird geladen…", + "status.place": "{name} legt ein Plättchen", + "status.found": "{name} benennt eine neue Kette", + "status.survivor": "{name} wählt, welche Kette die Fusion übersteht", + "status.defunctOrder": "{name} wählt die Reihenfolge der übernommenen Ketten", + "status.dispose": "{name} verkauft, tauscht oder behält {chain}-Aktien", + "status.buy": "{name} kauft Aktien", + "status.gameOver": "Spielende", + "status.yourDecision": "deine Entscheidung", + "status.announced": "Das Spielende wurde angekündigt; das Spiel endet nach diesem Zug.", + "status.replay": "Wiederholung: Zug {turn}", + "status.replayNote": "Du siehst eine frühere Stellung. Plättchen auf der Hand werden nicht gezeigt.", + "panel.label": "Deine Entscheidung", + "panel.sending": "Wird gesendet…", + "announce.ask": "Das Spiel nach diesem Zug beenden? Das kann nicht rückgängig gemacht werden.", + "announce.confirm": "Spielende ankündigen", + "announce.cancel": "Weiterspielen", + "announce.open": "Spielende ankündigen…", + "place.effect": "{tile}: {effect}.", + "place.loose": "bleibt einzeln liegen (keine Nachbarplättchen)", + "place.found": "gründet eine neue Kette", + "place.joins": "erweitert {chain}", + "place.merges": "fusioniert {chains}", + "place.button": "{tile} legen", + "place.another": "Anderes wählen", + "place.choose": "Wähle ein Plättchen von deiner Hand.", + "place.none": "Keines deiner Plättchen kann gelegt werden.", + "place.pass": "Ohne Legen weiter", + "found.prompt": "Benenne die neue Kette. Du erhältst eine Gratisaktie.", + "survivor.prompt": "Diese Ketten sind gleich groß und die größten. Wähle, welche bestehen bleibt.", + tiles: { one: "{count} Plättchen", other: "{count} Plättchen" }, + "order.prompt": + "{survivor} bleibt bestehen. Einige übernommene Ketten sind gleich groß: Wähle die Reihenfolge, in der sie abgerechnet werden, von der ersten bis zur letzten.", + "order.confirm": "Reihenfolge bestätigen", + "order.reset": "Neu beginnen", + "dispose.takenOver": "{defunct} wird von {survivor} übernommen.", + "dispose.holding": { one: "Du besitzt {count} {chain}-Aktie.", other: "Du besitzt {count} {chain}-Aktien." }, + "dispose.sell": "Verkaufen zu {price}", + "dispose.trade": "2 gegen 1 tauschen", + "dispose.keep": "Behalten", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "wertlos, außer {chain} wird neu gegründet", + "dispose.sellFewer": "Eine weniger verkaufen", + "dispose.sellMore": "Eine mehr verkaufen", + "dispose.tradeFewer": "Zwei weniger tauschen", + "dispose.tradeMore": "Zwei mehr tauschen", + "dispose.confirm": "Bestätigen", + "buy.prompt": "Kaufe bis zu 3 Aktien. Die Preise gelten für den ganzen Zug.", + "buy.chain": "Kette", + "buy.price": "Preis", + "buy.bank": "Bank", + "buy.buy": "Kaufen", + "buy.fewer": "Eine {chain}-Aktie weniger kaufen", + "buy.more": "Eine {chain}-Aktie mehr kaufen", + "buy.total": "{count} von 3 Aktien · Kosten {cost} · Restgeld {cash}", + "buy.nothing": "Nichts kaufen und Zug beenden", + "buy.confirm": "Für {cost} kaufen und Zug beenden", + "board.label": "Spielplan", + "board.empty": "{tile} leer", + "board.loose": "{tile} einzelnes Plättchen", + "board.chain": "{tile} {chain}", + "board.place": "{tile} legen", + "hand.yours": "Deine Plättchen", + "hand.seat": "Plättchen, Platz {seat}", + "hand.of": "Plättchen von {name}", + "hand.none": "Keine Plättchen", + "hand.dead": "tot: würde sichere Ketten fusionieren", + "hand.eighth": "keine 8. Kette möglich", + "chains.label": "Hotelketten", + "chains.title": "Ketten", + "chains.chain": "Kette", + "chains.size": "Größe", + "chains.price": "Preis", + "chains.bank": "Bank", + "chains.yours": "Deine", + "chains.notOnBoard": "nicht auf dem Plan", + "chains.safe": "sicher", + "prices.label": "Preistabelle", + "prices.show": "Preistabelle", + "prices.hide": "Preistabelle ausblenden", + "prices.minor": "Kleine Ketten:", + "prices.medium": "Mittlere Ketten:", + "prices.major": "Große Ketten:", + "prices.price": "Preis", + "prices.first": "1.", + "prices.second": "2.", + "prices.note": "Größen sind Plättchen pro Kette. Das Zeichen einer Kette zeigt, wo sie gerade steht.", + "players.label": "Spieler", + "players.title": "Spieler", + "players.player": "Spieler", + "players.cash": "Geld", + "players.stock": "Aktien", + "players.tiles": "Plättchen", + "players.acting": "ist am Zug", + "players.you": "du", + "players.turn": "am Zug", + "players.left": "ausgeschieden", + "players.none": "keine", + hidden: "verdeckt", + "seat.name": "{name} (Platz {seat})", + "log.label": "Spielprotokoll", + "log.title": "Protokoll", + "log.recent": "Nur die letzten Zeilen zeigen", + "log.all": { one: "Ganzes Protokoll zeigen ({count} weitere)", other: "Ganzes Protokoll zeigen ({count} weitere)" }, + "log.init": { one: "Neues Spiel für {count} Spieler", other: "Neues Spiel für {count} Spieler" }, + "log.optionIgnored.players": { + one: "Option {option} wurde ignoriert: Sie gilt nur bei genau {count} Spieler", + other: "Option {option} wurde ignoriert: Sie gilt nur bei genau {count} Spielern", + }, + "log.optionIgnored.value": "Option {option} wurde ignoriert: unbekannter Wert", + "log.turnOrder": "Plättchen für die Reihenfolge: {tiles}. {name} beginnt", + "log.turn": "{name} ist am Zug", + "log.placed": "{name} legt {tile}", + "log.placedAuto": "{name} legt {tile} (automatisch)", + "log.survivor": "{name} wählt {chain} als bestehende Kette", + "log.survivorAuto": "{name} wählt {chain} als bestehende Kette (automatisch)", + "log.order": "{name} wählt die Reihenfolge {chains}", + "log.orderAuto": "{name} wählt die Reihenfolge {chains} (automatisch)", + "log.skipPlace": "{name} legt kein Plättchen", + "log.founded": "{name} gründet {chain} ({tiles}) und erhält eine Gratisaktie", + "log.foundedNoShare": "{name} gründet {chain} ({tiles}); keine Gratisaktie mehr übrig", + "log.grew": "{chain} wächst auf {tiles}", + "log.merger": "{tile} von {name} fusioniert {chains}", + "log.mergerBank": "Das Bankplättchen {tile} fusioniert {chains}", + "log.mergerPlan": "{survivor} bleibt bestehen und übernimmt {chains}", + "log.bonuses": "Prämien für {chain} bei Größe {size}: {payouts}", + "log.bonusesNobody": "Prämien für {chain} bei Größe {size}: niemand erhält etwas", + "log.bankHeld": { + one: "; die Bank hielt {count} Aktie (zog {tile})", + other: "; die Bank hielt {count} Aktien (zog {tile})", + }, + "log.bankHeldEmpty": "; die Bank hielt 0 Aktien (Vorrat leer)", + "log.bankKept": " und behielt {amount}", + "log.shares": { one: "{count} {chain}-Aktie", other: "{count} {chain}-Aktien" }, + "log.sold": "verkauft {shares} für {amount}", + "log.traded": "tauscht {shares} gegen {count} der bestehenden Kette", + "log.kept": "behält {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} hatte nichts abzurechnen", + "log.merged": "{chain} hat jetzt {tiles}", + "log.bankLoose": "Das Bankplättchen {tile} bleibt einzeln liegen", + "log.bankJoined": "Das Bankplättchen {tile} erweitert eine Kette", + "log.bankMerger": "Das Bankplättchen {tile} löst eine Fusion aus", + "log.bankRemoved": "Das Bankplättchen {tile} ist nicht spielbar und wird entfernt", + "log.bought": "{name} kauft {shares} für {cost}", + "log.boughtNothing": "{name} kauft keine Aktien", + "log.discarded": "{name} wirft unspielbare Plättchen ab: {tiles}", + "log.drew": { one: "{name} zieht ein Plättchen", other: "{name} zieht {count} Plättchen" }, + "log.dropped": "{name} hat das Spiel verlassen", + "log.announced": "{name} kündigt das Spielende an", + "log.end.announced": "Spielende: Das Ende wurde angekündigt", + "log.end.condition": "Spielende: Eine Endbedingung ist erfüllt", + "log.end.stall": "Spielende: Eine ganze Runde lang wurde kein Plättchen gelegt", + "log.end.dropped": "Spielende: Nur noch ein Spieler ist übrig", + "log.finalSale": "{name} verkauft {count} {chain} für {amount}", + "log.result": "Endstand: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Nachricht", + "chat.placeholder": "Nachricht…", + "chat.send": "Senden", + "chat.sending": "Wird gesendet…", + "chat.empty": "Noch keine Nachrichten.", + "chat.edited": "bearbeitet", +}; diff --git a/packages/viewer/src/lib/locales/el.ts b/packages/viewer/src/lib/locales/el.ts new file mode 100644 index 0000000..47f6276 --- /dev/null +++ b/packages/viewer/src/lib/locales/el.ts @@ -0,0 +1,168 @@ +import type { Catalog } from "../i18n.ts"; + +export const el: Catalog = { + loading: "Φόρτωση παιχνιδιού…", + "status.place": "{name}: τοποθέτηση πλακιδίου", + "status.found": "{name}: ονομασία νέας αλυσίδας", + "status.survivor": "{name}: επιλογή αλυσίδας που επιβιώνει από τη συγχώνευση", + "status.defunctOrder": "{name}: επιλογή σειράς των αλυσίδων που απορροφώνται", + "status.dispose": "{name}: πώληση, ανταλλαγή ή διατήρηση μετοχών {chain}", + "status.buy": "{name}: αγορά μετοχών", + "status.gameOver": "Τέλος παιχνιδιού", + "status.yourDecision": "η απόφασή σου", + "status.announced": "Ανακοινώθηκε το τέλος του παιχνιδιού· τελειώνει μετά από αυτόν τον γύρο.", + "status.replay": "Επανάληψη: γύρος {turn}", + "status.replayNote": "Βλέπεις μια παλαιότερη θέση. Τα πλακίδια στο χέρι δεν εμφανίζονται.", + "panel.label": "Η απόφασή σου", + "panel.sending": "Αποστολή…", + "announce.ask": "Να τελειώσει το παιχνίδι μετά από αυτόν τον γύρο; Δεν αναιρείται.", + "announce.confirm": "Ανακοίνωση τέλους", + "announce.cancel": "Συνέχεια παιχνιδιού", + "announce.open": "Ανακοίνωση τέλους…", + "place.effect": "{tile}: {effect}.", + "place.loose": "μένει μεμονωμένο (χωρίς γειτονικά πλακίδια)", + "place.found": "ιδρύει νέα αλυσίδα", + "place.joins": "επεκτείνει την {chain}", + "place.merges": "συγχωνεύει {chains}", + "place.button": "Τοποθέτηση {tile}", + "place.another": "Άλλη επιλογή", + "place.choose": "Διάλεξε ένα πλακίδιο από το χέρι σου.", + "place.none": "Κανένα από τα πλακίδιά σου δεν μπορεί να τοποθετηθεί.", + "place.pass": "Συνέχεια χωρίς τοποθέτηση", + "found.prompt": "Ονόμασε τη νέα αλυσίδα. Παίρνεις μία δωρεάν μετοχή.", + "survivor.prompt": "Αυτές οι αλυσίδες είναι ισόπαλες ως οι μεγαλύτερες. Διάλεξε ποια επιβιώνει.", + tiles: { one: "{count} πλακίδιο", other: "{count} πλακίδια" }, + "order.prompt": + "Η {survivor} επιβιώνει. Ορισμένες αλυσίδες που απορροφώνται έχουν το ίδιο μέγεθος: διάλεξε τη σειρά εκκαθάρισής τους, από την πρώτη ως την τελευταία.", + "order.confirm": "Επιβεβαίωση σειράς", + "order.reset": "Από την αρχή", + "dispose.takenOver": "Η {defunct} απορροφάται από την {survivor}.", + "dispose.holding": { one: "Έχεις {count} μετοχή {chain}.", other: "Έχεις {count} μετοχές {chain}." }, + "dispose.sell": "Πώληση προς {price}", + "dispose.trade": "Ανταλλαγή 2 προς 1", + "dispose.keep": "Διατήρηση", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "χωρίς αξία, εκτός αν η {chain} ιδρυθεί ξανά", + "dispose.sellFewer": "Πώληση μίας λιγότερης", + "dispose.sellMore": "Πώληση μίας ακόμη", + "dispose.tradeFewer": "Ανταλλαγή δύο λιγότερων", + "dispose.tradeMore": "Ανταλλαγή δύο ακόμη", + "dispose.confirm": "Επιβεβαίωση", + "buy.prompt": "Αγόρασε έως 3 μετοχές. Οι τιμές μένουν σταθερές σε αυτόν τον γύρο.", + "buy.chain": "Αλυσίδα", + "buy.price": "Τιμή", + "buy.bank": "Τράπεζα", + "buy.buy": "Αγορά", + "buy.fewer": "Μία μετοχή {chain} λιγότερη", + "buy.more": "Μία μετοχή {chain} ακόμη", + "buy.total": "{count} από 3 μετοχές · κόστος {cost} · υπόλοιπο {cash}", + "buy.nothing": "Καμία αγορά και τέλος γύρου", + "buy.confirm": "Αγορά για {cost} και τέλος γύρου", + "board.label": "Ταμπλό", + "board.empty": "{tile} κενό", + "board.loose": "{tile} μεμονωμένο πλακίδιο", + "board.chain": "{tile} {chain}", + "board.place": "Τοποθέτηση {tile}", + "hand.yours": "Τα πλακίδιά σου", + "hand.seat": "Πλακίδια, θέση {seat}", + "hand.of": "Πλακίδια του/της {name}", + "hand.none": "Κανένα πλακίδιο", + "hand.dead": "νεκρό: θα συγχώνευε ασφαλείς αλυσίδες", + "hand.eighth": "δεν ιδρύεται 8η αλυσίδα", + "chains.label": "Αλυσίδες ξενοδοχείων", + "chains.title": "Αλυσίδες", + "chains.chain": "Αλυσίδα", + "chains.size": "Μέγεθος", + "chains.price": "Τιμή", + "chains.bank": "Τράπεζα", + "chains.yours": "Δικές σου", + "chains.notOnBoard": "εκτός ταμπλό", + "chains.safe": "ασφαλής", + "prices.label": "Πίνακας τιμών", + "prices.show": "Πίνακας τιμών", + "prices.hide": "Απόκρυψη πίνακα τιμών", + "prices.minor": "Μικρές αλυσίδες:", + "prices.medium": "Μεσαίες αλυσίδες:", + "prices.major": "Μεγάλες αλυσίδες:", + "prices.price": "Τιμή", + "prices.first": "1ο", + "prices.second": "2ο", + "prices.note": "Το μέγεθος είναι πλακίδια ανά αλυσίδα. Ο δείκτης μιας αλυσίδας δείχνει πού βρίσκεται τώρα.", + "players.label": "Παίκτες", + "players.title": "Παίκτες", + "players.player": "Παίκτης", + "players.cash": "Μετρητά", + "players.stock": "Μετοχές", + "players.tiles": "Πλακίδια", + "players.acting": "παίζει τώρα", + "players.you": "εσύ", + "players.turn": "σειρά", + "players.left": "αποχώρησε", + "players.none": "καμία", + hidden: "κρυφό", + "seat.name": "{name} (θέση {seat})", + "log.label": "Ημερολόγιο παιχνιδιού", + "log.title": "Ημερολόγιο", + "log.recent": "Μόνο οι τελευταίες γραμμές", + "log.all": { one: "Όλο το ημερολόγιο ({count} ακόμη)", other: "Όλο το ημερολόγιο ({count} ακόμη)" }, + "log.init": { one: "Νέο παιχνίδι για {count} παίκτη", other: "Νέο παιχνίδι για {count} παίκτες" }, + "log.optionIgnored.players": { + one: "Η επιλογή {option} αγνοήθηκε: ισχύει μόνο με ακριβώς {count} παίκτη", + other: "Η επιλογή {option} αγνοήθηκε: ισχύει μόνο με ακριβώς {count} παίκτες", + }, + "log.optionIgnored.value": "Η επιλογή {option} αγνοήθηκε: άγνωστη τιμή", + "log.turnOrder": "Πλακίδια σειράς: {tiles}. Ξεκινά ο/η {name}", + "log.turn": "Σειρά: {name}", + "log.placed": "{name}: τοποθετεί {tile}", + "log.placedAuto": "{name}: τοποθετεί {tile} (αυτόματα)", + "log.survivor": "{name}: επιλέγει να επιβιώσει η {chain}", + "log.survivorAuto": "{name}: επιλέγει να επιβιώσει η {chain} (αυτόματα)", + "log.order": "{name}: επιλέγει τη σειρά {chains}", + "log.orderAuto": "{name}: επιλέγει τη σειρά {chains} (αυτόματα)", + "log.skipPlace": "{name}: δεν τοποθετεί πλακίδιο", + "log.founded": "{name}: ιδρύει την {chain} ({tiles}) και παίρνει δωρεάν μετοχή", + "log.foundedNoShare": "{name}: ιδρύει την {chain} ({tiles})· δεν έμεινε δωρεάν μετοχή", + "log.grew": "Η {chain} μεγαλώνει σε {tiles}", + "log.merger": "Το {tile} του/της {name} συγχωνεύει {chains}", + "log.mergerBank": "Το πλακίδιο {tile} της τράπεζας συγχωνεύει {chains}", + "log.mergerPlan": "Η {survivor} επιβιώνει και απορροφά {chains}", + "log.bonuses": "Μπόνους {chain} στο μέγεθος {size}: {payouts}", + "log.bonusesNobody": "Μπόνους {chain} στο μέγεθος {size}: δεν πληρώθηκε κανείς", + "log.bankHeld": { + one: "· η τράπεζα είχε {count} μετοχή (τράβηξε {tile})", + other: "· η τράπεζα είχε {count} μετοχές (τράβηξε {tile})", + }, + "log.bankHeldEmpty": "· η τράπεζα είχε 0 μετοχές (άδεια δεξαμενή)", + "log.bankKept": " και κράτησε {amount}", + "log.shares": { one: "{count} μετοχή {chain}", other: "{count} μετοχές {chain}" }, + "log.sold": "πουλά {shares} για {amount}", + "log.traded": "ανταλλάσσει {shares} με {count} της επιζώσας αλυσίδας", + "log.kept": "κρατά {shares}", + "log.disposed": "{name}: {actions}", + "log.disposedNothing": "{name}: τίποτα για εκκαθάριση", + "log.merged": "Η {chain} έχει τώρα {tiles}", + "log.bankLoose": "Το πλακίδιο {tile} της τράπεζας μένει μεμονωμένο", + "log.bankJoined": "Το πλακίδιο {tile} της τράπεζας επεκτείνει μια αλυσίδα", + "log.bankMerger": "Το πλακίδιο {tile} της τράπεζας προκαλεί συγχώνευση", + "log.bankRemoved": "Το πλακίδιο {tile} της τράπεζας δεν παίζεται και αφαιρείται", + "log.bought": "{name}: αγοράζει {shares} για {cost}", + "log.boughtNothing": "{name}: δεν αγοράζει μετοχές", + "log.discarded": "{name}: πετά μη παιζόμενα πλακίδια: {tiles}", + "log.drew": { one: "{name}: τραβά ένα πλακίδιο", other: "{name}: τραβά {count} πλακίδια" }, + "log.dropped": "{name}: αποχώρησε από το παιχνίδι", + "log.announced": "{name}: ανακοινώνει το τέλος του παιχνιδιού", + "log.end.announced": "Τέλος παιχνιδιού: ανακοινώθηκε το τέλος", + "log.end.condition": "Τέλος παιχνιδιού: ικανοποιήθηκε συνθήκη λήξης", + "log.end.stall": "Τέλος παιχνιδιού: πέρασε ένας ολόκληρος γύρος χωρίς τοποθέτηση πλακιδίου", + "log.end.dropped": "Τέλος παιχνιδιού: έμεινε μόνο ένας παίκτης", + "log.finalSale": "{name}: πουλά {count} {chain} για {amount}", + "log.result": "Τελικά μετρητά: {results}", + "chat.label": "Συνομιλία", + "chat.title": "Συνομιλία", + "chat.message": "Μήνυμα", + "chat.placeholder": "Μήνυμα…", + "chat.send": "Αποστολή", + "chat.sending": "Αποστολή…", + "chat.empty": "Δεν υπάρχουν μηνύματα ακόμη.", + "chat.edited": "επεξεργάστηκε", +}; diff --git a/packages/viewer/src/lib/locales/en.ts b/packages/viewer/src/lib/locales/en.ts new file mode 100644 index 0000000..8b78e5b --- /dev/null +++ b/packages/viewer/src/lib/locales/en.ts @@ -0,0 +1,183 @@ +// English source catalogue. Every other locale has exactly these keys (checked by the type +// system and by i18n.spec.ts). {name} placeholders must be kept; plural messages give one form +// per CLDR plural category of the language. Chain names are never translated. +export const en = { + loading: "Loading game…", + + // Status bar + "status.place": "{name} to place a tile", + "status.found": "{name} to name a new chain", + "status.survivor": "{name} to choose which chain survives the merger", + "status.defunctOrder": "{name} to choose the order of the defunct chains", + "status.dispose": "{name} to sell, trade or hold {chain} stock", + "status.buy": "{name} to buy shares", + "status.gameOver": "Game over", + "status.yourDecision": "your decision", + "status.announced": "The end of the game has been announced; it ends after this turn.", + "status.replay": "Replay: turn {turn}", + "status.replayNote": "You are viewing an earlier position. Tiles in hand are not shown.", + + // Decision panel + "panel.label": "Your decision", + "panel.sending": "Sending…", + "announce.ask": "End the game after this turn? This cannot be undone.", + "announce.confirm": "Announce the end", + "announce.cancel": "Keep playing", + "announce.open": "Announce the end…", + "place.effect": "{tile} {effect}.", + "place.loose": "stays loose (no neighbouring tiles)", + "place.found": "founds a new chain", + "place.joins": "joins {chain}", + "place.merges": "merges {chains}", + "place.button": "Place {tile}", + "place.another": "Choose another", + "place.choose": "Choose a tile from your hand.", + "place.none": "None of your tiles can be placed.", + "place.pass": "Continue without placing", + "found.prompt": "Name the new chain. You receive one free share.", + "survivor.prompt": "These chains are tied for largest. Choose which one survives.", + tiles: { one: "{count} tile", other: "{count} tiles" }, + "order.prompt": + "{survivor} survives. Some defunct chains are the same size: choose the order they are resolved in, first to last.", + "order.confirm": "Confirm order", + "order.reset": "Start over", + "dispose.takenOver": "{defunct} is taken over by {survivor}.", + "dispose.holding": { one: "You hold {count} {chain} share.", other: "You hold {count} {chain} shares." }, + "dispose.sell": "Sell at {price}", + "dispose.trade": "Trade 2 for 1", + "dispose.keep": "Keep", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "worthless unless {chain} is founded again", + "dispose.sellFewer": "Sell one fewer", + "dispose.sellMore": "Sell one more", + "dispose.tradeFewer": "Trade two fewer", + "dispose.tradeMore": "Trade two more", + "dispose.confirm": "Confirm", + "buy.prompt": "Buy up to 3 shares. Prices are fixed for this turn.", + "buy.chain": "Chain", + "buy.price": "Price", + "buy.bank": "Bank", + "buy.buy": "Buy", + "buy.fewer": "Buy one fewer {chain}", + "buy.more": "Buy one more {chain}", + "buy.total": "{count} of 3 shares · cost {cost} · cash left {cash}", + "buy.nothing": "Buy nothing and end turn", + "buy.confirm": "Buy for {cost} and end turn", + + // Board and hand + "board.label": "Board", + "board.empty": "{tile} empty", + "board.loose": "{tile} loose tile", + "board.chain": "{tile} {chain}", + "board.place": "Place {tile}", + "hand.yours": "Your tiles", + "hand.seat": "Tiles, seat {seat}", + "hand.of": "Tiles of {name}", + "hand.none": "No tiles", + "hand.dead": "dead: would merge safe chains", + "hand.eighth": "can't found an 8th chain", + + // Chain and price tables + "chains.label": "Hotel chains", + "chains.title": "Chains", + "chains.chain": "Chain", + "chains.size": "Size", + "chains.price": "Price", + "chains.bank": "Bank", + "chains.yours": "Yours", + "chains.notOnBoard": "not on board", + "chains.safe": "safe", + "prices.label": "Price table", + "prices.show": "Price table", + "prices.hide": "Hide price table", + "prices.minor": "Minor chains:", + "prices.medium": "Medium chains:", + "prices.major": "Major chains:", + "prices.price": "Price", + "prices.first": "1st", + "prices.second": "2nd", + "prices.note": "Sizes are tiles per chain. A chain's marker shows where it stands now.", + + // Players + "players.label": "Players", + "players.title": "Players", + "players.player": "Player", + "players.cash": "Cash", + "players.stock": "Stock", + "players.tiles": "Tiles", + "players.acting": "acting now", + "players.you": "you", + "players.turn": "turn", + "players.left": "left", + "players.none": "none", + hidden: "hidden", + "seat.name": "{name} (seat {seat})", + + // Log + "log.label": "Game log", + "log.title": "Log", + "log.recent": "Show recent lines only", + "log.all": { one: "Show the whole log ({count} more)", other: "Show the whole log ({count} more)" }, + "log.init": { one: "New game for {count} player", other: "New game for {count} players" }, + "log.optionIgnored.players": { + one: "Option {option} was ignored: it only applies with exactly {count} player", + other: "Option {option} was ignored: it only applies with exactly {count} players", + }, + "log.optionIgnored.value": "Option {option} was ignored: unknown value", + "log.turnOrder": "Turn order tiles: {tiles}. {name} goes first", + "log.turn": "{name}'s turn", + "log.placed": "{name} placed {tile}", + "log.placedAuto": "{name} placed {tile} (automatic)", + "log.survivor": "{name} chose {chain} to survive", + "log.survivorAuto": "{name} chose {chain} to survive (automatic)", + "log.order": "{name} chose the order {chains}", + "log.orderAuto": "{name} chose the order {chains} (automatic)", + "log.skipPlace": "{name} placed no tile", + "log.founded": "{name} founded {chain} ({tiles}) and received a free share", + "log.foundedNoShare": "{name} founded {chain} ({tiles}); no free share was left", + "log.grew": "{chain} grew to {tiles}", + "log.merger": "{name}'s {tile} merges {chains}", + "log.mergerBank": "The bank's tile {tile} merges {chains}", + "log.mergerPlan": "{survivor} survives and takes over {chains}", + "log.bonuses": "{chain} bonuses at size {size}: {payouts}", + "log.bonusesNobody": "{chain} bonuses at size {size}: nobody paid", + "log.bankHeld": { + one: "; the bank held {count} share (drew {tile})", + other: "; the bank held {count} shares (drew {tile})", + }, + "log.bankHeldEmpty": "; the bank held 0 shares (empty pool)", + "log.bankKept": " and kept {amount}", + "log.shares": { one: "{count} {chain} share", other: "{count} {chain} shares" }, + "log.sold": "sold {shares} for {amount}", + "log.traded": "traded {shares} for {count} of the survivor", + "log.kept": "kept {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} had nothing to dispose of", + "log.merged": "{chain} now has {tiles}", + "log.bankLoose": "The bank's tile {tile} stays loose", + "log.bankJoined": "The bank's tile {tile} joins a chain", + "log.bankMerger": "The bank's tile {tile} causes a merger", + "log.bankRemoved": "The bank's tile {tile} cannot be played and is removed", + "log.bought": "{name} bought {shares} for {cost}", + "log.boughtNothing": "{name} bought no shares", + "log.discarded": "{name} discarded unplayable {tiles}", + "log.drew": { one: "{name} drew a tile", other: "{name} drew {count} tiles" }, + "log.dropped": "{name} left the game", + "log.announced": "{name} announced the end of the game", + "log.end.announced": "Game over: the end was announced", + "log.end.condition": "Game over: an end condition was met", + "log.end.stall": "Game over: a full round passed with no tile placed", + "log.end.dropped": "Game over: only one player remained", + "log.finalSale": "{name} sold {count} {chain} for {amount}", + "log.result": "Final cash: {results}", + + // Chat panel (the shared BGS panel's own labels) + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Message", + "chat.placeholder": "Message…", + "chat.send": "Send", + "chat.sending": "Sending…", + "chat.empty": "No messages yet.", + "chat.edited": "edited", +} as const; diff --git a/packages/viewer/src/lib/locales/fa.ts b/packages/viewer/src/lib/locales/fa.ts new file mode 100644 index 0000000..05f99b1 --- /dev/null +++ b/packages/viewer/src/lib/locales/fa.ts @@ -0,0 +1,168 @@ +import type { Catalog } from "../i18n.ts"; + +export const fa: Catalog = { + loading: "در حال بارگذاری بازی…", + "status.place": "{name} باید یک کاشی بگذارد", + "status.found": "{name} باید برای زنجیره‌ی جدید نام انتخاب کند", + "status.survivor": "{name} باید زنجیره‌ای را که در ادغام می‌ماند انتخاب کند", + "status.defunctOrder": "{name} باید ترتیب زنجیره‌های ادغام‌شونده را انتخاب کند", + "status.dispose": "{name} باید سهام {chain} را بفروشد، معاوضه کند یا نگه دارد", + "status.buy": "{name} باید سهام بخرد", + "status.gameOver": "پایان بازی", + "status.yourDecision": "تصمیم شما", + "status.announced": "پایان بازی اعلام شده است؛ بازی بعد از این نوبت تمام می‌شود.", + "status.replay": "بازپخش: نوبت {turn}", + "status.replayNote": "شما وضعیت قبلی بازی را می‌بینید. کاشی‌های دست نشان داده نمی‌شوند.", + "panel.label": "تصمیم شما", + "panel.sending": "در حال ارسال…", + "announce.ask": "بازی بعد از این نوبت تمام شود؟ این کار برگشت‌پذیر نیست.", + "announce.confirm": "اعلام پایان", + "announce.cancel": "ادامه‌ی بازی", + "announce.open": "اعلام پایان…", + "place.effect": "{tile}: {effect}.", + "place.loose": "تنها می‌ماند (کاشی همسایه ندارد)", + "place.found": "زنجیره‌ی جدیدی تأسیس می‌کند", + "place.joins": "به {chain} می‌پیوندد", + "place.merges": "{chains} را ادغام می‌کند", + "place.button": "گذاشتن {tile}", + "place.another": "انتخاب کاشی دیگر", + "place.choose": "یک کاشی از دستتان انتخاب کنید.", + "place.none": "هیچ‌کدام از کاشی‌های شما قابل گذاشتن نیست.", + "place.pass": "ادامه بدون گذاشتن", + "found.prompt": "برای زنجیره‌ی جدید نام انتخاب کنید. یک سهم رایگان می‌گیرید.", + "survivor.prompt": "این زنجیره‌ها هم‌اندازه و بزرگ‌ترین‌اند. انتخاب کنید کدام بماند.", + tiles: { one: "{count} کاشی", other: "{count} کاشی" }, + "order.prompt": + "{survivor} می‌ماند. برخی زنجیره‌های ادغام‌شونده هم‌اندازه‌اند: ترتیب تسویه‌ی آن‌ها را از اول تا آخر انتخاب کنید.", + "order.confirm": "تأیید ترتیب", + "order.reset": "از نو", + "dispose.takenOver": "{defunct} در {survivor} ادغام می‌شود.", + "dispose.holding": { one: "شما {count} سهم {chain} دارید.", other: "شما {count} سهم {chain} دارید." }, + "dispose.sell": "فروش به {price}", + "dispose.trade": "معاوضه‌ی 2 به 1", + "dispose.keep": "نگه‌داشتن", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "بی‌ارزش، مگر اینکه {chain} دوباره تأسیس شود", + "dispose.sellFewer": "یکی کمتر بفروش", + "dispose.sellMore": "یکی بیشتر بفروش", + "dispose.tradeFewer": "دو تا کمتر معاوضه کن", + "dispose.tradeMore": "دو تا بیشتر معاوضه کن", + "dispose.confirm": "تأیید", + "buy.prompt": "حداکثر 3 سهم بخرید. قیمت‌ها در این نوبت ثابت‌اند.", + "buy.chain": "زنجیره", + "buy.price": "قیمت", + "buy.bank": "بانک", + "buy.buy": "خرید", + "buy.fewer": "یک سهم {chain} کمتر", + "buy.more": "یک سهم {chain} بیشتر", + "buy.total": "{count} از 3 سهم · هزینه {cost} · باقی‌مانده {cash}", + "buy.nothing": "چیزی نخر و نوبت را تمام کن", + "buy.confirm": "خرید به {cost} و پایان نوبت", + "board.label": "صفحه‌ی بازی", + "board.empty": "{tile} خالی", + "board.loose": "{tile} کاشی تنها", + "board.chain": "{tile} {chain}", + "board.place": "گذاشتن {tile}", + "hand.yours": "کاشی‌های شما", + "hand.seat": "کاشی‌ها، جایگاه {seat}", + "hand.of": "کاشی‌های {name}", + "hand.none": "بدون کاشی", + "hand.dead": "مرده: زنجیره‌های امن را ادغام می‌کند", + "hand.eighth": "زنجیره‌ی هشتم ممکن نیست", + "chains.label": "زنجیره‌های هتل", + "chains.title": "زنجیره‌ها", + "chains.chain": "زنجیره", + "chains.size": "اندازه", + "chains.price": "قیمت", + "chains.bank": "بانک", + "chains.yours": "مال شما", + "chains.notOnBoard": "روی صفحه نیست", + "chains.safe": "امن", + "prices.label": "جدول قیمت", + "prices.show": "جدول قیمت", + "prices.hide": "پنهان‌کردن جدول قیمت", + "prices.minor": "زنجیره‌های کوچک:", + "prices.medium": "زنجیره‌های متوسط:", + "prices.major": "زنجیره‌های بزرگ:", + "prices.price": "قیمت", + "prices.first": "اول", + "prices.second": "دوم", + "prices.note": "اندازه یعنی تعداد کاشی‌های زنجیره. نشان هر زنجیره جای فعلی آن را نشان می‌دهد.", + "players.label": "بازیکنان", + "players.title": "بازیکنان", + "players.player": "بازیکن", + "players.cash": "پول", + "players.stock": "سهام", + "players.tiles": "کاشی‌ها", + "players.acting": "در حال تصمیم", + "players.you": "شما", + "players.turn": "نوبت", + "players.left": "رفته", + "players.none": "هیچ", + hidden: "پنهان", + "seat.name": "{name} (جایگاه {seat})", + "log.label": "گزارش بازی", + "log.title": "گزارش", + "log.recent": "فقط خط‌های اخیر", + "log.all": { one: "نمایش کل گزارش ({count} خط دیگر)", other: "نمایش کل گزارش ({count} خط دیگر)" }, + "log.init": { one: "بازی جدید برای {count} بازیکن", other: "بازی جدید برای {count} بازیکن" }, + "log.optionIgnored.players": { + one: "گزینه‌ی {option} نادیده گرفته شد: فقط با دقیقاً {count} بازیکن اعمال می‌شود", + other: "گزینه‌ی {option} نادیده گرفته شد: فقط با دقیقاً {count} بازیکن اعمال می‌شود", + }, + "log.optionIgnored.value": "گزینه‌ی {option} نادیده گرفته شد: مقدار ناشناخته", + "log.turnOrder": "کاشی‌های ترتیب نوبت: {tiles}. {name} شروع می‌کند", + "log.turn": "نوبت {name}", + "log.placed": "{name} کاشی {tile} را گذاشت", + "log.placedAuto": "{name} کاشی {tile} را گذاشت (خودکار)", + "log.survivor": "{name} ماندن {chain} را انتخاب کرد", + "log.survivorAuto": "{name} ماندن {chain} را انتخاب کرد (خودکار)", + "log.order": "{name} ترتیب {chains} را انتخاب کرد", + "log.orderAuto": "{name} ترتیب {chains} را انتخاب کرد (خودکار)", + "log.skipPlace": "{name} کاشی نگذاشت", + "log.founded": "{name} {chain} را تأسیس کرد ({tiles}) و یک سهم رایگان گرفت", + "log.foundedNoShare": "{name} {chain} را تأسیس کرد ({tiles})؛ سهم رایگانی نمانده بود", + "log.grew": "{chain} به {tiles} رسید", + "log.merger": "کاشی {tile} از {name} {chains} را ادغام می‌کند", + "log.mergerBank": "کاشی {tile} بانک {chains} را ادغام می‌کند", + "log.mergerPlan": "{survivor} می‌ماند و {chains} را جذب می‌کند", + "log.bonuses": "پاداش‌های {chain} در اندازه‌ی {size}: {payouts}", + "log.bonusesNobody": "پاداش‌های {chain} در اندازه‌ی {size}: به کسی پرداخت نشد", + "log.bankHeld": { + one: "؛ بانک {count} سهم داشت ({tile} را کشید)", + other: "؛ بانک {count} سهم داشت ({tile} را کشید)", + }, + "log.bankHeldEmpty": "؛ بانک 0 سهم داشت (کیسه خالی است)", + "log.bankKept": " و {amount} را نگه داشت", + "log.shares": { one: "{count} سهم {chain}", other: "{count} سهم {chain}" }, + "log.sold": "{shares} را به {amount} فروخت", + "log.traded": "{shares} را با {count} سهم زنجیره‌ی باقی‌مانده معاوضه کرد", + "log.kept": "{shares} را نگه داشت", + "log.disposed": "{name}: {actions}", + "log.disposedNothing": "{name} چیزی برای تسویه نداشت", + "log.merged": "{chain} اکنون {tiles} دارد", + "log.bankLoose": "کاشی {tile} بانک تنها می‌ماند", + "log.bankJoined": "کاشی {tile} بانک به یک زنجیره می‌پیوندد", + "log.bankMerger": "کاشی {tile} بانک ادغامی را آغاز می‌کند", + "log.bankRemoved": "کاشی {tile} بانک قابل گذاشتن نیست و حذف می‌شود", + "log.bought": "{name} {shares} را به {cost} خرید", + "log.boughtNothing": "{name} سهمی نخرید", + "log.discarded": "{name} کاشی‌های غیرقابل‌بازی را کنار گذاشت: {tiles}", + "log.drew": { one: "{name} یک کاشی کشید", other: "{name} {count} کاشی کشید" }, + "log.dropped": "{name} بازی را ترک کرد", + "log.announced": "{name} پایان بازی را اعلام کرد", + "log.end.announced": "پایان بازی: پایان اعلام شد", + "log.end.condition": "پایان بازی: یکی از شرایط پایان برقرار شد", + "log.end.stall": "پایان بازی: یک دور کامل بدون گذاشتن کاشی گذشت", + "log.end.dropped": "پایان بازی: فقط یک بازیکن ماند", + "log.finalSale": "{name} {count} سهم {chain} را به {amount} فروخت", + "log.result": "پول نهایی: {results}", + "chat.label": "گفتگو", + "chat.title": "گفتگو", + "chat.message": "پیام", + "chat.placeholder": "پیام…", + "chat.send": "ارسال", + "chat.sending": "در حال ارسال…", + "chat.empty": "هنوز پیامی نیست.", + "chat.edited": "ویرایش‌شده", +}; diff --git a/packages/viewer/src/lib/locales/fr.ts b/packages/viewer/src/lib/locales/fr.ts new file mode 100644 index 0000000..2310b3b --- /dev/null +++ b/packages/viewer/src/lib/locales/fr.ts @@ -0,0 +1,186 @@ +import type { Catalog } from "../i18n.ts"; + +export const fr: Catalog = { + loading: "Chargement de la partie…", + "status.place": "{name} doit poser une tuile", + "status.found": "{name} doit nommer une nouvelle chaîne", + "status.survivor": "{name} doit choisir la chaîne qui survit à la fusion", + "status.defunctOrder": "{name} doit choisir l’ordre des chaînes absorbées", + "status.dispose": "{name} doit vendre, échanger ou garder ses actions {chain}", + "status.buy": "{name} doit acheter des actions", + "status.gameOver": "Partie terminée", + "status.yourDecision": "à vous de décider", + "status.announced": "La fin de la partie a été annoncée ; elle se termine après ce tour.", + "status.replay": "Relecture : tour {turn}", + "status.replayNote": "Vous regardez une position antérieure. Les tuiles en main ne sont pas affichées.", + "panel.label": "Votre décision", + "panel.sending": "Envoi…", + "announce.ask": "Terminer la partie après ce tour ? Ce choix est définitif.", + "announce.confirm": "Annoncer la fin", + "announce.cancel": "Continuer à jouer", + "announce.open": "Annoncer la fin…", + "place.effect": "{tile} : {effect}.", + "place.loose": "reste isolée (aucune tuile voisine)", + "place.found": "fonde une nouvelle chaîne", + "place.joins": "agrandit {chain}", + "place.merges": "fusionne {chains}", + "place.button": "Poser {tile}", + "place.another": "Choisir une autre", + "place.choose": "Choisissez une tuile de votre main.", + "place.none": "Aucune de vos tuiles ne peut être posée.", + "place.pass": "Continuer sans poser", + "found.prompt": "Nommez la nouvelle chaîne. Vous recevez une action gratuite.", + "survivor.prompt": "Ces chaînes sont à égalité pour la plus grande. Choisissez celle qui survit.", + tiles: { one: "{count} tuile", many: "{count} tuiles", other: "{count} tuiles" }, + "order.prompt": + "{survivor} survit. Certaines chaînes absorbées ont la même taille : choisissez l’ordre dans lequel elles sont réglées, de la première à la dernière.", + "order.confirm": "Confirmer l’ordre", + "order.reset": "Recommencer", + "dispose.takenOver": "{defunct} est absorbée par {survivor}.", + "dispose.holding": { + one: "Vous détenez {count} action {chain}.", + many: "Vous détenez {count} actions {chain}.", + other: "Vous détenez {count} actions {chain}.", + }, + "dispose.sell": "Vendre à {price}", + "dispose.trade": "Échanger 2 contre 1", + "dispose.keep": "Garder", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "sans valeur, sauf si {chain} est fondée à nouveau", + "dispose.sellFewer": "Vendre une de moins", + "dispose.sellMore": "Vendre une de plus", + "dispose.tradeFewer": "Échanger deux de moins", + "dispose.tradeMore": "Échanger deux de plus", + "dispose.confirm": "Confirmer", + "buy.prompt": "Achetez jusqu’à 3 actions. Les prix restent fixes pendant ce tour.", + "buy.chain": "Chaîne", + "buy.price": "Prix", + "buy.bank": "Banque", + "buy.buy": "Achat", + "buy.fewer": "Acheter une action {chain} de moins", + "buy.more": "Acheter une action {chain} de plus", + "buy.total": "{count} actions sur 3 · coût {cost} · argent restant {cash}", + "buy.nothing": "Ne rien acheter et finir le tour", + "buy.confirm": "Acheter pour {cost} et finir le tour", + "board.label": "Plateau", + "board.empty": "{tile} vide", + "board.loose": "{tile} tuile isolée", + "board.chain": "{tile} {chain}", + "board.place": "Poser {tile}", + "hand.yours": "Vos tuiles", + "hand.seat": "Tuiles, place {seat}", + "hand.of": "Tuiles de {name}", + "hand.none": "Aucune tuile", + "hand.dead": "morte : fusionnerait des chaînes sûres", + "hand.eighth": "impossible de fonder une 8e chaîne", + "chains.label": "Chaînes d’hôtels", + "chains.title": "Chaînes", + "chains.chain": "Chaîne", + "chains.size": "Taille", + "chains.price": "Prix", + "chains.bank": "Banque", + "chains.yours": "Les vôtres", + "chains.notOnBoard": "absente du plateau", + "chains.safe": "sûre", + "prices.label": "Table des prix", + "prices.show": "Table des prix", + "prices.hide": "Masquer la table des prix", + "prices.minor": "Petites chaînes :", + "prices.medium": "Chaînes moyennes :", + "prices.major": "Grandes chaînes :", + "prices.price": "Prix", + "prices.first": "1re", + "prices.second": "2e", + "prices.note": "Les tailles sont en tuiles par chaîne. Le marqueur d’une chaîne indique où elle en est.", + "players.label": "Joueurs", + "players.title": "Joueurs", + "players.player": "Joueur", + "players.cash": "Argent", + "players.stock": "Actions", + "players.tiles": "Tuiles", + "players.acting": "doit jouer", + "players.you": "vous", + "players.turn": "son tour", + "players.left": "parti", + "players.none": "aucune", + hidden: "caché", + "seat.name": "{name} (place {seat})", + "log.label": "Journal de la partie", + "log.title": "Journal", + "log.recent": "Afficher seulement les dernières lignes", + "log.all": { + one: "Afficher tout le journal ({count} de plus)", + many: "Afficher tout le journal ({count} de plus)", + other: "Afficher tout le journal ({count} de plus)", + }, + "log.init": { + one: "Nouvelle partie à {count} joueur", + many: "Nouvelle partie à {count} joueurs", + other: "Nouvelle partie à {count} joueurs", + }, + "log.optionIgnored.players": { + one: "L’option {option} a été ignorée : elle ne s’applique qu’avec exactement {count} joueur", + many: "L’option {option} a été ignorée : elle ne s’applique qu’avec exactement {count} joueurs", + other: "L’option {option} a été ignorée : elle ne s’applique qu’avec exactement {count} joueurs", + }, + "log.optionIgnored.value": "L’option {option} a été ignorée : valeur inconnue", + "log.turnOrder": "Tuiles pour l’ordre de jeu : {tiles}. {name} commence", + "log.turn": "Tour de {name}", + "log.placed": "{name} pose {tile}", + "log.placedAuto": "{name} pose {tile} (automatique)", + "log.survivor": "{name} choisit {chain} comme survivante", + "log.survivorAuto": "{name} choisit {chain} comme survivante (automatique)", + "log.order": "{name} choisit l’ordre {chains}", + "log.orderAuto": "{name} choisit l’ordre {chains} (automatique)", + "log.skipPlace": "{name} ne pose aucune tuile", + "log.founded": "{name} fonde {chain} ({tiles}) et reçoit une action gratuite", + "log.foundedNoShare": "{name} fonde {chain} ({tiles}) ; il ne restait aucune action gratuite", + "log.grew": "{chain} passe à {tiles}", + "log.merger": "La tuile {tile} de {name} fusionne {chains}", + "log.mergerBank": "La tuile {tile} de la banque fusionne {chains}", + "log.mergerPlan": "{survivor} survit et absorbe {chains}", + "log.bonuses": "Primes de {chain} à la taille {size} : {payouts}", + "log.bonusesNobody": "Primes de {chain} à la taille {size} : personne n’est payé", + "log.bankHeld": { + one: " ; la banque détenait {count} action (tuile {tile})", + many: " ; la banque détenait {count} actions (tuile {tile})", + other: " ; la banque détenait {count} actions (tuile {tile})", + }, + "log.bankHeldEmpty": " ; la banque détenait 0 action (pioche vide)", + "log.bankKept": " et a gardé {amount}", + "log.shares": { one: "{count} action {chain}", many: "{count} actions {chain}", other: "{count} actions {chain}" }, + "log.sold": "vend {shares} pour {amount}", + "log.traded": "échange {shares} contre {count} de la survivante", + "log.kept": "garde {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} n’avait rien à régler", + "log.merged": "{chain} compte maintenant {tiles}", + "log.bankLoose": "La tuile {tile} de la banque reste isolée", + "log.bankJoined": "La tuile {tile} de la banque agrandit une chaîne", + "log.bankMerger": "La tuile {tile} de la banque provoque une fusion", + "log.bankRemoved": "La tuile {tile} de la banque est injouable et retirée", + "log.bought": "{name} achète {shares} pour {cost}", + "log.boughtNothing": "{name} n’achète aucune action", + "log.discarded": "{name} défausse des tuiles injouables : {tiles}", + "log.drew": { + one: "{name} pioche une tuile", + many: "{name} pioche {count} tuiles", + other: "{name} pioche {count} tuiles", + }, + "log.dropped": "{name} a quitté la partie", + "log.announced": "{name} annonce la fin de la partie", + "log.end.announced": "Partie terminée : la fin a été annoncée", + "log.end.condition": "Partie terminée : une condition de fin est remplie", + "log.end.stall": "Partie terminée : un tour complet s’est passé sans pose de tuile", + "log.end.dropped": "Partie terminée : il ne reste qu’un joueur", + "log.finalSale": "{name} vend {count} {chain} pour {amount}", + "log.result": "Argent final : {results}", + "chat.label": "Discussion", + "chat.title": "Discussion", + "chat.message": "Message", + "chat.placeholder": "Message…", + "chat.send": "Envoyer", + "chat.sending": "Envoi…", + "chat.empty": "Aucun message pour l’instant.", + "chat.edited": "modifié", +}; diff --git a/packages/viewer/src/lib/locales/hi.ts b/packages/viewer/src/lib/locales/hi.ts new file mode 100644 index 0000000..14b02aa --- /dev/null +++ b/packages/viewer/src/lib/locales/hi.ts @@ -0,0 +1,167 @@ +import type { Catalog } from "../i18n.ts"; + +export const hi: Catalog = { + loading: "खेल लोड हो रहा है…", + "status.place": "{name} को एक टाइल रखनी है", + "status.found": "{name} को नई श्रृंखला का नाम चुनना है", + "status.survivor": "{name} को चुनना है कि विलय में कौन सी श्रृंखला बचेगी", + "status.defunctOrder": "{name} को विलय होने वाली श्रृंखलाओं का क्रम चुनना है", + "status.dispose": "{name} को {chain} के शेयर बेचने, बदलने या रखने हैं", + "status.buy": "{name} को शेयर खरीदने हैं", + "status.gameOver": "खेल समाप्त", + "status.yourDecision": "आपका निर्णय", + "status.announced": "खेल के अंत की घोषणा हो चुकी है; यह इस बारी के बाद समाप्त होगा।", + "status.replay": "रीप्ले: बारी {turn}", + "status.replayNote": "आप पहले की स्थिति देख रहे हैं। हाथ की टाइलें नहीं दिखाई जातीं।", + "panel.label": "आपका निर्णय", + "panel.sending": "भेजा जा रहा है…", + "announce.ask": "इस बारी के बाद खेल समाप्त करें? इसे वापस नहीं लिया जा सकता।", + "announce.confirm": "अंत की घोषणा करें", + "announce.cancel": "खेलना जारी रखें", + "announce.open": "अंत की घोषणा करें…", + "place.effect": "{tile}: {effect}।", + "place.loose": "अकेली रहती है (कोई पड़ोसी टाइल नहीं)", + "place.found": "नई श्रृंखला स्थापित करती है", + "place.joins": "{chain} में जुड़ती है", + "place.merges": "{chains} का विलय करती है", + "place.button": "{tile} रखें", + "place.another": "दूसरी चुनें", + "place.choose": "अपने हाथ से एक टाइल चुनें।", + "place.none": "आपकी कोई भी टाइल रखी नहीं जा सकती।", + "place.pass": "बिना रखे आगे बढ़ें", + "found.prompt": "नई श्रृंखला का नाम चुनें। आपको एक मुफ़्त शेयर मिलेगा।", + "survivor.prompt": "ये श्रृंखलाएँ सबसे बड़ी होने में बराबर हैं। चुनें कि कौन सी बचेगी।", + tiles: { one: "{count} टाइल", other: "{count} टाइलें" }, + "order.prompt": "{survivor} बचती है। विलय होने वाली कुछ श्रृंखलाएँ एक ही आकार की हैं: पहली से आख़िरी तक, उनके निपटान का क्रम चुनें।", + "order.confirm": "क्रम की पुष्टि करें", + "order.reset": "फिर से शुरू करें", + "dispose.takenOver": "{defunct} का {survivor} में विलय हो रहा है।", + "dispose.holding": { one: "आपके पास {chain} का {count} शेयर है।", other: "आपके पास {chain} के {count} शेयर हैं।" }, + "dispose.sell": "{price} पर बेचें", + "dispose.trade": "2 के बदले 1", + "dispose.keep": "रखें", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "बेकार, जब तक {chain} फिर से स्थापित न हो", + "dispose.sellFewer": "एक कम बेचें", + "dispose.sellMore": "एक और बेचें", + "dispose.tradeFewer": "दो कम बदलें", + "dispose.tradeMore": "दो और बदलें", + "dispose.confirm": "पुष्टि करें", + "buy.prompt": "अधिकतम 3 शेयर खरीदें। इस बारी में कीमतें नहीं बदलतीं।", + "buy.chain": "श्रृंखला", + "buy.price": "कीमत", + "buy.bank": "बैंक", + "buy.buy": "खरीदें", + "buy.fewer": "{chain} का एक शेयर कम", + "buy.more": "{chain} का एक शेयर और", + "buy.total": "3 में से {count} शेयर · लागत {cost} · बची नकदी {cash}", + "buy.nothing": "कुछ न खरीदें और बारी समाप्त करें", + "buy.confirm": "{cost} में खरीदें और बारी समाप्त करें", + "board.label": "बोर्ड", + "board.empty": "{tile} खाली", + "board.loose": "{tile} अकेली टाइल", + "board.chain": "{tile} {chain}", + "board.place": "{tile} रखें", + "hand.yours": "आपकी टाइलें", + "hand.seat": "टाइलें, सीट {seat}", + "hand.of": "{name} की टाइलें", + "hand.none": "कोई टाइल नहीं", + "hand.dead": "बेकार: सुरक्षित श्रृंखलाओं का विलय कर देगी", + "hand.eighth": "8वीं श्रृंखला स्थापित नहीं हो सकती", + "chains.label": "होटल श्रृंखलाएँ", + "chains.title": "श्रृंखलाएँ", + "chains.chain": "श्रृंखला", + "chains.size": "आकार", + "chains.price": "कीमत", + "chains.bank": "बैंक", + "chains.yours": "आपके", + "chains.notOnBoard": "बोर्ड पर नहीं", + "chains.safe": "सुरक्षित", + "prices.label": "कीमत तालिका", + "prices.show": "कीमत तालिका", + "prices.hide": "कीमत तालिका छिपाएँ", + "prices.minor": "छोटी श्रृंखलाएँ:", + "prices.medium": "मध्यम श्रृंखलाएँ:", + "prices.major": "बड़ी श्रृंखलाएँ:", + "prices.price": "कीमत", + "prices.first": "पहला", + "prices.second": "दूसरा", + "prices.note": "आकार यानी श्रृंखला की टाइलें। श्रृंखला का चिह्न बताता है कि वह अभी कहाँ है।", + "players.label": "खिलाड़ी", + "players.title": "खिलाड़ी", + "players.player": "खिलाड़ी", + "players.cash": "नकदी", + "players.stock": "शेयर", + "players.tiles": "टाइलें", + "players.acting": "अभी चल रहे हैं", + "players.you": "आप", + "players.turn": "बारी", + "players.left": "छोड़ गए", + "players.none": "कोई नहीं", + hidden: "छिपा", + "seat.name": "{name} (सीट {seat})", + "log.label": "खेल का लॉग", + "log.title": "लॉग", + "log.recent": "केवल हाल की पंक्तियाँ दिखाएँ", + "log.all": { one: "पूरा लॉग दिखाएँ ({count} और)", other: "पूरा लॉग दिखाएँ ({count} और)" }, + "log.init": { one: "{count} खिलाड़ी के लिए नया खेल", other: "{count} खिलाड़ियों के लिए नया खेल" }, + "log.optionIgnored.players": { + one: "विकल्प {option} अनदेखा किया गया: यह केवल ठीक {count} खिलाड़ी के साथ लागू होता है", + other: "विकल्प {option} अनदेखा किया गया: यह केवल ठीक {count} खिलाड़ियों के साथ लागू होता है", + }, + "log.optionIgnored.value": "विकल्प {option} अनदेखा किया गया: अज्ञात मान", + "log.turnOrder": "क्रम की टाइलें: {tiles}। पहले {name} खेलेंगे", + "log.turn": "{name} की बारी", + "log.placed": "{name} ने {tile} रखी", + "log.placedAuto": "{name} ने {tile} रखी (स्वचालित)", + "log.survivor": "{name} ने {chain} को बचाने के लिए चुना", + "log.survivorAuto": "{name} ने {chain} को बचाने के लिए चुना (स्वचालित)", + "log.order": "{name} ने क्रम चुना: {chains}", + "log.orderAuto": "{name} ने क्रम चुना: {chains} (स्वचालित)", + "log.skipPlace": "{name} ने कोई टाइल नहीं रखी", + "log.founded": "{name} ने {chain} स्थापित की ({tiles}) और एक मुफ़्त शेयर पाया", + "log.foundedNoShare": "{name} ने {chain} स्थापित की ({tiles}); कोई मुफ़्त शेयर नहीं बचा था", + "log.grew": "{chain} बढ़कर {tiles} की हुई", + "log.merger": "{name} की {tile} ने {chains} का विलय किया", + "log.mergerBank": "बैंक की टाइल {tile} ने {chains} का विलय किया", + "log.mergerPlan": "{survivor} बचती है और {chains} को अपने में मिलाती है", + "log.bonuses": "आकार {size} पर {chain} के बोनस: {payouts}", + "log.bonusesNobody": "आकार {size} पर {chain} के बोनस: किसी को भुगतान नहीं", + "log.bankHeld": { + one: "; बैंक के पास {count} शेयर था ({tile} निकाली)", + other: "; बैंक के पास {count} शेयर थे ({tile} निकाली)", + }, + "log.bankHeldEmpty": "; बैंक के पास 0 शेयर थे (भंडार खाली)", + "log.bankKept": " और {amount} रख लिए", + "log.shares": { one: "{chain} का {count} शेयर", other: "{chain} के {count} शेयर" }, + "log.sold": "{shares} {amount} में बेचे", + "log.traded": "{shares} बचने वाली श्रृंखला के {count} शेयरों से बदले", + "log.kept": "{shares} रखे", + "log.disposed": "{name}: {actions}", + "log.disposedNothing": "{name} के पास निपटाने को कुछ नहीं था", + "log.merged": "{chain} में अब {tiles} हैं", + "log.bankLoose": "बैंक की टाइल {tile} अकेली रहती है", + "log.bankJoined": "बैंक की टाइल {tile} एक श्रृंखला में जुड़ती है", + "log.bankMerger": "बैंक की टाइल {tile} से विलय होता है", + "log.bankRemoved": "बैंक की टाइल {tile} खेली नहीं जा सकती और हटा दी जाती है", + "log.bought": "{name} ने {shares} {cost} में खरीदे", + "log.boughtNothing": "{name} ने कोई शेयर नहीं खरीदा", + "log.discarded": "{name} ने न खेली जा सकने वाली टाइलें हटाईं: {tiles}", + "log.drew": { one: "{name} ने एक टाइल ली", other: "{name} ने {count} टाइलें लीं" }, + "log.dropped": "{name} ने खेल छोड़ दिया", + "log.announced": "{name} ने खेल के अंत की घोषणा की", + "log.end.announced": "खेल समाप्त: अंत की घोषणा हुई", + "log.end.condition": "खेल समाप्त: अंत की एक शर्त पूरी हुई", + "log.end.stall": "खेल समाप्त: पूरे एक दौर में कोई टाइल नहीं रखी गई", + "log.end.dropped": "खेल समाप्त: केवल एक खिलाड़ी बचा", + "log.finalSale": "{name} ने {chain} के {count} शेयर {amount} में बेचे", + "log.result": "अंतिम नकदी: {results}", + "chat.label": "चैट", + "chat.title": "चैट", + "chat.message": "संदेश", + "chat.placeholder": "संदेश…", + "chat.send": "भेजें", + "chat.sending": "भेजा जा रहा है…", + "chat.empty": "अभी कोई संदेश नहीं।", + "chat.edited": "संपादित", +}; diff --git a/packages/viewer/src/lib/locales/it.ts b/packages/viewer/src/lib/locales/it.ts new file mode 100644 index 0000000..db0c81d --- /dev/null +++ b/packages/viewer/src/lib/locales/it.ts @@ -0,0 +1,191 @@ +import type { Catalog } from "../i18n.ts"; + +export const it: Catalog = { + loading: "Caricamento della partita…", + "status.place": "{name} deve piazzare una tessera", + "status.found": "{name} deve dare un nome a una nuova catena", + "status.survivor": "{name} deve scegliere quale catena sopravvive alla fusione", + "status.defunctOrder": "{name} deve scegliere l'ordine delle catene assorbite", + "status.dispose": "{name} deve vendere, scambiare o tenere azioni {chain}", + "status.buy": "{name} deve comprare azioni", + "status.gameOver": "Partita finita", + "status.yourDecision": "tocca a te decidere", + "status.announced": "È stata annunciata la fine; la partita termina dopo questo turno.", + "status.replay": "Replay: turno {turn}", + "status.replayNote": "Stai guardando una posizione precedente. Le tessere in mano non sono mostrate.", + "panel.label": "La tua decisione", + "panel.sending": "Invio…", + "announce.ask": "Terminare la partita dopo questo turno? Non si può annullare.", + "announce.confirm": "Annuncia la fine", + "announce.cancel": "Continua a giocare", + "announce.open": "Annuncia la fine…", + "place.effect": "{tile}: {effect}.", + "place.loose": "resta isolata (nessuna tessera vicina)", + "place.found": "fonda una nuova catena", + "place.joins": "si unisce a {chain}", + "place.merges": "fonde {chains}", + "place.button": "Piazza {tile}", + "place.another": "Scegline un'altra", + "place.choose": "Scegli una tessera dalla tua mano.", + "place.none": "Nessuna delle tue tessere può essere piazzata.", + "place.pass": "Continua senza piazzare", + "found.prompt": "Dai un nome alla nuova catena. Ricevi un'azione gratuita.", + "survivor.prompt": "Queste catene sono le più grandi a pari merito. Scegli quale sopravvive.", + tiles: { one: "{count} tessera", many: "{count} tessere", other: "{count} tessere" }, + "order.prompt": + "{survivor} sopravvive. Alcune catene assorbite hanno la stessa dimensione: scegli l'ordine in cui vengono liquidate, dalla prima all'ultima.", + "order.confirm": "Conferma l'ordine", + "order.reset": "Ricomincia", + "dispose.takenOver": "{defunct} viene assorbita da {survivor}.", + "dispose.holding": { + one: "Hai {count} azione {chain}.", + many: "Hai {count} azioni {chain}.", + other: "Hai {count} azioni {chain}.", + }, + "dispose.sell": "Vendi a {price}", + "dispose.trade": "Scambia 2 per 1", + "dispose.keep": "Tieni", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "senza valore, a meno che {chain} non venga fondata di nuovo", + "dispose.sellFewer": "Vendine una in meno", + "dispose.sellMore": "Vendine una in più", + "dispose.tradeFewer": "Scambiane due in meno", + "dispose.tradeMore": "Scambiane due in più", + "dispose.confirm": "Conferma", + "buy.prompt": "Compra fino a 3 azioni. I prezzi restano fissi in questo turno.", + "buy.chain": "Catena", + "buy.price": "Prezzo", + "buy.bank": "Banca", + "buy.buy": "Compra", + "buy.fewer": "Un'azione {chain} in meno", + "buy.more": "Un'azione {chain} in più", + "buy.total": "{count} di 3 azioni · costo {cost} · restano {cash}", + "buy.nothing": "Non comprare nulla e termina il turno", + "buy.confirm": "Compra per {cost} e termina il turno", + "board.label": "Tabellone", + "board.empty": "{tile} vuota", + "board.loose": "{tile} tessera isolata", + "board.chain": "{tile} {chain}", + "board.place": "Piazza {tile}", + "hand.yours": "Le tue tessere", + "hand.seat": "Tessere, posto {seat}", + "hand.of": "Tessere di {name}", + "hand.none": "Nessuna tessera", + "hand.dead": "morta: fonderebbe catene sicure", + "hand.eighth": "non si può fondare un'8ª catena", + "chains.label": "Catene alberghiere", + "chains.title": "Catene", + "chains.chain": "Catena", + "chains.size": "Dimensione", + "chains.price": "Prezzo", + "chains.bank": "Banca", + "chains.yours": "Tue", + "chains.notOnBoard": "non sul tabellone", + "chains.safe": "sicura", + "prices.label": "Tabella dei prezzi", + "prices.show": "Tabella dei prezzi", + "prices.hide": "Nascondi la tabella dei prezzi", + "prices.minor": "Catene piccole:", + "prices.medium": "Catene medie:", + "prices.major": "Catene grandi:", + "prices.price": "Prezzo", + "prices.first": "1º", + "prices.second": "2º", + "prices.note": + "La dimensione è il numero di tessere della catena. Il segnalino di ogni catena mostra dove si trova ora.", + "players.label": "Giocatori", + "players.title": "Giocatori", + "players.player": "Giocatore", + "players.cash": "Denaro", + "players.stock": "Azioni", + "players.tiles": "Tessere", + "players.acting": "sta decidendo", + "players.you": "tu", + "players.turn": "turno", + "players.left": "uscito", + "players.none": "nessuna", + hidden: "nascosto", + "seat.name": "{name} (posto {seat})", + "log.label": "Registro della partita", + "log.title": "Registro", + "log.recent": "Mostra solo le righe recenti", + "log.all": { + one: "Mostra tutto il registro (altre {count})", + many: "Mostra tutto il registro (altre {count})", + other: "Mostra tutto il registro (altre {count})", + }, + "log.init": { + one: "Nuova partita per {count} giocatore", + many: "Nuova partita per {count} giocatori", + other: "Nuova partita per {count} giocatori", + }, + "log.optionIgnored.players": { + one: "Opzione {option} ignorata: vale solo con esattamente {count} giocatore", + many: "Opzione {option} ignorata: vale solo con esattamente {count} giocatori", + other: "Opzione {option} ignorata: vale solo con esattamente {count} giocatori", + }, + "log.optionIgnored.value": "Opzione {option} ignorata: valore sconosciuto", + "log.turnOrder": "Tessere per l'ordine di gioco: {tiles}. Inizia {name}", + "log.turn": "Turno di {name}", + "log.placed": "{name} piazza {tile}", + "log.placedAuto": "{name} piazza {tile} (automatico)", + "log.survivor": "{name} sceglie che sopravviva {chain}", + "log.survivorAuto": "{name} sceglie che sopravviva {chain} (automatico)", + "log.order": "{name} sceglie l'ordine {chains}", + "log.orderAuto": "{name} sceglie l'ordine {chains} (automatico)", + "log.skipPlace": "{name} non piazza tessere", + "log.founded": "{name} fonda {chain} ({tiles}) e riceve un'azione gratuita", + "log.foundedNoShare": "{name} fonda {chain} ({tiles}); non restavano azioni gratuite", + "log.grew": "{chain} cresce a {tiles}", + "log.merger": "La tessera {tile} di {name} fonde {chains}", + "log.mergerBank": "La tessera {tile} della banca fonde {chains}", + "log.mergerPlan": "{survivor} sopravvive e assorbe {chains}", + "log.bonuses": "Premi di {chain} a dimensione {size}: {payouts}", + "log.bonusesNobody": "Premi di {chain} a dimensione {size}: nessuno pagato", + "log.bankHeld": { + one: "; la banca aveva {count} azione (ha pescato {tile})", + many: "; la banca aveva {count} azioni (ha pescato {tile})", + other: "; la banca aveva {count} azioni (ha pescato {tile})", + }, + "log.bankHeldEmpty": "; la banca aveva 0 azioni (riserva vuota)", + "log.bankKept": " e ha tenuto {amount}", + "log.shares": { + one: "{count} azione {chain}", + many: "{count} azioni {chain}", + other: "{count} azioni {chain}", + }, + "log.sold": "vende {shares} per {amount}", + "log.traded": "scambia {shares} con {count} della sopravvissuta", + "log.kept": "tiene {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} non aveva nulla da liquidare", + "log.merged": "{chain} ora ha {tiles}", + "log.bankLoose": "La tessera {tile} della banca resta isolata", + "log.bankJoined": "La tessera {tile} della banca si unisce a una catena", + "log.bankMerger": "La tessera {tile} della banca causa una fusione", + "log.bankRemoved": "La tessera {tile} della banca non può essere giocata e viene rimossa", + "log.bought": "{name} compra {shares} per {cost}", + "log.boughtNothing": "{name} non compra azioni", + "log.discarded": "{name} scarta tessere ingiocabili: {tiles}", + "log.drew": { + one: "{name} pesca una tessera", + many: "{name} pesca {count} tessere", + other: "{name} pesca {count} tessere", + }, + "log.dropped": "{name} ha lasciato la partita", + "log.announced": "{name} annuncia la fine della partita", + "log.end.announced": "Partita finita: è stata annunciata la fine", + "log.end.condition": "Partita finita: è stata raggiunta una condizione di fine", + "log.end.stall": "Partita finita: un giro intero senza tessere piazzate", + "log.end.dropped": "Partita finita: è rimasto un solo giocatore", + "log.finalSale": "{name} vende {count} {chain} per {amount}", + "log.result": "Denaro finale: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Messaggio", + "chat.placeholder": "Messaggio…", + "chat.send": "Invia", + "chat.sending": "Invio…", + "chat.empty": "Ancora nessun messaggio.", + "chat.edited": "modificato", +}; diff --git a/packages/viewer/src/lib/locales/ko.ts b/packages/viewer/src/lib/locales/ko.ts new file mode 100644 index 0000000..831db84 --- /dev/null +++ b/packages/viewer/src/lib/locales/ko.ts @@ -0,0 +1,162 @@ +import type { Catalog } from "../i18n.ts"; + +export const ko: Catalog = { + loading: "게임을 불러오는 중…", + "status.place": "{name}: 타일을 놓을 차례", + "status.found": "{name}: 새 체인의 이름을 정할 차례", + "status.survivor": "{name}: 합병에서 살아남을 체인을 고를 차례", + "status.defunctOrder": "{name}: 흡수되는 체인의 순서를 정할 차례", + "status.dispose": "{name}: {chain} 주식을 팔기, 교환하기 또는 보유하기", + "status.buy": "{name}: 주식을 살 차례", + "status.gameOver": "게임 종료", + "status.yourDecision": "내 결정", + "status.announced": "게임 종료가 선언되었습니다. 이번 턴이 끝나면 게임이 끝납니다.", + "status.replay": "다시 보기: {turn}턴", + "status.replayNote": "이전 상황을 보고 있습니다. 손에 든 타일은 표시되지 않습니다.", + "panel.label": "내 결정", + "panel.sending": "보내는 중…", + "announce.ask": "이번 턴이 끝나면 게임을 끝낼까요? 되돌릴 수 없습니다.", + "announce.confirm": "종료 선언", + "announce.cancel": "계속 플레이", + "announce.open": "종료 선언…", + "place.effect": "{tile}: {effect}.", + "place.loose": "따로 놓입니다 (이웃한 타일 없음)", + "place.found": "새 체인을 세웁니다", + "place.joins": "{chain}에 합류합니다", + "place.merges": "{chains}을(를) 합병합니다", + "place.button": "{tile} 놓기", + "place.another": "다른 타일 고르기", + "place.choose": "손에서 타일 하나를 고르세요.", + "place.none": "놓을 수 있는 타일이 없습니다.", + "place.pass": "놓지 않고 계속하기", + "found.prompt": "새 체인의 이름을 고르세요. 무료 주식 1주를 받습니다.", + "survivor.prompt": "이 체인들이 가장 크고 크기가 같습니다. 살아남을 체인을 고르세요.", + tiles: { other: "타일 {count}개" }, + "order.prompt": + "{survivor}이(가) 살아남습니다. 흡수되는 체인 중 크기가 같은 것이 있습니다. 처음부터 마지막까지 정산할 순서를 고르세요.", + "order.confirm": "순서 확정", + "order.reset": "다시 고르기", + "dispose.takenOver": "{survivor}이(가) {defunct}을(를) 흡수합니다.", + "dispose.holding": { other: "{chain} 주식을 {count}주 가지고 있습니다." }, + "dispose.sell": "{price}에 팔기", + "dispose.trade": "2주를 1주로 교환", + "dispose.keep": "보유", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "{chain}이(가) 다시 세워지지 않으면 가치 없음", + "dispose.sellFewer": "1주 덜 팔기", + "dispose.sellMore": "1주 더 팔기", + "dispose.tradeFewer": "2주 덜 교환", + "dispose.tradeMore": "2주 더 교환", + "dispose.confirm": "확정", + "buy.prompt": "주식을 최대 3주까지 사세요. 이번 턴에는 가격이 바뀌지 않습니다.", + "buy.chain": "체인", + "buy.price": "가격", + "buy.bank": "은행", + "buy.buy": "구매", + "buy.fewer": "{chain} 주식 1주 빼기", + "buy.more": "{chain} 주식 1주 더하기", + "buy.total": "3주 중 {count}주 · 비용 {cost} · 남는 돈 {cash}", + "buy.nothing": "사지 않고 턴 끝내기", + "buy.confirm": "{cost}에 사고 턴 끝내기", + "board.label": "게임판", + "board.empty": "{tile} 빈칸", + "board.loose": "{tile} 따로 놓인 타일", + "board.chain": "{tile} {chain}", + "board.place": "{tile} 놓기", + "hand.yours": "내 타일", + "hand.seat": "타일, {seat}번 자리", + "hand.of": "{name}의 타일", + "hand.none": "타일 없음", + "hand.dead": "죽은 타일: 안전한 체인끼리 합병하게 됨", + "hand.eighth": "8번째 체인은 세울 수 없음", + "chains.label": "호텔 체인", + "chains.title": "체인", + "chains.chain": "체인", + "chains.size": "크기", + "chains.price": "가격", + "chains.bank": "은행", + "chains.yours": "내 주식", + "chains.notOnBoard": "게임판에 없음", + "chains.safe": "안전", + "prices.label": "가격표", + "prices.show": "가격표", + "prices.hide": "가격표 숨기기", + "prices.minor": "소형 체인:", + "prices.medium": "중형 체인:", + "prices.major": "대형 체인:", + "prices.price": "가격", + "prices.first": "1위", + "prices.second": "2위", + "prices.note": "크기는 체인의 타일 수입니다. 체인 표시는 지금 위치를 보여 줍니다.", + "players.label": "플레이어", + "players.title": "플레이어", + "players.player": "플레이어", + "players.cash": "현금", + "players.stock": "주식", + "players.tiles": "타일", + "players.acting": "결정 중", + "players.you": "나", + "players.turn": "차례", + "players.left": "나감", + "players.none": "없음", + hidden: "비공개", + "seat.name": "{name} ({seat}번 자리)", + "log.label": "게임 기록", + "log.title": "기록", + "log.recent": "최근 줄만 보기", + "log.all": { other: "전체 기록 보기 ({count}줄 더)" }, + "log.init": { other: "{count}인 새 게임" }, + "log.optionIgnored.players": { other: "{option} 옵션 무시됨: 정확히 {count}명일 때만 적용됩니다" }, + "log.optionIgnored.value": "{option} 옵션 무시됨: 알 수 없는 값", + "log.turnOrder": "순서 정하기 타일: {tiles}. {name}부터 시작", + "log.turn": "{name}의 차례", + "log.placed": "{name}: {tile} 놓음", + "log.placedAuto": "{name}: {tile} 놓음 (자동)", + "log.survivor": "{name}: {chain}을(를) 살리기로 선택", + "log.survivorAuto": "{name}: {chain}을(를) 살리기로 선택 (자동)", + "log.order": "{name}: 순서 {chains} 선택", + "log.orderAuto": "{name}: 순서 {chains} 선택 (자동)", + "log.skipPlace": "{name}: 타일을 놓지 않음", + "log.founded": "{name}: {chain} 세움 ({tiles}), 무료 주식 받음", + "log.foundedNoShare": "{name}: {chain} 세움 ({tiles}), 남은 무료 주식 없음", + "log.grew": "{chain}이(가) {tiles}로 커짐", + "log.merger": "{name}의 {tile}이(가) {chains}을(를) 합병", + "log.mergerBank": "은행 타일 {tile}이(가) {chains}을(를) 합병", + "log.mergerPlan": "{survivor}이(가) 살아남아 {chains}을(를) 흡수", + "log.bonuses": "{chain} 보너스 (크기 {size}): {payouts}", + "log.bonusesNobody": "{chain} 보너스 (크기 {size}): 받은 사람 없음", + "log.bankHeld": { other: "; 은행은 {count}주 보유 ({tile} 뽑음)" }, + "log.bankHeldEmpty": "; 은행은 0주 보유 (타일 더미 비었음)", + "log.bankKept": ", {amount}을(를) 가짐", + "log.shares": { other: "{chain} {count}주" }, + "log.sold": "{shares}를 {amount}에 팖", + "log.traded": "{shares}를 살아남은 체인 {count}주로 교환", + "log.kept": "{shares} 보유", + "log.disposed": "{name}: {actions}", + "log.disposedNothing": "{name}: 정산할 주식 없음", + "log.merged": "{chain}의 크기는 이제 {tiles}", + "log.bankLoose": "은행 타일 {tile}이(가) 따로 놓임", + "log.bankJoined": "은행 타일 {tile}이(가) 체인에 합류", + "log.bankMerger": "은행 타일 {tile}이(가) 합병을 일으킴", + "log.bankRemoved": "은행 타일 {tile}은(는) 놓을 수 없어 제거됨", + "log.bought": "{name}: {shares}를 {cost}에 삼", + "log.boughtNothing": "{name}: 주식을 사지 않음", + "log.discarded": "{name}: 놓을 수 없는 타일 버림: {tiles}", + "log.drew": { other: "{name}: 타일 {count}개 뽑음" }, + "log.dropped": "{name}이(가) 게임을 나감", + "log.announced": "{name}이(가) 게임 종료를 선언", + "log.end.announced": "게임 종료: 종료가 선언됨", + "log.end.condition": "게임 종료: 종료 조건 충족", + "log.end.stall": "게임 종료: 한 바퀴 동안 아무도 타일을 놓지 않음", + "log.end.dropped": "게임 종료: 플레이어가 한 명만 남음", + "log.finalSale": "{name}: {chain} {count}주를 {amount}에 팖", + "log.result": "최종 현금: {results}", + "chat.label": "채팅", + "chat.title": "채팅", + "chat.message": "메시지", + "chat.placeholder": "메시지…", + "chat.send": "보내기", + "chat.sending": "보내는 중…", + "chat.empty": "아직 메시지가 없습니다.", + "chat.edited": "수정됨", +}; diff --git a/packages/viewer/src/lib/locales/nl.ts b/packages/viewer/src/lib/locales/nl.ts new file mode 100644 index 0000000..8a9a7ee --- /dev/null +++ b/packages/viewer/src/lib/locales/nl.ts @@ -0,0 +1,168 @@ +import type { Catalog } from "../i18n.ts"; + +export const nl: Catalog = { + loading: "Spel laden…", + "status.place": "{name} moet een tegel leggen", + "status.found": "{name} moet een nieuwe keten een naam geven", + "status.survivor": "{name} moet kiezen welke keten de fusie overleeft", + "status.defunctOrder": "{name} moet de volgorde van de overgenomen ketens kiezen", + "status.dispose": "{name} moet {chain}-aandelen verkopen, ruilen of houden", + "status.buy": "{name} moet aandelen kopen", + "status.gameOver": "Spel afgelopen", + "status.yourDecision": "jouw beslissing", + "status.announced": "Het einde is aangekondigd; het spel eindigt na deze beurt.", + "status.replay": "Herhaling: beurt {turn}", + "status.replayNote": "Je bekijkt een eerdere stand. Tegels in de hand worden niet getoond.", + "panel.label": "Jouw beslissing", + "panel.sending": "Versturen…", + "announce.ask": "Het spel na deze beurt beëindigen? Dit kan niet ongedaan worden gemaakt.", + "announce.confirm": "Einde aankondigen", + "announce.cancel": "Verder spelen", + "announce.open": "Einde aankondigen…", + "place.effect": "{tile}: {effect}.", + "place.loose": "ligt los (geen aangrenzende tegels)", + "place.found": "sticht een nieuwe keten", + "place.joins": "sluit aan bij {chain}", + "place.merges": "fuseert {chains}", + "place.button": "Leg {tile}", + "place.another": "Kies een andere", + "place.choose": "Kies een tegel uit je hand.", + "place.none": "Geen van je tegels kan gelegd worden.", + "place.pass": "Verder zonder te leggen", + "found.prompt": "Geef de nieuwe keten een naam. Je krijgt één gratis aandeel.", + "survivor.prompt": "Deze ketens zijn gelijk de grootste. Kies welke overleeft.", + tiles: { one: "{count} tegel", other: "{count} tegels" }, + "order.prompt": + "{survivor} overleeft. Sommige overgenomen ketens zijn even groot: kies de volgorde waarin ze worden afgehandeld, van eerste tot laatste.", + "order.confirm": "Volgorde bevestigen", + "order.reset": "Opnieuw beginnen", + "dispose.takenOver": "{defunct} wordt overgenomen door {survivor}.", + "dispose.holding": { one: "Je hebt {count} {chain}-aandeel.", other: "Je hebt {count} {chain}-aandelen." }, + "dispose.sell": "Verkopen voor {price}", + "dispose.trade": "2 voor 1 ruilen", + "dispose.keep": "Houden", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "waardeloos, tenzij {chain} opnieuw wordt gesticht", + "dispose.sellFewer": "Eén minder verkopen", + "dispose.sellMore": "Eén meer verkopen", + "dispose.tradeFewer": "Twee minder ruilen", + "dispose.tradeMore": "Twee meer ruilen", + "dispose.confirm": "Bevestigen", + "buy.prompt": "Koop tot 3 aandelen. De prijzen liggen vast tijdens deze beurt.", + "buy.chain": "Keten", + "buy.price": "Prijs", + "buy.bank": "Bank", + "buy.buy": "Kopen", + "buy.fewer": "Eén {chain}-aandeel minder", + "buy.more": "Eén {chain}-aandeel meer", + "buy.total": "{count} van 3 aandelen · kosten {cost} · over {cash}", + "buy.nothing": "Niets kopen en beurt beëindigen", + "buy.confirm": "Kopen voor {cost} en beurt beëindigen", + "board.label": "Spelbord", + "board.empty": "{tile} leeg", + "board.loose": "{tile} losse tegel", + "board.chain": "{tile} {chain}", + "board.place": "Leg {tile}", + "hand.yours": "Jouw tegels", + "hand.seat": "Tegels, plaats {seat}", + "hand.of": "Tegels van {name}", + "hand.none": "Geen tegels", + "hand.dead": "dood: zou veilige ketens fuseren", + "hand.eighth": "kan geen 8e keten stichten", + "chains.label": "Hotelketens", + "chains.title": "Ketens", + "chains.chain": "Keten", + "chains.size": "Grootte", + "chains.price": "Prijs", + "chains.bank": "Bank", + "chains.yours": "Jouw", + "chains.notOnBoard": "niet op het bord", + "chains.safe": "veilig", + "prices.label": "Prijstabel", + "prices.show": "Prijstabel", + "prices.hide": "Prijstabel verbergen", + "prices.minor": "Kleine ketens:", + "prices.medium": "Middelgrote ketens:", + "prices.major": "Grote ketens:", + "prices.price": "Prijs", + "prices.first": "1e", + "prices.second": "2e", + "prices.note": "Grootte is het aantal tegels van een keten. De markering van een keten toont waar die nu staat.", + "players.label": "Spelers", + "players.title": "Spelers", + "players.player": "Speler", + "players.cash": "Geld", + "players.stock": "Aandelen", + "players.tiles": "Tegels", + "players.acting": "is aan zet", + "players.you": "jij", + "players.turn": "beurt", + "players.left": "vertrokken", + "players.none": "geen", + hidden: "verborgen", + "seat.name": "{name} (plaats {seat})", + "log.label": "Spelverslag", + "log.title": "Verslag", + "log.recent": "Alleen recente regels tonen", + "log.all": { one: "Hele verslag tonen (nog {count})", other: "Hele verslag tonen (nog {count})" }, + "log.init": { one: "Nieuw spel voor {count} speler", other: "Nieuw spel voor {count} spelers" }, + "log.optionIgnored.players": { + one: "Optie {option} genegeerd: geldt alleen met precies {count} speler", + other: "Optie {option} genegeerd: geldt alleen met precies {count} spelers", + }, + "log.optionIgnored.value": "Optie {option} genegeerd: onbekende waarde", + "log.turnOrder": "Tegels voor de beurtvolgorde: {tiles}. {name} begint", + "log.turn": "Beurt van {name}", + "log.placed": "{name} legt {tile}", + "log.placedAuto": "{name} legt {tile} (automatisch)", + "log.survivor": "{name} kiest {chain} als overlevende", + "log.survivorAuto": "{name} kiest {chain} als overlevende (automatisch)", + "log.order": "{name} kiest de volgorde {chains}", + "log.orderAuto": "{name} kiest de volgorde {chains} (automatisch)", + "log.skipPlace": "{name} legt geen tegel", + "log.founded": "{name} sticht {chain} ({tiles}) en krijgt een gratis aandeel", + "log.foundedNoShare": "{name} sticht {chain} ({tiles}); er was geen gratis aandeel meer", + "log.grew": "{chain} groeit naar {tiles}", + "log.merger": "De {tile} van {name} fuseert {chains}", + "log.mergerBank": "Banktegel {tile} fuseert {chains}", + "log.mergerPlan": "{survivor} overleeft en neemt {chains} over", + "log.bonuses": "Bonussen van {chain} bij grootte {size}: {payouts}", + "log.bonusesNobody": "Bonussen van {chain} bij grootte {size}: niemand uitbetaald", + "log.bankHeld": { + one: "; de bank had {count} aandeel (trok {tile})", + other: "; de bank had {count} aandelen (trok {tile})", + }, + "log.bankHeldEmpty": "; de bank had 0 aandelen (voorraad leeg)", + "log.bankKept": " en hield {amount}", + "log.shares": { one: "{count} {chain}-aandeel", other: "{count} {chain}-aandelen" }, + "log.sold": "verkoopt {shares} voor {amount}", + "log.traded": "ruilt {shares} voor {count} van de overlevende keten", + "log.kept": "houdt {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} had niets af te handelen", + "log.merged": "{chain} heeft nu {tiles}", + "log.bankLoose": "Banktegel {tile} ligt los", + "log.bankJoined": "Banktegel {tile} sluit aan bij een keten", + "log.bankMerger": "Banktegel {tile} veroorzaakt een fusie", + "log.bankRemoved": "Banktegel {tile} kan niet gelegd worden en wordt verwijderd", + "log.bought": "{name} koopt {shares} voor {cost}", + "log.boughtNothing": "{name} koopt geen aandelen", + "log.discarded": "{name} legt onspeelbare tegels af: {tiles}", + "log.drew": { one: "{name} trekt een tegel", other: "{name} trekt {count} tegels" }, + "log.dropped": "{name} heeft het spel verlaten", + "log.announced": "{name} kondigt het einde van het spel aan", + "log.end.announced": "Spel afgelopen: het einde werd aangekondigd", + "log.end.condition": "Spel afgelopen: aan een eindvoorwaarde is voldaan", + "log.end.stall": "Spel afgelopen: een hele ronde zonder gelegde tegel", + "log.end.dropped": "Spel afgelopen: er bleef maar één speler over", + "log.finalSale": "{name} verkoopt {count} {chain} voor {amount}", + "log.result": "Eindbedrag: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Bericht", + "chat.placeholder": "Bericht…", + "chat.send": "Versturen", + "chat.sending": "Versturen…", + "chat.empty": "Nog geen berichten.", + "chat.edited": "bewerkt", +}; diff --git a/packages/viewer/src/lib/locales/pl.ts b/packages/viewer/src/lib/locales/pl.ts new file mode 100644 index 0000000..05b74a6 --- /dev/null +++ b/packages/viewer/src/lib/locales/pl.ts @@ -0,0 +1,197 @@ +import type { Catalog } from "../i18n.ts"; + +export const pl: Catalog = { + loading: "Wczytywanie gry…", + "status.place": "{name} kładzie płytkę", + "status.found": "{name} nazywa nową sieć", + "status.survivor": "{name} wybiera sieć, która przetrwa fuzję", + "status.defunctOrder": "{name} wybiera kolejność przejmowanych sieci", + "status.dispose": "{name} sprzedaje, wymienia lub zatrzymuje akcje {chain}", + "status.buy": "{name} kupuje akcje", + "status.gameOver": "Koniec gry", + "status.yourDecision": "twoja decyzja", + "status.announced": "Ogłoszono koniec gry; gra kończy się po tej turze.", + "status.replay": "Powtórka: tura {turn}", + "status.replayNote": "Oglądasz wcześniejszą pozycję. Płytki na ręce nie są pokazywane.", + "panel.label": "Twoja decyzja", + "panel.sending": "Wysyłanie…", + "announce.ask": "Zakończyć grę po tej turze? Tego nie można cofnąć.", + "announce.confirm": "Ogłoś koniec gry", + "announce.cancel": "Graj dalej", + "announce.open": "Ogłoś koniec gry…", + "place.effect": "{tile}: {effect}.", + "place.loose": "zostaje pojedyncza (brak sąsiednich płytek)", + "place.found": "zakłada nową sieć", + "place.joins": "dołącza do {chain}", + "place.merges": "łączy {chains}", + "place.button": "Połóż {tile}", + "place.another": "Wybierz inną", + "place.choose": "Wybierz płytkę z ręki.", + "place.none": "Żadnej z twoich płytek nie można położyć.", + "place.pass": "Kontynuuj bez kładzenia", + "found.prompt": "Nazwij nową sieć. Otrzymujesz jedną darmową akcję.", + "survivor.prompt": "Te sieci są równie duże i największe. Wybierz, która przetrwa.", + tiles: { one: "{count} płytka", few: "{count} płytki", many: "{count} płytek", other: "{count} płytki" }, + "order.prompt": + "{survivor} przetrwa. Niektóre przejmowane sieci są tej samej wielkości: wybierz kolejność ich rozliczenia, od pierwszej do ostatniej.", + "order.confirm": "Potwierdź kolejność", + "order.reset": "Zacznij od nowa", + "dispose.takenOver": "{survivor} przejmuje {defunct}.", + "dispose.holding": { + one: "Masz {count} akcję {chain}.", + few: "Masz {count} akcje {chain}.", + many: "Masz {count} akcji {chain}.", + other: "Masz {count} akcji {chain}.", + }, + "dispose.sell": "Sprzedaj po {price}", + "dispose.trade": "Wymień 2 za 1", + "dispose.keep": "Zatrzymaj", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "bez wartości, chyba że {chain} zostanie założona ponownie", + "dispose.sellFewer": "Sprzedaj o jedną mniej", + "dispose.sellMore": "Sprzedaj o jedną więcej", + "dispose.tradeFewer": "Wymień o dwie mniej", + "dispose.tradeMore": "Wymień o dwie więcej", + "dispose.confirm": "Potwierdź", + "buy.prompt": "Kup do 3 akcji. Ceny nie zmieniają się w tej turze.", + "buy.chain": "Sieć", + "buy.price": "Cena", + "buy.bank": "Bank", + "buy.buy": "Kup", + "buy.fewer": "Kup o jedną akcję {chain} mniej", + "buy.more": "Kup o jedną akcję {chain} więcej", + "buy.total": "{count} z 3 akcji · koszt {cost} · zostaje {cash}", + "buy.nothing": "Nic nie kupuj i zakończ turę", + "buy.confirm": "Kup za {cost} i zakończ turę", + "board.label": "Plansza", + "board.empty": "{tile} puste", + "board.loose": "{tile} pojedyncza płytka", + "board.chain": "{tile} {chain}", + "board.place": "Połóż {tile}", + "hand.yours": "Twoje płytki", + "hand.seat": "Płytki, miejsce {seat}", + "hand.of": "Płytki gracza {name}", + "hand.none": "Brak płytek", + "hand.dead": "martwa: połączyłaby bezpieczne sieci", + "hand.eighth": "nie można założyć 8. sieci", + "chains.label": "Sieci hoteli", + "chains.title": "Sieci", + "chains.chain": "Sieć", + "chains.size": "Wielkość", + "chains.price": "Cena", + "chains.bank": "Bank", + "chains.yours": "Twoje", + "chains.notOnBoard": "poza planszą", + "chains.safe": "bezpieczna", + "prices.label": "Tabela cen", + "prices.show": "Tabela cen", + "prices.hide": "Ukryj tabelę cen", + "prices.minor": "Małe sieci:", + "prices.medium": "Średnie sieci:", + "prices.major": "Duże sieci:", + "prices.price": "Cena", + "prices.first": "1.", + "prices.second": "2.", + "prices.note": "Wielkość to liczba płytek w sieci. Znacznik sieci pokazuje, gdzie teraz jest.", + "players.label": "Gracze", + "players.title": "Gracze", + "players.player": "Gracz", + "players.cash": "Gotówka", + "players.stock": "Akcje", + "players.tiles": "Płytki", + "players.acting": "teraz działa", + "players.you": "ty", + "players.turn": "tura", + "players.left": "odszedł", + "players.none": "brak", + hidden: "ukryte", + "seat.name": "{name} (miejsce {seat})", + "log.label": "Dziennik gry", + "log.title": "Dziennik", + "log.recent": "Pokaż tylko ostatnie wpisy", + "log.all": { + one: "Pokaż cały dziennik (jeszcze {count})", + few: "Pokaż cały dziennik (jeszcze {count})", + many: "Pokaż cały dziennik (jeszcze {count})", + other: "Pokaż cały dziennik (jeszcze {count})", + }, + "log.init": { + one: "Nowa gra dla {count} gracza", + few: "Nowa gra dla {count} graczy", + many: "Nowa gra dla {count} graczy", + other: "Nowa gra dla {count} gracza", + }, + "log.optionIgnored.players": { + one: "Opcję {option} pominięto: działa tylko przy dokładnie {count} graczu", + few: "Opcję {option} pominięto: działa tylko przy dokładnie {count} graczach", + many: "Opcję {option} pominięto: działa tylko przy dokładnie {count} graczach", + other: "Opcję {option} pominięto: działa tylko przy dokładnie {count} graczach", + }, + "log.optionIgnored.value": "Opcję {option} pominięto: nieznana wartość", + "log.turnOrder": "Płytki kolejności: {tiles}. Zaczyna {name}", + "log.turn": "Tura: {name}", + "log.placed": "{name} kładzie {tile}", + "log.placedAuto": "{name} kładzie {tile} (automatycznie)", + "log.survivor": "{name} wybiera {chain} jako sieć przetrwałą", + "log.survivorAuto": "{name} wybiera {chain} jako sieć przetrwałą (automatycznie)", + "log.order": "{name} wybiera kolejność {chains}", + "log.orderAuto": "{name} wybiera kolejność {chains} (automatycznie)", + "log.skipPlace": "{name} nie kładzie płytki", + "log.founded": "{name} zakłada {chain} ({tiles}) i otrzymuje darmową akcję", + "log.foundedNoShare": "{name} zakłada {chain} ({tiles}); nie było już darmowej akcji", + "log.grew": "{chain} rośnie i ma teraz {tiles}", + "log.merger": "Płytka {tile} gracza {name} łączy {chains}", + "log.mergerBank": "Płytka banku {tile} łączy {chains}", + "log.mergerPlan": "{survivor} przetrwa i przejmuje {chains}", + "log.bonuses": "Premie za {chain} przy wielkości {size}: {payouts}", + "log.bonusesNobody": "Premie za {chain} przy wielkości {size}: nikt nie otrzymuje", + "log.bankHeld": { + one: "; bank miał {count} akcję (dobrał {tile})", + few: "; bank miał {count} akcje (dobrał {tile})", + many: "; bank miał {count} akcji (dobrał {tile})", + other: "; bank miał {count} akcji (dobrał {tile})", + }, + "log.bankHeldEmpty": "; bank miał 0 akcji (pula pusta)", + "log.bankKept": " i zatrzymał {amount}", + "log.shares": { + one: "{count} akcję {chain}", + few: "{count} akcje {chain}", + many: "{count} akcji {chain}", + other: "{count} akcji {chain}", + }, + "log.sold": "sprzedaje {shares} za {amount}", + "log.traded": "wymienia {shares} na {count} akcji sieci przetrwałej", + "log.kept": "zatrzymuje {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} nie miał(a) nic do rozliczenia", + "log.merged": "{chain} ma teraz {tiles}", + "log.bankLoose": "Płytka banku {tile} zostaje pojedyncza", + "log.bankJoined": "Płytka banku {tile} dołącza do sieci", + "log.bankMerger": "Płytka banku {tile} powoduje fuzję", + "log.bankRemoved": "Płytki banku {tile} nie można położyć i zostaje usunięta", + "log.bought": "{name} kupuje {shares} za {cost}", + "log.boughtNothing": "{name} nie kupuje akcji", + "log.discarded": "{name} odrzuca niezagrywalne płytki: {tiles}", + "log.drew": { + one: "{name} dobiera płytkę", + few: "{name} dobiera {count} płytki", + many: "{name} dobiera {count} płytek", + other: "{name} dobiera {count} płytki", + }, + "log.dropped": "{name} opuścił(a) grę", + "log.announced": "{name} ogłasza koniec gry", + "log.end.announced": "Koniec gry: ogłoszono koniec", + "log.end.condition": "Koniec gry: spełniono warunek końca", + "log.end.stall": "Koniec gry: przez całą rundę nikt nie położył płytki", + "log.end.dropped": "Koniec gry: został tylko jeden gracz", + "log.finalSale": "{name} sprzedaje {count} {chain} za {amount}", + "log.result": "Gotówka na koniec: {results}", + "chat.label": "Czat", + "chat.title": "Czat", + "chat.message": "Wiadomość", + "chat.placeholder": "Wiadomość…", + "chat.send": "Wyślij", + "chat.sending": "Wysyłanie…", + "chat.empty": "Brak wiadomości.", + "chat.edited": "edytowano", +}; diff --git a/packages/viewer/src/lib/locales/pt-BR.ts b/packages/viewer/src/lib/locales/pt-BR.ts new file mode 100644 index 0000000..1d91cb6 --- /dev/null +++ b/packages/viewer/src/lib/locales/pt-BR.ts @@ -0,0 +1,190 @@ +import type { Catalog } from "../i18n.ts"; + +export const ptBR: Catalog = { + loading: "Carregando o jogo…", + "status.place": "{name} deve colocar uma peça", + "status.found": "{name} deve dar nome a uma nova rede", + "status.survivor": "{name} deve escolher qual rede sobrevive à fusão", + "status.defunctOrder": "{name} deve escolher a ordem das redes absorvidas", + "status.dispose": "{name} deve vender, trocar ou manter ações da {chain}", + "status.buy": "{name} deve comprar ações", + "status.gameOver": "Fim de jogo", + "status.yourDecision": "sua decisão", + "status.announced": "O fim do jogo foi anunciado; ele termina depois deste turno.", + "status.replay": "Replay: turno {turn}", + "status.replayNote": "Você está vendo uma posição anterior. As peças na mão não são mostradas.", + "panel.label": "Sua decisão", + "panel.sending": "Enviando…", + "announce.ask": "Encerrar o jogo depois deste turno? Não dá para desfazer.", + "announce.confirm": "Anunciar o fim", + "announce.cancel": "Continuar jogando", + "announce.open": "Anunciar o fim…", + "place.effect": "{tile}: {effect}.", + "place.loose": "fica isolada (sem peças vizinhas)", + "place.found": "funda uma nova rede", + "place.joins": "entra na {chain}", + "place.merges": "funde {chains}", + "place.button": "Colocar {tile}", + "place.another": "Escolher outra", + "place.choose": "Escolha uma peça da sua mão.", + "place.none": "Nenhuma das suas peças pode ser colocada.", + "place.pass": "Continuar sem colocar", + "found.prompt": "Dê nome à nova rede. Você recebe uma ação grátis.", + "survivor.prompt": "Estas redes empatam como as maiores. Escolha qual sobrevive.", + tiles: { one: "{count} peça", many: "{count} peças", other: "{count} peças" }, + "order.prompt": + "A {survivor} sobrevive. Algumas redes absorvidas têm o mesmo tamanho: escolha a ordem em que são liquidadas, da primeira à última.", + "order.confirm": "Confirmar a ordem", + "order.reset": "Recomeçar", + "dispose.takenOver": "A {defunct} é absorvida pela {survivor}.", + "dispose.holding": { + one: "Você tem {count} ação da {chain}.", + many: "Você tem {count} ações da {chain}.", + other: "Você tem {count} ações da {chain}.", + }, + "dispose.sell": "Vender a {price}", + "dispose.trade": "Trocar 2 por 1", + "dispose.keep": "Manter", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "sem valor, a menos que a {chain} seja fundada de novo", + "dispose.sellFewer": "Vender uma a menos", + "dispose.sellMore": "Vender uma a mais", + "dispose.tradeFewer": "Trocar duas a menos", + "dispose.tradeMore": "Trocar duas a mais", + "dispose.confirm": "Confirmar", + "buy.prompt": "Compre até 3 ações. Os preços ficam fixos neste turno.", + "buy.chain": "Rede", + "buy.price": "Preço", + "buy.bank": "Banco", + "buy.buy": "Comprar", + "buy.fewer": "Uma ação da {chain} a menos", + "buy.more": "Uma ação da {chain} a mais", + "buy.total": "{count} de 3 ações · custo {cost} · sobra {cash}", + "buy.nothing": "Não comprar nada e encerrar o turno", + "buy.confirm": "Comprar por {cost} e encerrar o turno", + "board.label": "Tabuleiro", + "board.empty": "{tile} vazia", + "board.loose": "{tile} peça isolada", + "board.chain": "{tile} {chain}", + "board.place": "Colocar {tile}", + "hand.yours": "Suas peças", + "hand.seat": "Peças, lugar {seat}", + "hand.of": "Peças de {name}", + "hand.none": "Nenhuma peça", + "hand.dead": "morta: fundiria redes seguras", + "hand.eighth": "não dá para fundar uma 8ª rede", + "chains.label": "Redes de hotéis", + "chains.title": "Redes", + "chains.chain": "Rede", + "chains.size": "Tamanho", + "chains.price": "Preço", + "chains.bank": "Banco", + "chains.yours": "Suas", + "chains.notOnBoard": "fora do tabuleiro", + "chains.safe": "segura", + "prices.label": "Tabela de preços", + "prices.show": "Tabela de preços", + "prices.hide": "Ocultar tabela de preços", + "prices.minor": "Redes pequenas:", + "prices.medium": "Redes médias:", + "prices.major": "Redes grandes:", + "prices.price": "Preço", + "prices.first": "1º", + "prices.second": "2º", + "prices.note": "O tamanho é o número de peças da rede. O marcador de cada rede mostra onde ela está agora.", + "players.label": "Jogadores", + "players.title": "Jogadores", + "players.player": "Jogador", + "players.cash": "Dinheiro", + "players.stock": "Ações", + "players.tiles": "Peças", + "players.acting": "jogando agora", + "players.you": "você", + "players.turn": "vez", + "players.left": "saiu", + "players.none": "nenhuma", + hidden: "oculto", + "seat.name": "{name} (lugar {seat})", + "log.label": "Registro do jogo", + "log.title": "Registro", + "log.recent": "Mostrar só as linhas recentes", + "log.all": { + one: "Mostrar o registro inteiro (mais {count})", + many: "Mostrar o registro inteiro (mais {count})", + other: "Mostrar o registro inteiro (mais {count})", + }, + "log.init": { + one: "Novo jogo para {count} jogador", + many: "Novo jogo para {count} jogadores", + other: "Novo jogo para {count} jogadores", + }, + "log.optionIgnored.players": { + one: "A opção {option} foi ignorada: só vale com exatamente {count} jogador", + many: "A opção {option} foi ignorada: só vale com exatamente {count} jogadores", + other: "A opção {option} foi ignorada: só vale com exatamente {count} jogadores", + }, + "log.optionIgnored.value": "A opção {option} foi ignorada: valor desconhecido", + "log.turnOrder": "Peças da ordem de jogo: {tiles}. {name} começa", + "log.turn": "Vez de {name}", + "log.placed": "{name} colocou {tile}", + "log.placedAuto": "{name} colocou {tile} (automático)", + "log.survivor": "{name} escolheu a {chain} para sobreviver", + "log.survivorAuto": "{name} escolheu a {chain} para sobreviver (automático)", + "log.order": "{name} escolheu a ordem {chains}", + "log.orderAuto": "{name} escolheu a ordem {chains} (automático)", + "log.skipPlace": "{name} não colocou peça", + "log.founded": "{name} fundou a {chain} ({tiles}) e recebeu uma ação grátis", + "log.foundedNoShare": "{name} fundou a {chain} ({tiles}); não restava ação grátis", + "log.grew": "A {chain} cresceu para {tiles}", + "log.merger": "A peça {tile} de {name} funde {chains}", + "log.mergerBank": "A peça {tile} do banco funde {chains}", + "log.mergerPlan": "A {survivor} sobrevive e absorve {chains}", + "log.bonuses": "Bônus da {chain} no tamanho {size}: {payouts}", + "log.bonusesNobody": "Bônus da {chain} no tamanho {size}: ninguém recebeu", + "log.bankHeld": { + one: "; o banco tinha {count} ação (tirou {tile})", + many: "; o banco tinha {count} ações (tirou {tile})", + other: "; o banco tinha {count} ações (tirou {tile})", + }, + "log.bankHeldEmpty": "; o banco tinha 0 ações (monte vazio)", + "log.bankKept": " e ficou com {amount}", + "log.shares": { + one: "{count} ação da {chain}", + many: "{count} ações da {chain}", + other: "{count} ações da {chain}", + }, + "log.sold": "vendeu {shares} por {amount}", + "log.traded": "trocou {shares} por {count} da sobrevivente", + "log.kept": "manteve {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} não tinha nada para liquidar", + "log.merged": "A {chain} agora tem {tiles}", + "log.bankLoose": "A peça {tile} do banco fica isolada", + "log.bankJoined": "A peça {tile} do banco entra numa rede", + "log.bankMerger": "A peça {tile} do banco causa uma fusão", + "log.bankRemoved": "A peça {tile} do banco não pode ser jogada e é removida", + "log.bought": "{name} comprou {shares} por {cost}", + "log.boughtNothing": "{name} não comprou ações", + "log.discarded": "{name} descartou peças injogáveis: {tiles}", + "log.drew": { + one: "{name} comprou uma peça", + many: "{name} comprou {count} peças", + other: "{name} comprou {count} peças", + }, + "log.dropped": "{name} saiu do jogo", + "log.announced": "{name} anunciou o fim do jogo", + "log.end.announced": "Fim de jogo: o fim foi anunciado", + "log.end.condition": "Fim de jogo: uma condição de fim foi atingida", + "log.end.stall": "Fim de jogo: uma rodada inteira passou sem nenhuma peça colocada", + "log.end.dropped": "Fim de jogo: restou só um jogador", + "log.finalSale": "{name} vendeu {count} {chain} por {amount}", + "log.result": "Dinheiro final: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Mensagem", + "chat.placeholder": "Mensagem…", + "chat.send": "Enviar", + "chat.sending": "Enviando…", + "chat.empty": "Nenhuma mensagem ainda.", + "chat.edited": "editada", +}; diff --git a/packages/viewer/src/lib/locales/ro.ts b/packages/viewer/src/lib/locales/ro.ts new file mode 100644 index 0000000..002881c --- /dev/null +++ b/packages/viewer/src/lib/locales/ro.ts @@ -0,0 +1,190 @@ +import type { Catalog } from "../i18n.ts"; + +export const ro: Catalog = { + loading: "Se încarcă jocul…", + "status.place": "{name} trebuie să plaseze o piesă", + "status.found": "{name} trebuie să numească un lanț nou", + "status.survivor": "{name} trebuie să aleagă lanțul care supraviețuiește fuziunii", + "status.defunctOrder": "{name} trebuie să aleagă ordinea lanțurilor absorbite", + "status.dispose": "{name} trebuie să vândă, să schimbe sau să păstreze acțiuni {chain}", + "status.buy": "{name} trebuie să cumpere acțiuni", + "status.gameOver": "Joc încheiat", + "status.yourDecision": "decizia ta", + "status.announced": "Sfârșitul jocului a fost anunțat; jocul se încheie după această tură.", + "status.replay": "Reluare: tura {turn}", + "status.replayNote": "Vezi o poziție anterioară. Piesele din mână nu sunt afișate.", + "panel.label": "Decizia ta", + "panel.sending": "Se trimite…", + "announce.ask": "Încheiem jocul după această tură? Nu se poate anula.", + "announce.confirm": "Anunță sfârșitul", + "announce.cancel": "Continuă jocul", + "announce.open": "Anunță sfârșitul…", + "place.effect": "{tile}: {effect}.", + "place.loose": "rămâne izolată (nicio piesă vecină)", + "place.found": "înființează un lanț nou", + "place.joins": "se alătură lanțului {chain}", + "place.merges": "unește {chains}", + "place.button": "Plasează {tile}", + "place.another": "Alege alta", + "place.choose": "Alege o piesă din mână.", + "place.none": "Niciuna dintre piesele tale nu poate fi plasată.", + "place.pass": "Continuă fără să plasezi", + "found.prompt": "Numește lanțul nou. Primești o acțiune gratuită.", + "survivor.prompt": "Aceste lanțuri sunt la egalitate ca cele mai mari. Alege care supraviețuiește.", + tiles: { one: "{count} piesă", few: "{count} piese", other: "{count} de piese" }, + "order.prompt": + "{survivor} supraviețuiește. Unele lanțuri absorbite au aceeași mărime: alege ordinea în care sunt decontate, de la primul la ultimul.", + "order.confirm": "Confirmă ordinea", + "order.reset": "Ia de la capăt", + "dispose.takenOver": "{defunct} este preluat de {survivor}.", + "dispose.holding": { + one: "Deții {count} acțiune {chain}.", + few: "Deții {count} acțiuni {chain}.", + other: "Deții {count} de acțiuni {chain}.", + }, + "dispose.sell": "Vinde la {price}", + "dispose.trade": "Schimbă 2 pe 1", + "dispose.keep": "Păstrează", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "fără valoare, cu excepția cazului în care {chain} este înființat din nou", + "dispose.sellFewer": "Vinde una mai puțin", + "dispose.sellMore": "Vinde una în plus", + "dispose.tradeFewer": "Schimbă două mai puțin", + "dispose.tradeMore": "Schimbă două în plus", + "dispose.confirm": "Confirmă", + "buy.prompt": "Cumpără până la 3 acțiuni. Prețurile rămân fixe în această tură.", + "buy.chain": "Lanț", + "buy.price": "Preț", + "buy.bank": "Bancă", + "buy.buy": "Cumpără", + "buy.fewer": "Cumpără o acțiune {chain} mai puțin", + "buy.more": "Cumpără o acțiune {chain} în plus", + "buy.total": "{count} din 3 acțiuni · cost {cost} · bani rămași {cash}", + "buy.nothing": "Nu cumpăra nimic și încheie tura", + "buy.confirm": "Cumpără cu {cost} și încheie tura", + "board.label": "Tablă", + "board.empty": "{tile} liber", + "board.loose": "{tile} piesă izolată", + "board.chain": "{tile} {chain}", + "board.place": "Plasează {tile}", + "hand.yours": "Piesele tale", + "hand.seat": "Piese, locul {seat}", + "hand.of": "Piesele lui {name}", + "hand.none": "Nicio piesă", + "hand.dead": "moartă: ar uni lanțuri sigure", + "hand.eighth": "nu se poate înființa un al 8-lea lanț", + "chains.label": "Lanțuri hoteliere", + "chains.title": "Lanțuri", + "chains.chain": "Lanț", + "chains.size": "Mărime", + "chains.price": "Preț", + "chains.bank": "Bancă", + "chains.yours": "Ale tale", + "chains.notOnBoard": "nu e pe tablă", + "chains.safe": "sigur", + "prices.label": "Tabelul prețurilor", + "prices.show": "Tabelul prețurilor", + "prices.hide": "Ascunde tabelul prețurilor", + "prices.minor": "Lanțuri mici:", + "prices.medium": "Lanțuri medii:", + "prices.major": "Lanțuri mari:", + "prices.price": "Preț", + "prices.first": "Locul 1", + "prices.second": "Locul 2", + "prices.note": "Mărimea este numărul de piese al lanțului. Marcajul unui lanț arată unde se află acum.", + "players.label": "Jucători", + "players.title": "Jucători", + "players.player": "Jucător", + "players.cash": "Bani", + "players.stock": "Acțiuni", + "players.tiles": "Piese", + "players.acting": "acționează acum", + "players.you": "tu", + "players.turn": "la rând", + "players.left": "a plecat", + "players.none": "niciuna", + hidden: "ascuns", + "seat.name": "{name} (locul {seat})", + "log.label": "Jurnalul jocului", + "log.title": "Jurnal", + "log.recent": "Arată doar ultimele rânduri", + "log.all": { + one: "Arată tot jurnalul (încă {count})", + few: "Arată tot jurnalul (încă {count})", + other: "Arată tot jurnalul (încă {count})", + }, + "log.init": { + one: "Joc nou pentru {count} jucător", + few: "Joc nou pentru {count} jucători", + other: "Joc nou pentru {count} de jucători", + }, + "log.optionIgnored.players": { + one: "Opțiunea {option} a fost ignorată: se aplică doar cu exact {count} jucător", + few: "Opțiunea {option} a fost ignorată: se aplică doar cu exact {count} jucători", + other: "Opțiunea {option} a fost ignorată: se aplică doar cu exact {count} de jucători", + }, + "log.optionIgnored.value": "Opțiunea {option} a fost ignorată: valoare necunoscută", + "log.turnOrder": "Piese pentru ordinea de joc: {tiles}. Începe {name}", + "log.turn": "Rândul lui {name}", + "log.placed": "{name} plasează {tile}", + "log.placedAuto": "{name} plasează {tile} (automat)", + "log.survivor": "{name} alege ca {chain} să supraviețuiască", + "log.survivorAuto": "{name} alege ca {chain} să supraviețuiască (automat)", + "log.order": "{name} alege ordinea {chains}", + "log.orderAuto": "{name} alege ordinea {chains} (automat)", + "log.skipPlace": "{name} nu plasează nicio piesă", + "log.founded": "{name} înființează {chain} ({tiles}) și primește o acțiune gratuită", + "log.foundedNoShare": "{name} înființează {chain} ({tiles}); nu mai era nicio acțiune gratuită", + "log.grew": "{chain} crește la {tiles}", + "log.merger": "Piesa {tile} a lui {name} unește {chains}", + "log.mergerBank": "Piesa băncii {tile} unește {chains}", + "log.mergerPlan": "{survivor} supraviețuiește și preia {chains}", + "log.bonuses": "Prime pentru {chain} la mărimea {size}: {payouts}", + "log.bonusesNobody": "Prime pentru {chain} la mărimea {size}: nimeni nu primește", + "log.bankHeld": { + one: "; banca deținea {count} acțiune (a tras {tile})", + few: "; banca deținea {count} acțiuni (a tras {tile})", + other: "; banca deținea {count} de acțiuni (a tras {tile})", + }, + "log.bankHeldEmpty": "; banca deținea 0 acțiuni (rezerva goală)", + "log.bankKept": " și a păstrat {amount}", + "log.shares": { + one: "{count} acțiune {chain}", + few: "{count} acțiuni {chain}", + other: "{count} de acțiuni {chain}", + }, + "log.sold": "vinde {shares} pentru {amount}", + "log.traded": "schimbă {shares} pe {count} ale lanțului care supraviețuiește", + "log.kept": "păstrează {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} nu avea nimic de decontat", + "log.merged": "{chain} are acum {tiles}", + "log.bankLoose": "Piesa băncii {tile} rămâne izolată", + "log.bankJoined": "Piesa băncii {tile} se alătură unui lanț", + "log.bankMerger": "Piesa băncii {tile} provoacă o fuziune", + "log.bankRemoved": "Piesa băncii {tile} nu poate fi jucată și este eliminată", + "log.bought": "{name} cumpără {shares} cu {cost}", + "log.boughtNothing": "{name} nu cumpără acțiuni", + "log.discarded": "{name} aruncă piese care nu pot fi jucate: {tiles}", + "log.drew": { + one: "{name} trage o piesă", + few: "{name} trage {count} piese", + other: "{name} trage {count} de piese", + }, + "log.dropped": "{name} a părăsit jocul", + "log.announced": "{name} anunță sfârșitul jocului", + "log.end.announced": "Joc încheiat: sfârșitul a fost anunțat", + "log.end.condition": "Joc încheiat: o condiție de final a fost îndeplinită", + "log.end.stall": "Joc încheiat: o rundă întreagă nu s-a plasat nicio piesă", + "log.end.dropped": "Joc încheiat: a rămas un singur jucător", + "log.finalSale": "{name} vinde {count} {chain} pentru {amount}", + "log.result": "Bani la final: {results}", + "chat.label": "Chat", + "chat.title": "Chat", + "chat.message": "Mesaj", + "chat.placeholder": "Mesaj…", + "chat.send": "Trimite", + "chat.sending": "Se trimite…", + "chat.empty": "Niciun mesaj încă.", + "chat.edited": "editat", +}; diff --git a/packages/viewer/src/lib/locales/ru.ts b/packages/viewer/src/lib/locales/ru.ts new file mode 100644 index 0000000..cf85046 --- /dev/null +++ b/packages/viewer/src/lib/locales/ru.ts @@ -0,0 +1,197 @@ +import type { Catalog } from "../i18n.ts"; + +export const ru: Catalog = { + loading: "Загрузка игры…", + "status.place": "{name}: выложить фишку", + "status.found": "{name}: назвать новую сеть", + "status.survivor": "{name}: выбрать сеть, которая уцелеет при слиянии", + "status.defunctOrder": "{name}: выбрать порядок поглощаемых сетей", + "status.dispose": "{name}: продать, обменять или оставить акции {chain}", + "status.buy": "{name}: купить акции", + "status.gameOver": "Игра окончена", + "status.yourDecision": "ваше решение", + "status.announced": "Объявлен конец игры; она закончится после этого хода.", + "status.replay": "Повтор: ход {turn}", + "status.replayNote": "Вы смотрите более раннюю позицию. Фишки на руке не показываются.", + "panel.label": "Ваше решение", + "panel.sending": "Отправка…", + "announce.ask": "Закончить игру после этого хода? Это нельзя отменить.", + "announce.confirm": "Объявить конец игры", + "announce.cancel": "Продолжить игру", + "announce.open": "Объявить конец игры…", + "place.effect": "{tile}: {effect}.", + "place.loose": "останется одиночной (нет соседних фишек)", + "place.found": "основывает новую сеть", + "place.joins": "присоединяется к {chain}", + "place.merges": "сливает {chains}", + "place.button": "Выложить {tile}", + "place.another": "Выбрать другую", + "place.choose": "Выберите фишку с руки.", + "place.none": "Ни одну из ваших фишек нельзя выложить.", + "place.pass": "Продолжить без выкладки", + "found.prompt": "Назовите новую сеть. Вы получаете одну бесплатную акцию.", + "survivor.prompt": "Эти сети одинаково велики и крупнее остальных. Выберите, какая уцелеет.", + tiles: { one: "{count} фишка", few: "{count} фишки", many: "{count} фишек", other: "{count} фишки" }, + "order.prompt": + "{survivor} уцелеет. Некоторые поглощаемые сети одного размера: выберите порядок их расчёта, от первой до последней.", + "order.confirm": "Подтвердить порядок", + "order.reset": "Начать заново", + "dispose.takenOver": "{survivor} поглощает {defunct}.", + "dispose.holding": { + one: "У вас {count} акция {chain}.", + few: "У вас {count} акции {chain}.", + many: "У вас {count} акций {chain}.", + other: "У вас {count} акции {chain}.", + }, + "dispose.sell": "Продать по {price}", + "dispose.trade": "Обменять 2 на 1", + "dispose.keep": "Оставить", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "ничего не стоят, если {chain} не будет основана снова", + "dispose.sellFewer": "Продать на одну меньше", + "dispose.sellMore": "Продать на одну больше", + "dispose.tradeFewer": "Обменять на две меньше", + "dispose.tradeMore": "Обменять на две больше", + "dispose.confirm": "Подтвердить", + "buy.prompt": "Купите до 3 акций. Цены в этом ходе не меняются.", + "buy.chain": "Сеть", + "buy.price": "Цена", + "buy.bank": "Банк", + "buy.buy": "Купить", + "buy.fewer": "На одну акцию {chain} меньше", + "buy.more": "На одну акцию {chain} больше", + "buy.total": "{count} из 3 акций · стоимость {cost} · останется {cash}", + "buy.nothing": "Ничего не покупать и закончить ход", + "buy.confirm": "Купить за {cost} и закончить ход", + "board.label": "Поле", + "board.empty": "{tile} пусто", + "board.loose": "{tile} одиночная фишка", + "board.chain": "{tile} {chain}", + "board.place": "Выложить {tile}", + "hand.yours": "Ваши фишки", + "hand.seat": "Фишки, место {seat}", + "hand.of": "Фишки игрока {name}", + "hand.none": "Нет фишек", + "hand.dead": "мёртвая: слила бы защищённые сети", + "hand.eighth": "нельзя основать 8-ю сеть", + "chains.label": "Гостиничные сети", + "chains.title": "Сети", + "chains.chain": "Сеть", + "chains.size": "Размер", + "chains.price": "Цена", + "chains.bank": "Банк", + "chains.yours": "Ваши", + "chains.notOnBoard": "нет на поле", + "chains.safe": "защищена", + "prices.label": "Таблица цен", + "prices.show": "Таблица цен", + "prices.hide": "Скрыть таблицу цен", + "prices.minor": "Малые сети:", + "prices.medium": "Средние сети:", + "prices.major": "Крупные сети:", + "prices.price": "Цена", + "prices.first": "1-я", + "prices.second": "2-я", + "prices.note": "Размер — это число фишек в сети. Метка сети показывает, где она сейчас.", + "players.label": "Игроки", + "players.title": "Игроки", + "players.player": "Игрок", + "players.cash": "Деньги", + "players.stock": "Акции", + "players.tiles": "Фишки", + "players.acting": "ходит сейчас", + "players.you": "вы", + "players.turn": "ход", + "players.left": "вышел", + "players.none": "нет", + hidden: "скрыто", + "seat.name": "{name} (место {seat})", + "log.label": "Журнал игры", + "log.title": "Журнал", + "log.recent": "Показать только последние строки", + "log.all": { + one: "Показать весь журнал (ещё {count})", + few: "Показать весь журнал (ещё {count})", + many: "Показать весь журнал (ещё {count})", + other: "Показать весь журнал (ещё {count})", + }, + "log.init": { + one: "Новая игра на {count} игрока", + few: "Новая игра на {count} игроков", + many: "Новая игра на {count} игроков", + other: "Новая игра на {count} игрока", + }, + "log.optionIgnored.players": { + one: "Опция {option} пропущена: она действует только при ровно {count} игроке", + few: "Опция {option} пропущена: она действует только при ровно {count} игроках", + many: "Опция {option} пропущена: она действует только при ровно {count} игроках", + other: "Опция {option} пропущена: она действует только при ровно {count} игроках", + }, + "log.optionIgnored.value": "Опция {option} пропущена: неизвестное значение", + "log.turnOrder": "Фишки очерёдности: {tiles}. Первым ходит {name}", + "log.turn": "Ход: {name}", + "log.placed": "{name} выкладывает {tile}", + "log.placedAuto": "{name} выкладывает {tile} (автоматически)", + "log.survivor": "{name} оставляет {chain}", + "log.survivorAuto": "{name} оставляет {chain} (автоматически)", + "log.order": "{name} выбирает порядок: {chains}", + "log.orderAuto": "{name} выбирает порядок: {chains} (автоматически)", + "log.skipPlace": "{name} не выкладывает фишку", + "log.founded": "{name} основывает {chain} ({tiles}) и получает бесплатную акцию", + "log.foundedNoShare": "{name} основывает {chain} ({tiles}); бесплатных акций не осталось", + "log.grew": "{chain} растёт, теперь в ней {tiles}", + "log.merger": "{tile} игрока {name} сливает {chains}", + "log.mergerBank": "Фишка банка {tile} сливает {chains}", + "log.mergerPlan": "{survivor} уцелевает и поглощает {chains}", + "log.bonuses": "Премии {chain} при размере {size}: {payouts}", + "log.bonusesNobody": "Премии {chain} при размере {size}: никто не получает", + "log.bankHeld": { + one: "; у банка была {count} акция (вытянул {tile})", + few: "; у банка было {count} акции (вытянул {tile})", + many: "; у банка было {count} акций (вытянул {tile})", + other: "; у банка было {count} акции (вытянул {tile})", + }, + "log.bankHeldEmpty": "; у банка было 0 акций (запас пуст)", + "log.bankKept": " и оставил себе {amount}", + "log.shares": { + one: "{count} акцию {chain}", + few: "{count} акции {chain}", + many: "{count} акций {chain}", + other: "{count} акции {chain}", + }, + "log.sold": "продаёт {shares} за {amount}", + "log.traded": "обменивает {shares} на {count} уцелевшей сети", + "log.kept": "оставляет {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name}: нечего рассчитывать", + "log.merged": "В {chain} теперь {tiles}", + "log.bankLoose": "Фишка банка {tile} остаётся одиночной", + "log.bankJoined": "Фишка банка {tile} присоединяется к сети", + "log.bankMerger": "Фишка банка {tile} вызывает слияние", + "log.bankRemoved": "Фишку банка {tile} нельзя выложить, она убрана", + "log.bought": "{name} покупает {shares} за {cost}", + "log.boughtNothing": "{name} не покупает акций", + "log.discarded": "{name} сбрасывает невыкладываемые фишки: {tiles}", + "log.drew": { + one: "{name} берёт фишку", + few: "{name} берёт {count} фишки", + many: "{name} берёт {count} фишек", + other: "{name} берёт {count} фишки", + }, + "log.dropped": "{name} покидает игру", + "log.announced": "{name} объявляет конец игры", + "log.end.announced": "Игра окончена: объявлен конец", + "log.end.condition": "Игра окончена: выполнено условие окончания", + "log.end.stall": "Игра окончена: за целый круг не выложено ни одной фишки", + "log.end.dropped": "Игра окончена: остался только один игрок", + "log.finalSale": "{name} продаёт {count} {chain} за {amount}", + "log.result": "Итоговые деньги: {results}", + "chat.label": "Чат", + "chat.title": "Чат", + "chat.message": "Сообщение", + "chat.placeholder": "Сообщение…", + "chat.send": "Отправить", + "chat.sending": "Отправка…", + "chat.empty": "Сообщений пока нет.", + "chat.edited": "изменено", +}; diff --git a/packages/viewer/src/lib/locales/vi.ts b/packages/viewer/src/lib/locales/vi.ts new file mode 100644 index 0000000..63a00d1 --- /dev/null +++ b/packages/viewer/src/lib/locales/vi.ts @@ -0,0 +1,162 @@ +import type { Catalog } from "../i18n.ts"; + +export const vi: Catalog = { + loading: "Đang tải ván chơi…", + "status.place": "{name} cần đặt một ô", + "status.found": "{name} cần đặt tên cho chuỗi mới", + "status.survivor": "{name} cần chọn chuỗi tồn tại sau sáp nhập", + "status.defunctOrder": "{name} cần chọn thứ tự các chuỗi bị thâu tóm", + "status.dispose": "{name} cần bán, đổi hoặc giữ cổ phiếu {chain}", + "status.buy": "{name} cần mua cổ phiếu", + "status.gameOver": "Kết thúc ván chơi", + "status.yourDecision": "bạn quyết định", + "status.announced": "Đã tuyên bố kết thúc; ván chơi kết thúc sau lượt này.", + "status.replay": "Xem lại: lượt {turn}", + "status.replayNote": "Bạn đang xem một thế cờ trước đó. Các ô trên tay không được hiển thị.", + "panel.label": "Quyết định của bạn", + "panel.sending": "Đang gửi…", + "announce.ask": "Kết thúc ván chơi sau lượt này? Không thể hoàn tác.", + "announce.confirm": "Tuyên bố kết thúc", + "announce.cancel": "Tiếp tục chơi", + "announce.open": "Tuyên bố kết thúc…", + "place.effect": "{tile}: {effect}.", + "place.loose": "nằm riêng (không có ô kề bên)", + "place.found": "lập một chuỗi mới", + "place.joins": "nhập vào {chain}", + "place.merges": "sáp nhập {chains}", + "place.button": "Đặt {tile}", + "place.another": "Chọn ô khác", + "place.choose": "Chọn một ô trên tay.", + "place.none": "Không ô nào của bạn đặt được.", + "place.pass": "Tiếp tục mà không đặt", + "found.prompt": "Đặt tên cho chuỗi mới. Bạn nhận một cổ phiếu miễn phí.", + "survivor.prompt": "Các chuỗi này lớn nhất và bằng nhau. Chọn chuỗi tồn tại.", + tiles: { other: "{count} ô" }, + "order.prompt": + "{survivor} tồn tại. Một số chuỗi bị thâu tóm có cùng kích thước: chọn thứ tự thanh toán chúng, từ đầu đến cuối.", + "order.confirm": "Xác nhận thứ tự", + "order.reset": "Chọn lại", + "dispose.takenOver": "{defunct} bị {survivor} thâu tóm.", + "dispose.holding": { other: "Bạn có {count} cổ phiếu {chain}." }, + "dispose.sell": "Bán giá {price}", + "dispose.trade": "Đổi 2 lấy 1", + "dispose.keep": "Giữ", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "vô giá trị trừ khi {chain} được lập lại", + "dispose.sellFewer": "Bán bớt một", + "dispose.sellMore": "Bán thêm một", + "dispose.tradeFewer": "Đổi bớt hai", + "dispose.tradeMore": "Đổi thêm hai", + "dispose.confirm": "Xác nhận", + "buy.prompt": "Mua tối đa 3 cổ phiếu. Giá không đổi trong lượt này.", + "buy.chain": "Chuỗi", + "buy.price": "Giá", + "buy.bank": "Ngân hàng", + "buy.buy": "Mua", + "buy.fewer": "Bớt một cổ phiếu {chain}", + "buy.more": "Thêm một cổ phiếu {chain}", + "buy.total": "{count}/3 cổ phiếu · chi phí {cost} · còn lại {cash}", + "buy.nothing": "Không mua và kết thúc lượt", + "buy.confirm": "Mua với giá {cost} và kết thúc lượt", + "board.label": "Bàn chơi", + "board.empty": "{tile} trống", + "board.loose": "{tile} ô nằm riêng", + "board.chain": "{tile} {chain}", + "board.place": "Đặt {tile}", + "hand.yours": "Ô của bạn", + "hand.seat": "Ô, ghế {seat}", + "hand.of": "Ô của {name}", + "hand.none": "Không có ô", + "hand.dead": "ô chết: sẽ sáp nhập các chuỗi an toàn", + "hand.eighth": "không thể lập chuỗi thứ 8", + "chains.label": "Chuỗi khách sạn", + "chains.title": "Chuỗi", + "chains.chain": "Chuỗi", + "chains.size": "Kích thước", + "chains.price": "Giá", + "chains.bank": "Ngân hàng", + "chains.yours": "Của bạn", + "chains.notOnBoard": "không có trên bàn", + "chains.safe": "an toàn", + "prices.label": "Bảng giá", + "prices.show": "Bảng giá", + "prices.hide": "Ẩn bảng giá", + "prices.minor": "Chuỗi nhỏ:", + "prices.medium": "Chuỗi vừa:", + "prices.major": "Chuỗi lớn:", + "prices.price": "Giá", + "prices.first": "Nhất", + "prices.second": "Nhì", + "prices.note": "Kích thước là số ô của chuỗi. Dấu của mỗi chuỗi cho biết chuỗi đang ở đâu.", + "players.label": "Người chơi", + "players.title": "Người chơi", + "players.player": "Người chơi", + "players.cash": "Tiền", + "players.stock": "Cổ phiếu", + "players.tiles": "Ô", + "players.acting": "đang quyết định", + "players.you": "bạn", + "players.turn": "lượt", + "players.left": "đã rời", + "players.none": "không có", + hidden: "ẩn", + "seat.name": "{name} (ghế {seat})", + "log.label": "Nhật ký ván chơi", + "log.title": "Nhật ký", + "log.recent": "Chỉ hiện các dòng gần đây", + "log.all": { other: "Hiện toàn bộ nhật ký (thêm {count})" }, + "log.init": { other: "Ván mới cho {count} người chơi" }, + "log.optionIgnored.players": { other: "Bỏ qua tùy chọn {option}: chỉ áp dụng khi có đúng {count} người chơi" }, + "log.optionIgnored.value": "Bỏ qua tùy chọn {option}: giá trị không xác định", + "log.turnOrder": "Ô xác định thứ tự: {tiles}. {name} đi trước", + "log.turn": "Lượt của {name}", + "log.placed": "{name} đặt {tile}", + "log.placedAuto": "{name} đặt {tile} (tự động)", + "log.survivor": "{name} chọn {chain} tồn tại", + "log.survivorAuto": "{name} chọn {chain} tồn tại (tự động)", + "log.order": "{name} chọn thứ tự {chains}", + "log.orderAuto": "{name} chọn thứ tự {chains} (tự động)", + "log.skipPlace": "{name} không đặt ô", + "log.founded": "{name} lập {chain} ({tiles}) và nhận một cổ phiếu miễn phí", + "log.foundedNoShare": "{name} lập {chain} ({tiles}); không còn cổ phiếu miễn phí", + "log.grew": "{chain} tăng lên {tiles}", + "log.merger": "Ô {tile} của {name} sáp nhập {chains}", + "log.mergerBank": "Ô {tile} của ngân hàng sáp nhập {chains}", + "log.mergerPlan": "{survivor} tồn tại và thâu tóm {chains}", + "log.bonuses": "Tiền thưởng {chain} ở kích thước {size}: {payouts}", + "log.bonusesNobody": "Tiền thưởng {chain} ở kích thước {size}: không ai nhận", + "log.bankHeld": { other: "; ngân hàng có {count} cổ phiếu (rút {tile})" }, + "log.bankHeldEmpty": "; ngân hàng có 0 cổ phiếu (hết ô)", + "log.bankKept": " và giữ lại {amount}", + "log.shares": { other: "{count} cổ phiếu {chain}" }, + "log.sold": "bán {shares} được {amount}", + "log.traded": "đổi {shares} lấy {count} cổ phiếu của chuỗi tồn tại", + "log.kept": "giữ {shares}", + "log.disposed": "{name} {actions}", + "log.disposedNothing": "{name} không có gì để thanh toán", + "log.merged": "{chain} giờ có {tiles}", + "log.bankLoose": "Ô {tile} của ngân hàng nằm riêng", + "log.bankJoined": "Ô {tile} của ngân hàng nhập vào một chuỗi", + "log.bankMerger": "Ô {tile} của ngân hàng gây ra sáp nhập", + "log.bankRemoved": "Ô {tile} của ngân hàng không đặt được và bị loại bỏ", + "log.bought": "{name} mua {shares} với giá {cost}", + "log.boughtNothing": "{name} không mua cổ phiếu", + "log.discarded": "{name} bỏ các ô không đặt được: {tiles}", + "log.drew": { other: "{name} rút {count} ô" }, + "log.dropped": "{name} đã rời ván chơi", + "log.announced": "{name} tuyên bố kết thúc ván chơi", + "log.end.announced": "Kết thúc: đã tuyên bố kết thúc", + "log.end.condition": "Kết thúc: đạt điều kiện kết thúc", + "log.end.stall": "Kết thúc: trọn một vòng không ai đặt ô", + "log.end.dropped": "Kết thúc: chỉ còn một người chơi", + "log.finalSale": "{name} bán {count} {chain} được {amount}", + "log.result": "Tiền cuối cùng: {results}", + "chat.label": "Trò chuyện", + "chat.title": "Trò chuyện", + "chat.message": "Tin nhắn", + "chat.placeholder": "Tin nhắn…", + "chat.send": "Gửi", + "chat.sending": "Đang gửi…", + "chat.empty": "Chưa có tin nhắn.", + "chat.edited": "đã sửa", +}; diff --git a/packages/viewer/src/lib/locales/zh-CN.ts b/packages/viewer/src/lib/locales/zh-CN.ts new file mode 100644 index 0000000..703eb6e --- /dev/null +++ b/packages/viewer/src/lib/locales/zh-CN.ts @@ -0,0 +1,161 @@ +import type { Catalog } from "../i18n.ts"; + +export const zhCN: Catalog = { + loading: "正在加载游戏…", + "status.place": "{name}:放置一块板块", + "status.found": "{name}:为新连锁命名", + "status.survivor": "{name}:选择合并后存续的连锁", + "status.defunctOrder": "{name}:选择被吞并连锁的顺序", + "status.dispose": "{name}:出售、兑换或保留 {chain} 股票", + "status.buy": "{name}:购买股票", + "status.gameOver": "游戏结束", + "status.yourDecision": "轮到你决定", + "status.announced": "已宣布结束游戏,本回合结束后游戏结束。", + "status.replay": "回放:第 {turn} 回合", + "status.replayNote": "你正在查看较早的局面。手中的板块不会显示。", + "panel.label": "你的决定", + "panel.sending": "正在发送…", + "announce.ask": "在本回合结束后结束游戏?此操作无法撤销。", + "announce.confirm": "宣布结束", + "announce.cancel": "继续游戏", + "announce.open": "宣布结束…", + "place.effect": "{tile}:{effect}。", + "place.loose": "单独放置(没有相邻板块)", + "place.found": "创立新连锁", + "place.joins": "加入 {chain}", + "place.merges": "合并 {chains}", + "place.button": "放置 {tile}", + "place.another": "换一块", + "place.choose": "从手中选择一块板块。", + "place.none": "你没有可以放置的板块。", + "place.pass": "不放置,继续", + "found.prompt": "为新连锁命名。你将获得一股免费股票。", + "survivor.prompt": "这些连锁并列最大。请选择存续的连锁。", + tiles: { other: "{count} 块" }, + "order.prompt": "{survivor} 存续。部分被吞并的连锁大小相同:请从先到后选择它们的结算顺序。", + "order.confirm": "确认顺序", + "order.reset": "重新选择", + "dispose.takenOver": "{defunct} 被 {survivor} 吞并。", + "dispose.holding": { other: "你持有 {count} 股 {chain}。" }, + "dispose.sell": "以 {price} 出售", + "dispose.trade": "2 换 1", + "dispose.keep": "保留", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "除非 {chain} 重新创立,否则毫无价值", + "dispose.sellFewer": "少卖一股", + "dispose.sellMore": "多卖一股", + "dispose.tradeFewer": "少换两股", + "dispose.tradeMore": "多换两股", + "dispose.confirm": "确认", + "buy.prompt": "最多购买 3 股。本回合内价格不变。", + "buy.chain": "连锁", + "buy.price": "价格", + "buy.bank": "银行", + "buy.buy": "购买", + "buy.fewer": "少买一股 {chain}", + "buy.more": "多买一股 {chain}", + "buy.total": "{count}/3 股 · 花费 {cost} · 剩余 {cash}", + "buy.nothing": "不购买,结束回合", + "buy.confirm": "花费 {cost} 购买并结束回合", + "board.label": "游戏版图", + "board.empty": "{tile} 空", + "board.loose": "{tile} 单独板块", + "board.chain": "{tile} {chain}", + "board.place": "放置 {tile}", + "hand.yours": "你的板块", + "hand.seat": "板块,座位 {seat}", + "hand.of": "{name} 的板块", + "hand.none": "没有板块", + "hand.dead": "死板块:会合并安全连锁", + "hand.eighth": "无法创立第 8 个连锁", + "chains.label": "酒店连锁", + "chains.title": "连锁", + "chains.chain": "连锁", + "chains.size": "大小", + "chains.price": "价格", + "chains.bank": "银行", + "chains.yours": "你的", + "chains.notOnBoard": "不在版图上", + "chains.safe": "安全", + "prices.label": "价格表", + "prices.show": "价格表", + "prices.hide": "隐藏价格表", + "prices.minor": "小型连锁:", + "prices.medium": "中型连锁:", + "prices.major": "大型连锁:", + "prices.price": "价格", + "prices.first": "第一", + "prices.second": "第二", + "prices.note": "大小即连锁的板块数。连锁标记显示它目前所处的位置。", + "players.label": "玩家", + "players.title": "玩家", + "players.player": "玩家", + "players.cash": "现金", + "players.stock": "股票", + "players.tiles": "板块", + "players.acting": "正在行动", + "players.you": "你", + "players.turn": "回合", + "players.left": "已离开", + "players.none": "无", + hidden: "隐藏", + "seat.name": "{name}(座位 {seat})", + "log.label": "游戏记录", + "log.title": "记录", + "log.recent": "只显示最近几行", + "log.all": { other: "显示全部记录(还有 {count} 行)" }, + "log.init": { other: "{count} 人新游戏" }, + "log.optionIgnored.players": { other: "已忽略选项 {option}:仅在恰好 {count} 名玩家时生效" }, + "log.optionIgnored.value": "已忽略选项 {option}:未知的值", + "log.turnOrder": "顺序板块:{tiles}。{name} 先手", + "log.turn": "轮到 {name}", + "log.placed": "{name} 放置了 {tile}", + "log.placedAuto": "{name} 放置了 {tile}(自动)", + "log.survivor": "{name} 选择 {chain} 存续", + "log.survivorAuto": "{name} 选择 {chain} 存续(自动)", + "log.order": "{name} 选择顺序 {chains}", + "log.orderAuto": "{name} 选择顺序 {chains}(自动)", + "log.skipPlace": "{name} 没有放置板块", + "log.founded": "{name} 创立了 {chain}({tiles}),获得一股免费股票", + "log.foundedNoShare": "{name} 创立了 {chain}({tiles});免费股票已无剩余", + "log.grew": "{chain} 扩大到 {tiles}", + "log.merger": "{name} 的 {tile} 合并了 {chains}", + "log.mergerBank": "银行的板块 {tile} 合并了 {chains}", + "log.mergerPlan": "{survivor} 存续并吞并 {chains}", + "log.bonuses": "{chain} 在大小 {size} 时的奖金:{payouts}", + "log.bonusesNobody": "{chain} 在大小 {size} 时的奖金:无人获得", + "log.bankHeld": { other: ";银行持有 {count} 股(抽到 {tile})" }, + "log.bankHeldEmpty": ";银行持有 0 股(板块堆已空)", + "log.bankKept": ",留下 {amount}", + "log.shares": { other: "{count} 股 {chain}" }, + "log.sold": "以 {amount} 出售了 {shares}", + "log.traded": "将 {shares} 兑换成存续连锁的 {count} 股", + "log.kept": "保留了 {shares}", + "log.disposed": "{name}:{actions}", + "log.disposedNothing": "{name} 没有需要结算的股票", + "log.merged": "{chain} 现在有 {tiles}", + "log.bankLoose": "银行的板块 {tile} 单独放置", + "log.bankJoined": "银行的板块 {tile} 加入一个连锁", + "log.bankMerger": "银行的板块 {tile} 引发合并", + "log.bankRemoved": "银行的板块 {tile} 无法放置,已移除", + "log.bought": "{name} 以 {cost} 购买了 {shares}", + "log.boughtNothing": "{name} 没有购买股票", + "log.discarded": "{name} 弃掉了无法放置的板块:{tiles}", + "log.drew": { other: "{name} 抽了 {count} 块板块" }, + "log.dropped": "{name} 离开了游戏", + "log.announced": "{name} 宣布结束游戏", + "log.end.announced": "游戏结束:已宣布结束", + "log.end.condition": "游戏结束:达成结束条件", + "log.end.stall": "游戏结束:整整一轮没有人放置板块", + "log.end.dropped": "游戏结束:只剩一名玩家", + "log.finalSale": "{name} 以 {amount} 出售了 {count} 股 {chain}", + "log.result": "最终现金:{results}", + "chat.label": "聊天", + "chat.title": "聊天", + "chat.message": "消息", + "chat.placeholder": "消息…", + "chat.send": "发送", + "chat.sending": "正在发送…", + "chat.empty": "还没有消息。", + "chat.edited": "已编辑", +}; diff --git a/packages/viewer/src/lib/locales/zh-TW.ts b/packages/viewer/src/lib/locales/zh-TW.ts new file mode 100644 index 0000000..e9bb6a1 --- /dev/null +++ b/packages/viewer/src/lib/locales/zh-TW.ts @@ -0,0 +1,161 @@ +import type { Catalog } from "../i18n.ts"; + +export const zhTW: Catalog = { + loading: "正在載入遊戲…", + "status.place": "{name}:放置一塊板塊", + "status.found": "{name}:為新連鎖命名", + "status.survivor": "{name}:選擇合併後存續的連鎖", + "status.defunctOrder": "{name}:選擇被併購連鎖的順序", + "status.dispose": "{name}:出售、兌換或保留 {chain} 股票", + "status.buy": "{name}:購買股票", + "status.gameOver": "遊戲結束", + "status.yourDecision": "輪到你決定", + "status.announced": "已宣布結束遊戲,本回合結束後遊戲結束。", + "status.replay": "重播:第 {turn} 回合", + "status.replayNote": "你正在檢視較早的局面。手中的板塊不會顯示。", + "panel.label": "你的決定", + "panel.sending": "正在傳送…", + "announce.ask": "在本回合結束後結束遊戲?此動作無法復原。", + "announce.confirm": "宣布結束", + "announce.cancel": "繼續遊戲", + "announce.open": "宣布結束…", + "place.effect": "{tile}:{effect}。", + "place.loose": "單獨放置(沒有相鄰板塊)", + "place.found": "創立新連鎖", + "place.joins": "加入 {chain}", + "place.merges": "合併 {chains}", + "place.button": "放置 {tile}", + "place.another": "換一塊", + "place.choose": "從手中選擇一塊板塊。", + "place.none": "你沒有可以放置的板塊。", + "place.pass": "不放置,繼續", + "found.prompt": "為新連鎖命名。你將獲得一股免費股票。", + "survivor.prompt": "這些連鎖並列最大。請選擇存續的連鎖。", + tiles: { other: "{count} 塊" }, + "order.prompt": "{survivor} 存續。部分被併購的連鎖大小相同:請由先到後選擇它們的結算順序。", + "order.confirm": "確認順序", + "order.reset": "重新選擇", + "dispose.takenOver": "{defunct} 被 {survivor} 併購。", + "dispose.holding": { other: "你持有 {count} 股 {chain}。" }, + "dispose.sell": "以 {price} 出售", + "dispose.trade": "2 換 1", + "dispose.keep": "保留", + "dispose.receive": "+{count} {chain}", + "dispose.keepNote": "除非 {chain} 重新創立,否則毫無價值", + "dispose.sellFewer": "少賣一股", + "dispose.sellMore": "多賣一股", + "dispose.tradeFewer": "少換兩股", + "dispose.tradeMore": "多換兩股", + "dispose.confirm": "確認", + "buy.prompt": "最多購買 3 股。本回合內價格不變。", + "buy.chain": "連鎖", + "buy.price": "價格", + "buy.bank": "銀行", + "buy.buy": "購買", + "buy.fewer": "少買一股 {chain}", + "buy.more": "多買一股 {chain}", + "buy.total": "{count}/3 股 · 花費 {cost} · 剩餘 {cash}", + "buy.nothing": "不購買,結束回合", + "buy.confirm": "花費 {cost} 購買並結束回合", + "board.label": "遊戲圖板", + "board.empty": "{tile} 空", + "board.loose": "{tile} 單獨板塊", + "board.chain": "{tile} {chain}", + "board.place": "放置 {tile}", + "hand.yours": "你的板塊", + "hand.seat": "板塊,座位 {seat}", + "hand.of": "{name} 的板塊", + "hand.none": "沒有板塊", + "hand.dead": "死板塊:會合併安全連鎖", + "hand.eighth": "無法創立第 8 個連鎖", + "chains.label": "飯店連鎖", + "chains.title": "連鎖", + "chains.chain": "連鎖", + "chains.size": "大小", + "chains.price": "價格", + "chains.bank": "銀行", + "chains.yours": "你的", + "chains.notOnBoard": "不在圖板上", + "chains.safe": "安全", + "prices.label": "價格表", + "prices.show": "價格表", + "prices.hide": "隱藏價格表", + "prices.minor": "小型連鎖:", + "prices.medium": "中型連鎖:", + "prices.major": "大型連鎖:", + "prices.price": "價格", + "prices.first": "第一", + "prices.second": "第二", + "prices.note": "大小即連鎖的板塊數。連鎖標記顯示它目前所在的位置。", + "players.label": "玩家", + "players.title": "玩家", + "players.player": "玩家", + "players.cash": "現金", + "players.stock": "股票", + "players.tiles": "板塊", + "players.acting": "正在行動", + "players.you": "你", + "players.turn": "回合", + "players.left": "已離開", + "players.none": "無", + hidden: "隱藏", + "seat.name": "{name}(座位 {seat})", + "log.label": "遊戲紀錄", + "log.title": "紀錄", + "log.recent": "只顯示最近幾行", + "log.all": { other: "顯示全部紀錄(還有 {count} 行)" }, + "log.init": { other: "{count} 人新遊戲" }, + "log.optionIgnored.players": { other: "已忽略選項 {option}:僅在恰好 {count} 名玩家時生效" }, + "log.optionIgnored.value": "已忽略選項 {option}:未知的值", + "log.turnOrder": "順序板塊:{tiles}。{name} 先手", + "log.turn": "輪到 {name}", + "log.placed": "{name} 放置了 {tile}", + "log.placedAuto": "{name} 放置了 {tile}(自動)", + "log.survivor": "{name} 選擇 {chain} 存續", + "log.survivorAuto": "{name} 選擇 {chain} 存續(自動)", + "log.order": "{name} 選擇順序 {chains}", + "log.orderAuto": "{name} 選擇順序 {chains}(自動)", + "log.skipPlace": "{name} 沒有放置板塊", + "log.founded": "{name} 創立了 {chain}({tiles}),獲得一股免費股票", + "log.foundedNoShare": "{name} 創立了 {chain}({tiles});免費股票已無剩餘", + "log.grew": "{chain} 擴大到 {tiles}", + "log.merger": "{name} 的 {tile} 合併了 {chains}", + "log.mergerBank": "銀行的板塊 {tile} 合併了 {chains}", + "log.mergerPlan": "{survivor} 存續並併購 {chains}", + "log.bonuses": "{chain} 在大小 {size} 時的獎金:{payouts}", + "log.bonusesNobody": "{chain} 在大小 {size} 時的獎金:無人獲得", + "log.bankHeld": { other: ";銀行持有 {count} 股(抽到 {tile})" }, + "log.bankHeldEmpty": ";銀行持有 0 股(板塊堆已空)", + "log.bankKept": ",留下 {amount}", + "log.shares": { other: "{count} 股 {chain}" }, + "log.sold": "以 {amount} 出售了 {shares}", + "log.traded": "將 {shares} 兌換成存續連鎖的 {count} 股", + "log.kept": "保留了 {shares}", + "log.disposed": "{name}:{actions}", + "log.disposedNothing": "{name} 沒有需要結算的股票", + "log.merged": "{chain} 現在有 {tiles}", + "log.bankLoose": "銀行的板塊 {tile} 單獨放置", + "log.bankJoined": "銀行的板塊 {tile} 加入一個連鎖", + "log.bankMerger": "銀行的板塊 {tile} 引發合併", + "log.bankRemoved": "銀行的板塊 {tile} 無法放置,已移除", + "log.bought": "{name} 以 {cost} 購買了 {shares}", + "log.boughtNothing": "{name} 沒有購買股票", + "log.discarded": "{name} 棄掉了無法放置的板塊:{tiles}", + "log.drew": { other: "{name} 抽了 {count} 塊板塊" }, + "log.dropped": "{name} 離開了遊戲", + "log.announced": "{name} 宣布結束遊戲", + "log.end.announced": "遊戲結束:已宣布結束", + "log.end.condition": "遊戲結束:達成結束條件", + "log.end.stall": "遊戲結束:整整一輪沒有人放置板塊", + "log.end.dropped": "遊戲結束:只剩一名玩家", + "log.finalSale": "{name} 以 {amount} 出售了 {count} 股 {chain}", + "log.result": "最終現金:{results}", + "chat.label": "聊天", + "chat.title": "聊天", + "chat.message": "訊息", + "chat.placeholder": "訊息…", + "chat.send": "傳送", + "chat.sending": "正在傳送…", + "chat.empty": "還沒有訊息。", + "chat.edited": "已編輯", +}; diff --git a/packages/viewer/src/lib/palette.spec.ts b/packages/viewer/src/lib/palette.spec.ts new file mode 100644 index 0000000..2a1dad1 --- /dev/null +++ b/packages/viewer/src/lib/palette.spec.ts @@ -0,0 +1,170 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CHAINS } from "acquire-engine"; +import { contrastRatio, deltaE2000, difference, type Deficiency } from "./color.ts"; +import { ACCEPTED_ACCENT_CLASHES, CHAIN_STYLES, OKABE_ITO_ORIGIN, THEMES } from "./palette.ts"; + +/** Minimum CIEDE2000 difference required between any two chain colours, in every vision. */ +const MIN_CHAIN_DIFFERENCE = 12; +/** Minimum CIEDE2000 difference between any chain colour and any board colour, in every vision. */ +const MIN_BOARD_DIFFERENCE = 12; +/** WCAG AA contrast for normal-size text. */ +const MIN_TEXT_CONTRAST = 4.5; + +const VISIONS: (Deficiency | undefined)[] = [undefined, "protanopia", "deuteranopia", "tritanopia"]; +const chains = Object.entries(CHAIN_STYLES); +const themes = Object.entries(THEMES); + +test("CIEDE2000 matches the Sharma, Wu & Dalal (2005) reference data", () => { + const pairs: [[number, number, number], [number, number, number], number][] = [ + [[50, 2.6772, -79.7751], [50, 0, -82.7485], 2.0425], + [[50, 3.1571, -77.2803], [50, 0, -82.7485], 2.8615], + [[50, 2.8361, -74.02], [50, 0, -82.7485], 3.4412], + [[50, 0, 0], [50, -1, 2], 2.3669], + [[50, 2.5, 0], [73, 25, -18], 27.1492], + [[60.2574, -34.0099, 36.2677], [60.4626, -34.1751, 39.4387], 1.2644], + [[2.0776, 0.0795, -1.135], [0.9033, -0.0636, -0.5514], 0.9082], + ]; + for (const [lab1, lab2, expected] of pairs) { + assert.ok(Math.abs(deltaE2000(lab1, lab2) - expected) < 1e-4, `${lab1} vs ${lab2}`); + } +}); + +test("every engine chain has a style with a unique letter matching its name", () => { + assert.deepEqual(Object.keys(CHAIN_STYLES).sort(), CHAINS.map((chain) => chain.id).sort()); + for (const chain of CHAINS) { + assert.equal(CHAIN_STYLES[chain.id].letter, chain.name[0]); + } + assert.equal(new Set(chains.map(([, style]) => style.letter)).size, chains.length); +}); + +for (const vision of VISIONS) { + const name = vision ?? "normal vision"; + test(`chain colours stay distinguishable from each other with ${name}`, () => { + for (let i = 0; i < chains.length; i++) { + for (let j = i + 1; j < chains.length; j++) { + const [a, styleA] = chains[i]!; + const [b, styleB] = chains[j]!; + const d = difference(styleA.fill, styleB.fill, vision); + assert.ok(d >= MIN_CHAIN_DIFFERENCE, `${a} vs ${b}: ΔE00 ${d.toFixed(1)} with ${name}`); + } + } + }); + + for (const [themeName, theme] of themes) { + test(`${themeName} theme: chain colours stay distinguishable from the grey squares and black tiles with ${name}`, () => { + for (const [chain, style] of chains) { + for (const part of ["empty", "loose"] as const) { + const d = difference(style.fill, theme[part], vision); + assert.ok(d >= MIN_BOARD_DIFFERENCE, `${chain} vs ${part} square: ΔE00 ${d.toFixed(1)} with ${name}`); + } + } + }); + } +} + +for (const [themeName, theme] of themes) { + // Chain colours and their labels are the same in both themes, but the check runs per theme so a + // theme can never quietly diverge. + test(`${themeName} theme: every chain label has at least 4.5:1 contrast against its colour`, () => { + for (const [chain, style] of chains) { + const ratio = contrastRatio(style.fill, style.text); + assert.ok(ratio >= MIN_TEXT_CONTRAST, `${chain}: ${ratio.toFixed(2)}:1`); + } + }); + + test(`${themeName} theme: square coordinates have at least 3:1 contrast on empty squares and loose tiles`, () => { + const onEmpty = contrastRatio(theme.onEmpty, theme.empty); + const onLoose = contrastRatio(theme.onLoose, theme.loose); + assert.ok(onEmpty >= 3, `empty square coordinates: ${onEmpty.toFixed(2)}:1`); + assert.ok(onLoose >= 3, `loose tile coordinates: ${onLoose.toFixed(2)}:1`); + }); +} + +for (const [themeName, theme] of themes) { + // Pairs below the minimum must be on the accepted list, so a new clash fails here. + test(`${themeName} theme: the accent differs from every chain and board colour except the accepted clashes`, () => { + const others = [ + ...chains.map(([chain, style]) => [chain, style.fill] as const), + ["empty square", theme.empty] as const, + ["loose tile", theme.loose] as const, + ]; + const clashes: string[] = []; + for (const vision of VISIONS) { + for (const [name, color] of others) { + if (difference(theme.accent, color, vision) < MIN_CHAIN_DIFFERENCE) { + clashes.push(`${name} ${vision ?? "normal vision"}`); + } + } + } + assert.deepEqual(clashes.sort(), [...ACCEPTED_ACCENT_CLASHES[themeName as "light" | "dark"]].sort()); + }); + + test(`${themeName} theme: the accent has at least 3:1 contrast against the page and panels it is drawn on`, () => { + for (const surface of ["page", "panel"] as const) { + const ratio = contrastRatio(theme.accent, theme[surface]); + assert.ok(ratio >= 3, `accent on ${surface}: ${ratio.toFixed(2)}:1`); + } + const text = contrastRatio(theme.onAccent, theme.accent); + assert.ok(text >= MIN_TEXT_CONTRAST, `text on accent: ${text.toFixed(2)}:1`); + }); + + test(`${themeName} theme: the keyboard focus ring is clearly distinct from the accent and the outline`, () => { + for (const vision of VISIONS) { + for (const [name, color] of [ + ["accent", theme.accent], + ["actionable outline", theme.ink], + ] as const) { + const d = difference(theme.focus, color, vision); + assert.ok(d >= 15, `focus vs ${name}: ΔE00 ${d.toFixed(1)} with ${vision ?? "normal vision"}`); + } + } + for (const surface of ["page", "panel"] as const) { + const ratio = contrastRatio(theme.focus, theme[surface]); + assert.ok(ratio >= 3, `focus on ${surface}: ${ratio.toFixed(2)}:1`); + } + }); +} + +for (const [themeName, theme] of themes) { + test(`${themeName} theme: the hand rack keeps the accent and ink outlines at 3:1 or more`, () => { + const accent = contrastRatio(theme.accent, theme.rack); + const ink = contrastRatio(theme.ink, theme.rack); + assert.ok(accent >= 3, `selected-tile accent outline on the rack: ${accent.toFixed(2)}:1`); + assert.ok(ink >= 3, `playable-tile outline on the rack: ${ink.toFixed(2)}:1`); + assert.ok(contrastRatio(theme.rack, theme.page) > 1.2, "the rack is visibly distinct from the page"); + }); +} + +test("dark theme: the rack is the lightest grey that keeps the accent at 3:1, maximising the tiles' contrast", () => { + const { rack, accent, loose } = THEMES.dark; + const level = parseInt(rack.slice(1, 3), 16); + assert.equal(rack, `#${rack.slice(1, 3).repeat(3)}`, "the rack is a neutral grey"); + const lighter = `#${(level + 1).toString(16).padStart(2, "0").repeat(3)}`; + assert.ok(contrastRatio(accent, lighter) < 3, `one step lighter (${lighter}) would drop the accent below 3:1`); + assert.ok( + contrastRatio(loose, rack) > contrastRatio(loose, THEMES.dark.empty), + "tiles stand out more than on the board" + ); +}); + +for (const [themeName] of themes) { + // Patterns are non-text marks (3:1); letters sit on solid patches, so the 4.5:1 check holds. + test(`${themeName} theme: each chain pattern has at least 3:1 contrast against its chain colour`, () => { + for (const [chain, style] of chains) { + const ratio = contrastRatio(style.patternInk, style.fill); + assert.ok(ratio >= 3, `${chain} pattern: ${ratio.toFixed(2)}:1`); + } + }); +} + +test("colour-blind mode gives every chain a different pattern", () => { + assert.equal(new Set(chains.map(([, style]) => style.pattern)).size, chains.length); +}); + +test("the palette stays close to its Okabe-Ito origins", () => { + for (const [chain, origin] of Object.entries(OKABE_ITO_ORIGIN)) { + const d = difference(CHAIN_STYLES[chain as keyof typeof CHAIN_STYLES].fill, origin); + assert.ok(d <= 12, `${chain} moved ΔE00 ${d.toFixed(1)} from ${origin}`); + } +}); diff --git a/packages/viewer/src/lib/palette.ts b/packages/viewer/src/lib/palette.ts new file mode 100644 index 0000000..b7809ca --- /dev/null +++ b/packages/viewer/src/lib/palette.ts @@ -0,0 +1,180 @@ +import type { ChainId } from "acquire-engine"; + +export interface Theme { + page: string; + panel: string; + panelAlt: string; + ink: string; + inkMuted: string; + /** Between squares: the board showing through, never an outline. */ + gap: string; + /** Board colours: grey empty squares and black loose tiles. */ + empty: string; + loose: string; + /** Coordinates printed on squares: muted on empty squares, light on loose tiles. */ + onEmpty: string; + onLoose: string; + /** + * The rack behind the hand tiles. Its own colour, not the board grey, so the selected tile's + * accent outline and the playable tiles' ink outline both reach 3:1 against it. + */ + rack: string; + /** + * The board accent: selected square outline, merging-tile stripe, safe tag, status stripe. + * Never a square's fill, and always drawn against the page or panel colour. + */ + accent: string; + /** Text on the accent (safe tag, primary buttons). */ + onAccent: string; + /** Keyboard focus ring, clearly distinct from the accent and the actionable outline. */ + focus: string; +} + +// The traditional look in both themes: grey squares, black loose tiles. Chain colours are the +// same in both themes so a chain is always recognisable. +export const THEMES: Record<"light" | "dark", Theme> = { + light: { + page: "#fbfaf6", + panel: "#f4f2ec", + panelAlt: "#e9e6dc", + ink: "#1b1b1b", + inkMuted: "#5c5c5c", + gap: "#3a3a3a", + empty: "#a6a6a6", + loose: "#1e1e1e", + onEmpty: "#3f3f3f", + onLoose: "#f2f2f2", + rack: "#d4d4d4", + accent: "#1c599b", + onAccent: "#ffffff", + focus: "#c4002f", + }, + dark: { + page: "#121212", + panel: "#1d1d1d", + panelAlt: "#262626", + ink: "#ececec", + inkMuted: "#a8a8a8", + gap: "#000000", + empty: "#3c3c3c", + loose: "#141414", + onEmpty: "#c8c8c8", + onLoose: "#f2f2f2", + // The lightest grey that keeps the accent at 3:1, which maximises the black tiles' contrast. + rack: "#515151", + // #1c599b is only 2.63:1 on the dark page, so dark mode uses a lighter shade of its hue. + accent: "#68a3e4", + onAccent: "#121212", + focus: "#ff4f8f", + }, +}; + +/** + * Accent pairs known to fall below the chain colour-difference minimum. The accent is never a + * fill and every use has a non-colour cue (outline position, stripe, "safe" text), so these were + * accepted; the palette test fails if any other pair falls below the minimum. + */ +export const ACCEPTED_ACCENT_CLASHES: Record<"light" | "dark", string[]> = { + light: ["imperial protanopia", "imperial deuteranopia", "worldwide protanopia", "festival tritanopia"], + dark: [ + "american normal vision", + "american protanopia", + "american deuteranopia", + "american tritanopia", + "continental protanopia", + "continental deuteranopia", + "continental tritanopia", + ], +}; + +/** + * CSS custom properties for both themes. The BGS light/dark setting decides (data-theme on the + * viewer root); prefers-color-scheme is only the fallback while BGS has not sent a setting. + */ +export function themeCss(): string { + const vars = (theme: Theme) => + Object.entries(theme) + .map(([name, value]) => `--${name.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase())}: ${value};`) + .join(" "); + const light = `${vars(THEMES.light)} color-scheme: light;`; + const dark = `${vars(THEMES.dark)} color-scheme: dark;`; + return [ + `.acquire, .acquire[data-theme="light"] { ${light} }`, + `.acquire[data-theme="dark"] { ${dark} }`, + `@media (prefers-color-scheme: dark) { .acquire:not([data-theme]) { ${dark} } }`, + ].join(" "); +} + +/** + * The BGS theme known before the first theme event: the wrapper page marks + * (or passes ?dark=1) for the first paint. Undefined means no setting yet. + */ +export function initialTheme(): "dark" | undefined { + const dark = + document.documentElement.classList.contains("dark") || new URLSearchParams(location.search).get("dark") === "1"; + return dark ? "dark" : undefined; +} + +export interface ChainStyle { + /** Tile and marker fill. */ + fill: string; + /** Label colour on that fill, chosen for at least 4.5:1 contrast. */ + text: string; + /** Shown on every chain tile and marker, so colour is never the only signal. */ + letter: string; + /** Colour-blind mode: a pattern structurally different from every other chain's. */ + pattern: Pattern; + /** The pattern's ink: the label colour blended into the fill, softened to just over 3:1. */ + patternInk: string; +} + +export type Pattern = "stripes" | "bars" | "diagonalUp" | "diagonalDown" | "dots" | "checker" | "crosshatch"; + +/** + * CSS background for a chain pattern. Sizes are percentages of the tile, so the same pattern + * reads the same on a 26px phone square and a 44px desktop square. + */ +export function patternCss(pattern: Pattern | "grid", ink: string): string { + const lines = (angle: number, width = 9) => + `repeating-linear-gradient(${angle}deg, ${ink} 0 ${width}%, transparent ${width}% 25%)`; + switch (pattern) { + case "stripes": + return lines(0); + case "bars": + return lines(90); + case "diagonalUp": + return lines(45); + case "diagonalDown": + return lines(135); + case "dots": + return `radial-gradient(circle, ${ink} 0 30%, transparent 33%) 0 0 / 25% 25%`; + case "checker": + return `conic-gradient(${ink} 0 25%, transparent 0 50%, ${ink} 0 75%, transparent 0) 0 0 / 50% 50%`; + case "crosshatch": + return `${lines(45, 6)}, ${lines(135, 6)}`; + case "grid": + return `${lines(0, 7)}, ${lines(90, 7)}`; + } +} + +// Okabe-Ito without its black and yellow (they clash with the board), nudged and with a violet +// added so every pair stays apart under each colour-vision deficiency. See palette.spec.ts. +export const CHAIN_STYLES: Record = { + tower: { fill: "#b44906", text: "#ffffff", letter: "T", pattern: "stripes", patternInk: "#e6c1aa" }, + luxor: { fill: "#d08200", text: "#000000", letter: "L", pattern: "bars", patternInk: "#603c00" }, + worldwide: { fill: "#a16494", text: "#000000", letter: "W", pattern: "diagonalUp", patternInk: "#3a2435" }, + american: { fill: "#5285e0", text: "#000000", letter: "A", pattern: "diagonalDown", patternInk: "#22385e" }, + festival: { fill: "#0b7d59", text: "#ffffff", letter: "F", pattern: "dots", patternInk: "#b1d5ca" }, + imperial: { fill: "#7a2ac4", text: "#ffffff", letter: "I", pattern: "checker", patternInk: "#c4a1e5" }, + continental: { fill: "#21c5e2", text: "#000000", letter: "C", pattern: "crosshatch", patternInk: "#116473" }, +}; + +/** The Okabe-Ito colour each chain colour started from (the violet is new). */ +export const OKABE_ITO_ORIGIN: Partial> = { + tower: "#d55e00", + luxor: "#e69f00", + worldwide: "#cc79a7", + american: "#0072b2", + festival: "#009e73", + continental: "#56b4e9", +}; diff --git a/packages/viewer/src/lib/priceTable.spec.ts b/packages/viewer/src/lib/priceTable.spec.ts new file mode 100644 index 0000000..ada1d5c --- /dev/null +++ b/packages/viewer/src/lib/priceTable.spec.ts @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { chainsInTier, priceTable, rangeLabel, rowIndexFor } from "./priceTable.ts"; + +// rules.md §8, transcribed: minor sizes, medium sizes, major sizes, price, 1st bonus, 2nd bonus. +const RULES_TABLE = [ + ["2", "—", "—", 200, 2000, 1000], + ["3", "2", "—", 300, 3000, 1500], + ["4", "3", "2", 400, 4000, 2000], + ["5", "4", "3", 500, 5000, 2500], + ["6–10", "5", "4", 600, 6000, 3000], + ["11–20", "6–10", "5", 700, 7000, 3500], + ["21–30", "11–20", "6–10", 800, 8000, 4000], + ["31–40", "21–30", "11–20", 900, 9000, 4500], + ["41+", "31–40", "21–30", 1000, 10000, 5000], + ["—", "41+", "31–40", 1100, 11000, 5500], + ["—", "—", "41+", 1200, 12000, 6000], +]; + +test("§8 the generated price table matches the rules table row for row", () => { + const generated = priceTable().map((row) => [ + rangeLabel(row.sizes.minor), + rangeLabel(row.sizes.medium), + rangeLabel(row.sizes.major), + row.price, + row.first, + row.second, + ]); + assert.deepEqual(generated, RULES_TABLE); +}); + +test("§8 tier columns are headed by the chains of that tier", () => { + assert.deepEqual(chainsInTier("minor"), ["tower", "luxor"]); + assert.deepEqual(chainsInTier("medium"), ["worldwide", "american", "festival"]); + assert.deepEqual(chainsInTier("major"), ["imperial", "continental"]); +}); + +test("a chain's current size is marked in the right row", () => { + const table = priceTable(); + assert.equal(table[rowIndexFor(table, "minor", 7)]!.price, 600); + assert.equal(table[rowIndexFor(table, "medium", 11)]!.price, 800); + assert.equal(table[rowIndexFor(table, "major", 2)]!.price, 400); + assert.equal(table[rowIndexFor(table, "major", 60)]!.price, 1200); +}); diff --git a/packages/viewer/src/lib/priceTable.ts b/packages/viewer/src/lib/priceTable.ts new file mode 100644 index 0000000..85a4adf --- /dev/null +++ b/packages/viewer/src/lib/priceTable.ts @@ -0,0 +1,68 @@ +// The information card's price table (rules.md §8), generated from the engine's price functions +// and chain config so the viewer never holds its own copy of the numbers. +import { CHAINS, TILE_COUNT, majorityBonus, minorityBonus, sharePrice, type ChainId, type Tier } from "acquire-engine"; + +export const TIERS: Tier[] = ["minor", "medium", "major"]; + +/** Chain sizes in one tier that share a price: `to` is null for an open-ended range ("41+"). */ +export interface SizeRange { + from: number; + to: number | null; +} + +export interface PriceRow { + price: number; + first: number; + second: number; + sizes: Record; +} + +export function chainsInTier(tier: Tier): ChainId[] { + return CHAINS.filter((chain) => chain.tier === tier).map((chain) => chain.id); +} + +/** Every price row, cheapest first, with each tier's size range for that price. */ +export function priceTable(): PriceRow[] { + const rows = new Map(); + for (const tier of TIERS) { + const chain = chainsInTier(tier)[0]!; + for (let size = 2; size <= TILE_COUNT; size++) { + const price = sharePrice(chain, size); + let row = rows.get(price); + if (!row) { + row = { + price, + first: majorityBonus(chain, size), + second: minorityBonus(chain, size), + sizes: { minor: null, medium: null, major: null }, + }; + rows.set(price, row); + } + const range = row.sizes[tier]; + if (range) { + range.to = size === TILE_COUNT ? null : size; + } else { + row.sizes[tier] = { from: size, to: size === TILE_COUNT ? null : size }; + } + } + } + return [...rows.values()].sort((a, b) => a.price - b.price); +} + +export function rangeLabel(range: SizeRange | null): string { + if (!range) { + return "—"; + } + if (range.to === null) { + return `${range.from}+`; + } + return range.from === range.to ? `${range.from}` : `${range.from}–${range.to}`; +} + +/** The row a chain of this tier and size falls in. */ +export function rowIndexFor(table: PriceRow[], tier: Tier, size: number): number { + return table.findIndex((row) => { + const range = row.sizes[tier]; + return range !== null && size >= range.from && (range.to === null || size <= range.to); + }); +} diff --git a/packages/viewer/src/lib/replay.ts b/packages/viewer/src/lib/replay.ts new file mode 100644 index 0000000..4fa38c5 --- /dev/null +++ b/packages/viewer/src/lib/replay.ts @@ -0,0 +1,41 @@ +// BGS replay controls: the state to display at a log position, built from the engine's +// positionAt (the public log replayed with the engine's own placement functions). +import { CHAIN_IDS, HIDDEN, positionAt, seatsOf, type GameState, type Shares } from "acquire-engine"; + +const HIDDEN_SHARES = Object.fromEntries(CHAIN_IDS.map((chain) => [chain, HIDDEN])) as Shares; + +/** The first replay position: the board after setup, at the start of the first turn. */ +export function replayStart(state: GameState): number { + const firstTurn = state.log.findIndex((entry) => entry.type === "turn"); + return firstTurn < 0 ? state.log.length : firstTurn + 1; +} + +/** + * The game as it stood after `at` log entries. Holdings show only where they are public now: + * public holdings, a finished game, or the viewer's own seats. Tiles in hand are never shown. + */ +export function replayView(state: GameState, player: number | undefined, at: number): GameState { + const position = positionAt(state, at); + const own = seatsOf(state, player); + const holdingsPublic = state.options.publicHoldings || state.ended; + return { + ...state, + board: position.board, + bank: position.bank, + seats: state.seats.map((seat, index) => { + const shown = position.seats[index]!; + const visible = holdingsPublic || own.includes(index); + return { + ...seat, + cash: visible ? shown.cash : HIDDEN, + shares: visible ? shown.shares : { ...HIDDEN_SHARES }, + hand: Array.from({ length: shown.tiles }, () => HIDDEN), + }; + }), + log: state.log.slice(0, at), + merger: null, + pendingTile: null, + endAnnounced: null, + ended: false, + }; +} diff --git a/packages/viewer/src/lib/store.svelte.ts b/packages/viewer/src/lib/store.svelte.ts new file mode 100644 index 0000000..6eacb05 --- /dev/null +++ b/packages/viewer/src/lib/store.svelte.ts @@ -0,0 +1,72 @@ +import { getContext } from "svelte"; +import type { PlayerAppearance } from "@boardgamers/protocol"; +import { ChatController } from "@boardgamers/protocol/chat"; +import { seatsOf, type GameState, type Move, type Tile } from "acquire-engine"; +import { movesFor } from "./decisions"; +import { langFor } from "./format"; +import { isRightToLeft, type Locale } from "./i18n"; +import { replayStart, replayView } from "./replay"; + +/** Context key: the store is given to every component at mount, for viewer-wide settings. */ +export const STORE = Symbol("viewer-store"); + +export function useStore(): ViewerStore { + return getContext(STORE); +} + +export class ViewerStore { + state = $state(); + /** The viewer's BGS player index; undefined for a spectator. */ + player = $state(); + /** The internal seats this player controls (two in fourHands, none for a spectator). */ + seats = $derived(this.state ? seatsOf(this.state, this.player) : []); + /** BGS replay: the log position being shown, or undefined when showing the live game. */ + replayAt = $state(); + /** What the viewer shows: the live state, or the replayed position. */ + view = $derived( + this.state && this.replayAt !== undefined ? replayView(this.state, this.player, this.replayAt) : this.state + ); + /** Legal moves for this viewer right now, straight from the engine; none while replaying. */ + moves = $derived(this.state && this.replayAt === undefined ? movesFor(this.state, this.seats) : []); + /** A tile chosen in the hand but not yet placed. */ + selected = $state(); + /** Player avatars from BGS, in player order. */ + avatars = $state([]); + /** BGS player appearance (colours, symbols, Supporter badges), in player order; cosmetic only. */ + appearance = $state(); + /** BGS interface language (preferences.locale), English until BGS sends one. */ + locale = $state("en"); + /** Text helpers in the current language. */ + lang = $derived(langFor(this.locale)); + rightToLeft = $derived(isRightToLeft(this.locale)); + /** True in a BGS analysis sandbox, where live chat is hidden. */ + analysis = $state(false); + /** The shared BGS chat, one controller per viewer launch. */ + readonly chat = new ChatController(); + /** BGS's shared colour-blind setting: adds a pattern to every chain tile and table marker. */ + colorBlind = $state(false); + /** The BGS light/dark setting; undefined until BGS sends one (prefers-color-scheme applies). */ + theme = $state<"light" | "dark" | undefined>(); + /** True between sending a move and receiving the resulting state, so it cannot be sent twice. */ + sending = $state(false); + + constructor(private readonly sendMove: (move: Move) => boolean) {} + + setState(state: GameState): void { + this.state = state; + this.selected = undefined; + this.sending = false; + } + + /** The replay range BGS shows in its controls: setup done, up to the live position. */ + replayRange(): { start: number; end: number } { + return { start: replayStart(this.state!), end: this.state!.log.length }; + } + + send(move: Move): void { + if (this.sending) { + return; + } + this.sending = this.sendMove(move); + } +} diff --git a/packages/viewer/src/lib/theme.css b/packages/viewer/src/lib/theme.css new file mode 100644 index 0000000..0016dbb --- /dev/null +++ b/packages/viewer/src/lib/theme.css @@ -0,0 +1,84 @@ +/* Square corners everywhere; outlines only on things the player can act on. */ +.acquire, +.acquire * { + box-sizing: border-box; + border-radius: 0 !important; +} + +/* Colour variables come from palette.ts (themeCss), the same values the palette test checks. */ +.acquire { + color: var(--ink); + background: var(--page); + font-family: + system-ui, + -apple-system, + "Segoe UI", + Roboto, + sans-serif; + font-size: 15px; + line-height: 1.4; + padding: 12px; +} + +.acquire h2 { + font-size: 14px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + margin: 0 0 6px; + padding: 0 0 2px; + box-shadow: inset 0 -3px 0 var(--accent); + display: inline-block; +} + +.acquire table { + border-collapse: collapse; + width: 100%; + font-size: 14px; +} + +.acquire th, +.acquire td { + padding: 4px 6px; + text-align: left; + border: none; +} + +.acquire th { + font-weight: 600; + color: var(--ink-muted); + font-size: 12px; +} + +.acquire tbody tr:nth-child(odd) { + background: var(--panel-alt); +} + +.acquire .num { + text-align: right; + font-variant-numeric: tabular-nums; +} + +.acquire .hidden-value { + color: var(--ink-muted); + font-style: italic; +} + +/* 2.5px, not 2px: outlines snap to device pixels, and 2px drops to 1.6px at 125% scaling. */ +.acquire .actionable { + outline: 2.5px solid var(--ink); + outline-offset: -2.5px; + cursor: pointer; +} + +/* Keyboard focus has its own indicator, distinct from the actionable outline and always on top. */ +.acquire :focus-visible { + outline: 3px solid var(--focus) !important; + outline-offset: 3px !important; + box-shadow: 0 0 0 6px var(--page); +} + +.acquire button:disabled { + outline: none; + cursor: default; +} diff --git a/packages/viewer/src/viewer.ts b/packages/viewer/src/viewer.ts new file mode 100644 index 0000000..8f48cbb --- /dev/null +++ b/packages/viewer/src/viewer.ts @@ -0,0 +1,61 @@ +import { mount, tick, unmount } from "svelte"; +import { registerViewer } from "@boardgamers/protocol/viewer"; +import type { GameState, Move } from "acquire-engine"; +import App from "./App.svelte"; +import { resolveLocale } from "./lib/i18n"; +import { initialTheme, themeCss } from "./lib/palette"; +import { STORE, ViewerStore } from "./lib/store.svelte"; +import "./lib/theme.css"; + +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); + }, + }; +}); diff --git a/packages/viewer/svelte.config.js b/packages/viewer/svelte.config.js new file mode 100644 index 0000000..f77d881 --- /dev/null +++ b/packages/viewer/svelte.config.js @@ -0,0 +1,5 @@ +import { vitePreprocess } from "@sveltejs/vite-plugin-svelte"; + +export default { + preprocess: vitePreprocess(), +}; diff --git a/packages/viewer/tsconfig.json b/packages/viewer/tsconfig.json new file mode 100644 index 0000000..fd33802 --- /dev/null +++ b/packages/viewer/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "types": ["vite/client", "node"], + "allowImportingTsExtensions": true, + "noEmit": true, + "allowJs": true, + "checkJs": false, + "isolatedModules": true, + "resolveJsonModule": true, + "esModuleInterop": true + }, + "include": ["src/**/*.ts", "src/**/*.svelte", "src/**/*.svelte.ts", "vite.config.ts"] +} diff --git a/packages/viewer/vite.config.ts b/packages/viewer/vite.config.ts new file mode 100644 index 0000000..25cffa1 --- /dev/null +++ b/packages/viewer/vite.config.ts @@ -0,0 +1,30 @@ +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { defineConfig } from "vite"; + +export default defineConfig({ + base: "./", + plugins: [svelte()], + build: { + outDir: "dist", + emptyOutDir: true, + cssCodeSplit: false, + sourcemap: true, + // Vite requires a bundle name; registerViewer owns the acquire global. + lib: { + name: "acquireBundle", + entry: "src/viewer.ts", + formats: ["iife"], + fileName: () => "acquire-viewer.iife.js", + }, + rollupOptions: { + output: { + assetFileNames: (asset) => + asset.names?.some((n) => n.endsWith(".css")) ? "acquire-viewer.css" : "[name]-[hash][extname]", + }, + }, + }, + server: { + port: 5173, + strictPort: false, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..dd890c2 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,1217 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + oxfmt: + specifier: 0.61.0 + version: 0.61.0(svelte@5.56.8) + oxlint: + specifier: 1.76.0 + version: 1.76.0 + svelte: + specifier: 5.56.8 + version: 5.56.8 + + packages/engine: + dependencies: + seedrandom: + specifier: 3.0.5 + version: 3.0.5 + devDependencies: + '@boardgamers/protocol': + specifier: 0.10.0 + version: 0.10.0 + '@types/node': + specifier: 24.10.1 + version: 24.10.1 + '@types/seedrandom': + specifier: 3.0.8 + version: 3.0.8 + typescript: + specifier: 5.9.3 + version: 5.9.3 + + packages/viewer: + dependencies: + '@boardgamers/protocol': + specifier: 0.10.0 + version: 0.10.0 + acquire-engine: + specifier: workspace:* + version: link:../engine + devDependencies: + '@sveltejs/vite-plugin-svelte': + specifier: 7.2.0 + version: 7.2.0(svelte@5.56.8)(vite@8.2.0(@types/node@24.10.1)) + '@types/node': + specifier: 24.10.1 + version: 24.10.1 + svelte: + specifier: 5.56.8 + version: 5.56.8 + svelte-check: + specifier: 4.7.4 + version: 4.7.4(picomatch@4.0.7)(svelte@5.56.8)(typescript@5.9.3) + typescript: + specifier: 5.9.3 + version: 5.9.3 + vite: + specifier: 8.2.0 + version: 8.2.0(@types/node@24.10.1) + +packages: + + '@boardgamers/protocol@0.10.0': + resolution: {integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@oxc-project/types@0.154.0': + resolution: {integrity: sha512-KYOUGQFlLWR+s4QMV2Q9ko38TZm7EdO87Qm7rvZLqk/webse/cDjtyxKhg/47l0byCbs/k46LT8qc4PKjAikzA==} + + '@oxfmt/binding-android-arm-eabi@0.61.0': + resolution: {integrity: sha512-BaS+1OVvg9sr+Xav0+KdWedQRcAzrdoEcwMZeqoc2F6ieC1s/t5eM35YQoRPQ7vAqkZ+p3tbQb1r9I9mrV5oGA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxfmt/binding-android-arm64@0.61.0': + resolution: {integrity: sha512-of8atAV0M1egGcVOMbgZCvc10sFOP3ayQBNQV5h5G3fNq8gACdEswfFk9bzGrdbM23rtg0Coxi7np7oPLcueNw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxfmt/binding-darwin-arm64@0.61.0': + resolution: {integrity: sha512-7l8+5ov4BGwtAcmpzvEik/TG3bciwyw/S3e6j5GKH7pcQqcgCVxD3AuJeP6upto+SOTBKQ4wrrdbMt0gq8fHSQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxfmt/binding-darwin-x64@0.61.0': + resolution: {integrity: sha512-Fnz4dDDXBb7udk+DmwelNjxbD6yptyxwCqwCH2ebo4RVLxVsRfFsn/AHJC49KIltPrVokamGv4SSOsiV50DTxQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxfmt/binding-freebsd-x64@0.61.0': + resolution: {integrity: sha512-mddOebKNCP+AucmzfNsk3jgbr681qAUvgMqi865GW5gWLJ/AnzXbvjQRrny0e++NAN8aphav/aRSrfFxNsNjpA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxfmt/binding-linux-arm-gnueabihf@0.61.0': + resolution: {integrity: sha512-svx59iYL+DbaZGZUIoice4W0CjRXGExnbz7Re+awIb60rVxBS2KrU7Hnlx+nZYanLGLpjneUEgo/VFEKkSZAyQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxfmt/binding-linux-arm-musleabihf@0.61.0': + resolution: {integrity: sha512-BYK9MPJPCf6d+fLKMTruThmEyCtHzQ1zLcsrTlUVkmnoXIaHAbfpeLYQwX1tkjs7W11dyzoi6HFvKcdnvX1zNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxfmt/binding-linux-arm64-gnu@0.61.0': + resolution: {integrity: sha512-QUaCNLq2/EC6G5ljOuFanl9Lgw6ZWp4co7rs4+KOMUzbGfA4Lq58FHRjjF9sVIG+93XSbo343MxFATrOU1qctA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-arm64-musl@0.61.0': + resolution: {integrity: sha512-S6uvJ6MXnRXl+zTs0CARNDvkE+cymj0EVWEKKsyKnlLlqTyQJBjw5s4D2pSIOZc+S46cy4STefzcr/sm0VzVPA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-linux-ppc64-gnu@0.61.0': + resolution: {integrity: sha512-6VDlRcytvZG6UlSIdAFKDLbppo9tvPxrWzle6vHldYFMeuDPQEfMKrkwezp7FaBq1wik9ra554ZZeRPsyIkFpg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-riscv64-gnu@0.61.0': + resolution: {integrity: sha512-KkBTYbzExpbmn15XjKPLu2fRV2PVlq+KWt+brad5rwIa03vdYoaDRWiS7raHII/dCTR6Ro4UpYUCH4t6lif4WQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-riscv64-musl@0.61.0': + resolution: {integrity: sha512-69tzIq7sJLVB9dxYYtvMzcSSsnZHSO+U2U19O2RqDqgj6+Q4O7HjSXdaszbcgqzhsUwzSH7z5kWvk8nmf6BHTg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-linux-s390x-gnu@0.61.0': + resolution: {integrity: sha512-Oqi/N0OvtOVXsPKAOOhKgGH3msRYF8BLJaNBbWiupRiKoKVyc8JRKPCfarkQJC+RgP9U8raUKLe+bNwd0HUMiA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-x64-gnu@0.61.0': + resolution: {integrity: sha512-3TKwv/ed4uwJSemAA8P9XcoqETpjQI4waquF9UilhA9Mn/dhr1PdUEXWlL74mtc6ZNfmKPA9+NEJm01nRF8CVA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxfmt/binding-linux-x64-musl@0.61.0': + resolution: {integrity: sha512-uFso4u4nLkVSlMCpgjyvWV60Gt7GvDQHnk1mmRxHIkZTMB0ljpUKwCD9FYGgN9H97x2wYl0UwEjgRZaPIuhEhw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxfmt/binding-openharmony-arm64@0.61.0': + resolution: {integrity: sha512-keGLkzeOvkMpNmPp4hffXWpfoSsY6e1K8++KXD4mSSfxdvM8q9QUDsYY689TB1k6Co832DZn1MnaaVx6cIBMWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxfmt/binding-win32-arm64-msvc@0.61.0': + resolution: {integrity: sha512-VzsAISkFxmNhJ5LBDEL9VuH6tJsVJMtqYit2LyIUf/HLnsCe4Pg9SMOjjVQzGWt0bnpyfJ94CrqTqcpNZzK+ug==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxfmt/binding-win32-ia32-msvc@0.61.0': + resolution: {integrity: sha512-xv4t7yzwJoYaLB6Zv28B3W+j7brEjsyv50rLTAQgmxJzddce9fAMCxed8dSAkbWES0zz2J29nYK5FaTuD2YBHg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxfmt/binding-win32-x64-msvc@0.61.0': + resolution: {integrity: sha512-6EZXFkqOwxdDYjIn3TSNnPk3ST5E5GiYd4FiM6UF/mCL/LZSfr6D6UygTfW3R1PCQP2quCKpCEGRlij8E3VYbg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@oxlint/binding-android-arm-eabi@1.76.0': + resolution: {integrity: sha512-ZHIE5Zt9AsPDcY4nOlofXt0YfneEeo+QrKMPcPzLf2Z6Q8VtV2W73d7SFJ920WUwyik783u/doKCs3KXdwG+7w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxlint/binding-android-arm64@1.76.0': + resolution: {integrity: sha512-shm/ngQilHK6bs+ElJWa4oHfNj5vL1Gl/iVEJldTQjpr0/67oSgr0KUpbmcnLig5Fo0v/l6j2567A7TOL89ONA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxlint/binding-darwin-arm64@1.76.0': + resolution: {integrity: sha512-rvJmrAPKSQ9aWJ6wIS6CK2tJjwzfW0ApQH9qokq6sfDvmHwoyIHxHFMq7z7i7GiV6fdE6s8qvBqWKPTu8RmT6Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxlint/binding-darwin-x64@1.76.0': + resolution: {integrity: sha512-U/zYdb7VYKGY6pA9Vd2rYl9O/HlCylcOlb5PGPvVLtg+oLGsk6H3XGKEMHKyqD3nmmtmlmwb/8SwU2vfSAtvMw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxlint/binding-freebsd-x64@1.76.0': + resolution: {integrity: sha512-WvKG9CAriuo0XNiFzpXjDngUZcRGFNpaK2kLyMUsnJlShxkT96u+BpJQ3KqdQwGOrvI14L6V8bAwXwAYNNY6Jg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxlint/binding-linux-arm-gnueabihf@1.76.0': + resolution: {integrity: sha512-qJ5+RH99TqFRq3UCDxkW0zJJu9c+OAHFY72vGlxZLEpuO+MpKo3POgqb8sYipL9KYm8XY6ofb0HsOuvY6hQNqQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm-musleabihf@1.76.0': + resolution: {integrity: sha512-PvPCVptkgVARsucgIqFQQcSmJ6xc6GtnVB5bRBekRahTc9eObMtjHfMjy5M+C2tHt5UCMttWM9RuSk/H9NqYeg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxlint/binding-linux-arm64-gnu@1.76.0': + resolution: {integrity: sha512-3KeFDx8Bu4HPAXbuHZOr/oHvN+QT+JQhMw/NYPz7Z071xLSsG27Jfh9PIQVEY7hk1I+jr43ExqRIeJ6VKk2yLw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-arm64-musl@1.76.0': + resolution: {integrity: sha512-oPFkkKTgl0K/EIg9fQ8oA3IGcI05/Mq1en04iFa41mmNPT+6KEiByVazTOZZJiHMBBrbsns1YJ2e1Scqwzesjw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-ppc64-gnu@1.76.0': + resolution: {integrity: sha512-gN7yZ0eqflA5Fhf1wvHxGUltIV3FsvmB1zhNMDEK9vSHhc7E6qg9CuPeBgPZab66Tjzq6w6kHAtNEvnTHf4cyw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-gnu@1.76.0': + resolution: {integrity: sha512-S/HqMbn22mQrjtErUxEoS/a55u8kIeXvreIxiJu5G7Le3UecEd6SQZxrDIpuhtgaFnsY/nVra3ytP+pRljDilA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-riscv64-musl@1.76.0': + resolution: {integrity: sha512-ZIga3097VJZolGZk6SrIAUokIGfRkxRlhiHDUznZptGBfwrhD7pNfD1rzEzsCwvk/1DX0A1bLz+liuNh5QKIVQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxlint/binding-linux-s390x-gnu@1.76.0': + resolution: {integrity: sha512-ZGiiA7pFzMJSyMWYZTVlPgbTsx+Vl8ihLGMIujPwaslUF7kIPPWAbVmAlTc+9lWDV+DCiB8Ikixu+lSHeOIIWQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-gnu@1.76.0': + resolution: {integrity: sha512-JLiy5WuvEBFTT6ErIFV35SLzi0R7Iri6MKU6dZbTxfIx8pndbbPs3Mj780nMipBFcPkti+okAPOJ9POKkHFEgg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxlint/binding-linux-x64-musl@1.76.0': + resolution: {integrity: sha512-z7lgKQtbo/I1NIe8G5NHLesxJDv0tRSUWTpXKb9Pm3E9nKFKfO4IOSDtFroKgXtOYb0jQbcdH+0wzTyMXVes+A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxlint/binding-openharmony-arm64@1.76.0': + resolution: {integrity: sha512-JOjKymIpb9QcYfEhZsN6h4V9Ivd474W38cNIBRv6bg2TbIvogbMTH0Mg6YWW9TiRDqfcX+/Hyfsbo5vcSE5guQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxlint/binding-win32-arm64-msvc@1.76.0': + resolution: {integrity: sha512-pqDWZiwcmByWUEm1NFUBNiT6aentCcaoMWJv0HbXEmuYermJ4sg8ppVrshubYP2MZ6SHccJJcpr6x469PuDFIw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxlint/binding-win32-ia32-msvc@1.76.0': + resolution: {integrity: sha512-Ba0O659kgMv6pwO3z9PdO+K3aMxQRaw9HnG+e6AtOfgwcKFvYilciQYBoUBmxfQvOCKZe1SwjMkuB542NkuDMQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxlint/binding-win32-x64-msvc@1.76.0': + resolution: {integrity: sha512-5qcirPHO8nKfkoowEVWtpAoVTcYDy6g0UT0NGic450Qv8J2NrOqg4uQ8QppRP4MDTC7Xx47lbZnmadTH03CGGA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/binding-android-arm-eabi@1.2.14': + resolution: {integrity: sha512-aWR+XKH9+rW7m5fWq/5360J3mHycrx/o6xZM2DQFdJnTMdyP7/WzxPjhtLbVWdKo2y612/4U1bWqb3HQhiF7vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.14': + resolution: {integrity: sha512-QiVxHofl6A8lQU7WAtOUY4QMVZXohxwz7WJJoeh8NBEUyKfIkMRKhYyq8az/1RypNiIXzNTtiS6KwHz0erxYRQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.14': + resolution: {integrity: sha512-lTQOzHuBIooh3jIr5XINQkjPGEuGy+Dsy0meXDr6Sjty0b99kYgGh4uBC/8mJX1T0kC8d6S0aPP1Y+bHkh6aBw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.14': + resolution: {integrity: sha512-hyMKEGatjmBYCs/Q4sbIcL/GqpFEqsX3wc+HYVQ/85A4rxc1o7rPm4DUI4GV4k/h0ITddwFSGpqQunI14GXjTA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.14': + resolution: {integrity: sha512-u371GbXoVXrEgP20PwzoGNOdAOqAMhzo19JzzY+V4YmmnC+DTOoqdbMu+O+54emM59Mik/UdrtWgcuEDKWRPKA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.14': + resolution: {integrity: sha512-BqwKsdZQf6EqVWr8fv2MrDYzAvOZ7+NYFSJESRGs87fkseEhs0TU9TXgRJTkZoRRkxTizyEg1LKUXfU3/78uqg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.14': + resolution: {integrity: sha512-SD9kY8M009x/7s57Z1dgUVlP5+uYBgKQK0Tkr1WIWngrtUJmRCW1RJFMY7QDla2khXhmg2i5Io7MUjcmZNZ/KQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.14': + resolution: {integrity: sha512-BJ2CL19M6uuWesMgnqJzgxoI+N+eV7b0A9O9vLV42y+gitC41fNa8KElau1tHVzuLWX5GzEuxMPhAO0tQXQMkg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.14': + resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.14': + resolution: {integrity: sha512-V/h8ePq1fKDrmtFMz6xcCN3DKvuvMRrwwD1q0PkBeeo4DpK64biaKvqWGVxqCeYKqeRk7gE7/iKPxLCn08O97A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.14': + resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.14': + resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.14': + resolution: {integrity: sha512-qyr5XiNGxm2ytx17vvtcJ9nXn6v1gENETi503bJx3OGwZ1tSonj7BosxbMa/xeAfSl5iS9X6KjEWYXLu6v1L7Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.14': + resolution: {integrity: sha512-oA4o5o0S2yB199YyYXDzKUv1Z56Rc+mgOjwm7Z/vJ9Z8igiDPYvoOuDyo6g7AK/ZaF09nPhDKVnGBcYHO11GXA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.14': + resolution: {integrity: sha512-9mE94bf2GZUaR/fUSXCMpBoWkctu421Mi0ORpm4zqfbkjKep7RxzPFa5etcGs5h+2KApoWBOA/hAJa/7saGgEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@sveltejs/acorn-typescript@1.0.13': + resolution: {integrity: sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==} + peerDependencies: + acorn: ^8.9.0 + + '@sveltejs/load-config@0.2.3': + resolution: {integrity: sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==} + engines: {node: '>= 18.0.0'} + + '@sveltejs/vite-plugin-svelte@7.2.0': + resolution: {integrity: sha512-1SpkuMSRLfugrVX+IrKfE1RUegzo8AQzKQ6qQPfVzbcWi5IhuTPaKb5ZrLpucleFznkc4/RTeSPoRnGWFxX+EQ==} + engines: {node: ^20.19 || ^22.12 || >=24} + peerDependencies: + svelte: ^5.46.4 + vite: ^8.0.0-beta.7 || ^8.0.0 + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/node@24.10.1': + resolution: {integrity: sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==} + + '@types/seedrandom@3.0.8': + resolution: {integrity: sha512-TY1eezMU2zH2ozQoAFAQFOPpvP15g+ZgSfTZt31AUUH/Rxtnz3H+A/Sv1Snw2/amp//omibc+AEkTaA8KUeOLQ==} + + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + + acorn@8.19.0: + resolution: {integrity: sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==} + engines: {node: '>=0.4.0'} + hasBin: true + + aria-query@5.3.1: + resolution: {integrity: sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==} + engines: {node: '>= 0.4'} + + axobject-query@4.1.0: + resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} + engines: {node: '>= 0.4'} + + chokidar@4.0.3: + resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} + engines: {node: '>= 14.16.0'} + + clsx@2.1.1: + resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} + engines: {node: '>=6'} + + deepmerge@4.3.1: + resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} + engines: {node: '>=0.10.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + devalue@5.9.4: + resolution: {integrity: sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==} + + esm-env@1.2.2: + resolution: {integrity: sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==} + + esrap@2.4.0: + resolution: {integrity: sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==} + peerDependencies: + '@typescript-eslint/types': ^8.2.0 + peerDependenciesMeta: + '@typescript-eslint/types': + optional: true + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + is-reference@3.0.3: + resolution: {integrity: sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + locate-character@3.0.0: + resolution: {integrity: sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + mri@1.2.0: + resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} + engines: {node: '>=4'} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + obug@2.2.1: + resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} + engines: {node: '>=12.20.0'} + + oxfmt@0.61.0: + resolution: {integrity: sha512-DxdHBEMYpcEnHoUHjjOigUqV2TYKsvxLwUPXnVYBjgFdqrcQ/91OtwubtZ2PUodCs3sStI8R5Qw3fKNGK4e8wQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + svelte: ^5.0.0 + vite-plus: '*' + peerDependenciesMeta: + svelte: + optional: true + vite-plus: + optional: true + + oxlint@1.76.0: + resolution: {integrity: sha512-6QoFioEU4fNdiUx/2Eo6TRd6NG7H7njnRCz8rhB66cZmMHDTqcm1Rjvl8Wry+ZTQMBAmyb4Mlf62Mk5X+eHSOw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + oxlint-tsgolint: '>=7.0.2001' + vite-plus: '*' + peerDependenciesMeta: + oxlint-tsgolint: + optional: true + vite-plus: + optional: true + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.31: + resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} + engines: {node: ^10 || ^12 || >=14} + + readdirp@4.1.2: + resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} + engines: {node: '>= 14.18.0'} + + rolldown@1.2.14: + resolution: {integrity: sha512-eTBTTqMR6uHKLgcUqpJP8ntzDI6V4LYA8negAMBEI7gkgVvOdrx6VsvS2Ym+83KhOPdLCHWJu0w7UQFJZhHKNw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + sade@1.8.1: + resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} + engines: {node: '>=6'} + + seedrandom@3.0.5: + resolution: {integrity: sha512-8OwmbklUNzwezjGInmZ+2clQmExQPvomqjL7LFqOYqtmuxRgQYqOD3mHaU+MvZn5FLUeVxVfQjwLZW/n/JFuqg==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + svelte-check@4.7.4: + resolution: {integrity: sha512-IW9ot9YqAoyv8FvyN+eb4ZTe8zgcKZrJLNYU6dzSKkGwEBsSPc4K7lmQ8bKn8W2YMXM6WDfZSSVOaGtekyUfOQ==} + engines: {node: '>= 18.0.0'} + hasBin: true + peerDependencies: + svelte: ^4.0.0 || ^5.0.0-next.0 + typescript: ^5.0.0 || ^6.0.0 + + svelte@5.56.8: + resolution: {integrity: sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinypool@2.1.0: + resolution: {integrity: sha512-Pugqs6M0m7Lv1I7FtxN4aoyToKg1C4tu+/381vH35y8oENM/Ai7f7C4StcoK4/+BSw9ebcS8jRiVrORFKCALLw==} + engines: {node: ^20.0.0 || >=22.0.0} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.16.0: + resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + + vite@8.2.0: + resolution: {integrity: sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.4.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitefu@1.1.3: + resolution: {integrity: sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==} + peerDependencies: + vite: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + vite: + optional: true + + zimmerframe@1.1.5: + resolution: {integrity: sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==} + + zod@4.6.7: + resolution: {integrity: sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==} + +snapshots: + + '@boardgamers/protocol@0.10.0': + dependencies: + zod: 4.6.7 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@oxc-project/types@0.154.0': {} + + '@oxfmt/binding-android-arm-eabi@0.61.0': + optional: true + + '@oxfmt/binding-android-arm64@0.61.0': + optional: true + + '@oxfmt/binding-darwin-arm64@0.61.0': + optional: true + + '@oxfmt/binding-darwin-x64@0.61.0': + optional: true + + '@oxfmt/binding-freebsd-x64@0.61.0': + optional: true + + '@oxfmt/binding-linux-arm-gnueabihf@0.61.0': + optional: true + + '@oxfmt/binding-linux-arm-musleabihf@0.61.0': + optional: true + + '@oxfmt/binding-linux-arm64-gnu@0.61.0': + optional: true + + '@oxfmt/binding-linux-arm64-musl@0.61.0': + optional: true + + '@oxfmt/binding-linux-ppc64-gnu@0.61.0': + optional: true + + '@oxfmt/binding-linux-riscv64-gnu@0.61.0': + optional: true + + '@oxfmt/binding-linux-riscv64-musl@0.61.0': + optional: true + + '@oxfmt/binding-linux-s390x-gnu@0.61.0': + optional: true + + '@oxfmt/binding-linux-x64-gnu@0.61.0': + optional: true + + '@oxfmt/binding-linux-x64-musl@0.61.0': + optional: true + + '@oxfmt/binding-openharmony-arm64@0.61.0': + optional: true + + '@oxfmt/binding-win32-arm64-msvc@0.61.0': + optional: true + + '@oxfmt/binding-win32-ia32-msvc@0.61.0': + optional: true + + '@oxfmt/binding-win32-x64-msvc@0.61.0': + optional: true + + '@oxlint/binding-android-arm-eabi@1.76.0': + optional: true + + '@oxlint/binding-android-arm64@1.76.0': + optional: true + + '@oxlint/binding-darwin-arm64@1.76.0': + optional: true + + '@oxlint/binding-darwin-x64@1.76.0': + optional: true + + '@oxlint/binding-freebsd-x64@1.76.0': + optional: true + + '@oxlint/binding-linux-arm-gnueabihf@1.76.0': + optional: true + + '@oxlint/binding-linux-arm-musleabihf@1.76.0': + optional: true + + '@oxlint/binding-linux-arm64-gnu@1.76.0': + optional: true + + '@oxlint/binding-linux-arm64-musl@1.76.0': + optional: true + + '@oxlint/binding-linux-ppc64-gnu@1.76.0': + optional: true + + '@oxlint/binding-linux-riscv64-gnu@1.76.0': + optional: true + + '@oxlint/binding-linux-riscv64-musl@1.76.0': + optional: true + + '@oxlint/binding-linux-s390x-gnu@1.76.0': + optional: true + + '@oxlint/binding-linux-x64-gnu@1.76.0': + optional: true + + '@oxlint/binding-linux-x64-musl@1.76.0': + optional: true + + '@oxlint/binding-openharmony-arm64@1.76.0': + optional: true + + '@oxlint/binding-win32-arm64-msvc@1.76.0': + optional: true + + '@oxlint/binding-win32-ia32-msvc@1.76.0': + optional: true + + '@oxlint/binding-win32-x64-msvc@1.76.0': + optional: true + + '@rolldown/binding-android-arm-eabi@1.2.14': + optional: true + + '@rolldown/binding-android-arm64@1.2.14': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.14': + optional: true + + '@rolldown/binding-darwin-x64@1.2.14': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.14': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.14': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.14': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.14': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.14': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.14': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.14': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.14': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.14': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.14': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.14': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@sveltejs/acorn-typescript@1.0.13(acorn@8.19.0)': + dependencies: + acorn: 8.19.0 + + '@sveltejs/load-config@0.2.3': {} + + '@sveltejs/vite-plugin-svelte@7.2.0(svelte@5.56.8)(vite@8.2.0(@types/node@24.10.1))': + dependencies: + deepmerge: 4.3.1 + magic-string: 0.30.21 + obug: 2.2.1 + svelte: 5.56.8 + vite: 8.2.0(@types/node@24.10.1) + vitefu: 1.1.3(vite@8.2.0(@types/node@24.10.1)) + + '@types/estree@1.0.9': {} + + '@types/node@24.10.1': + dependencies: + undici-types: 7.16.0 + + '@types/seedrandom@3.0.8': {} + + '@types/trusted-types@2.0.7': {} + + acorn@8.19.0: {} + + aria-query@5.3.1: {} + + axobject-query@4.1.0: {} + + chokidar@4.0.3: + dependencies: + readdirp: 4.1.2 + + clsx@2.1.1: {} + + deepmerge@4.3.1: {} + + detect-libc@2.1.2: {} + + devalue@5.9.4: {} + + esm-env@1.2.2: {} + + esrap@2.4.0: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + is-reference@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + locate-character@3.0.0: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + mri@1.2.0: {} + + nanoid@3.3.20: {} + + obug@2.2.1: {} + + oxfmt@0.61.0(svelte@5.56.8): + dependencies: + tinypool: 2.1.0 + optionalDependencies: + '@oxfmt/binding-android-arm-eabi': 0.61.0 + '@oxfmt/binding-android-arm64': 0.61.0 + '@oxfmt/binding-darwin-arm64': 0.61.0 + '@oxfmt/binding-darwin-x64': 0.61.0 + '@oxfmt/binding-freebsd-x64': 0.61.0 + '@oxfmt/binding-linux-arm-gnueabihf': 0.61.0 + '@oxfmt/binding-linux-arm-musleabihf': 0.61.0 + '@oxfmt/binding-linux-arm64-gnu': 0.61.0 + '@oxfmt/binding-linux-arm64-musl': 0.61.0 + '@oxfmt/binding-linux-ppc64-gnu': 0.61.0 + '@oxfmt/binding-linux-riscv64-gnu': 0.61.0 + '@oxfmt/binding-linux-riscv64-musl': 0.61.0 + '@oxfmt/binding-linux-s390x-gnu': 0.61.0 + '@oxfmt/binding-linux-x64-gnu': 0.61.0 + '@oxfmt/binding-linux-x64-musl': 0.61.0 + '@oxfmt/binding-openharmony-arm64': 0.61.0 + '@oxfmt/binding-win32-arm64-msvc': 0.61.0 + '@oxfmt/binding-win32-ia32-msvc': 0.61.0 + '@oxfmt/binding-win32-x64-msvc': 0.61.0 + svelte: 5.56.8 + + oxlint@1.76.0: + optionalDependencies: + '@oxlint/binding-android-arm-eabi': 1.76.0 + '@oxlint/binding-android-arm64': 1.76.0 + '@oxlint/binding-darwin-arm64': 1.76.0 + '@oxlint/binding-darwin-x64': 1.76.0 + '@oxlint/binding-freebsd-x64': 1.76.0 + '@oxlint/binding-linux-arm-gnueabihf': 1.76.0 + '@oxlint/binding-linux-arm-musleabihf': 1.76.0 + '@oxlint/binding-linux-arm64-gnu': 1.76.0 + '@oxlint/binding-linux-arm64-musl': 1.76.0 + '@oxlint/binding-linux-ppc64-gnu': 1.76.0 + '@oxlint/binding-linux-riscv64-gnu': 1.76.0 + '@oxlint/binding-linux-riscv64-musl': 1.76.0 + '@oxlint/binding-linux-s390x-gnu': 1.76.0 + '@oxlint/binding-linux-x64-gnu': 1.76.0 + '@oxlint/binding-linux-x64-musl': 1.76.0 + '@oxlint/binding-openharmony-arm64': 1.76.0 + '@oxlint/binding-win32-arm64-msvc': 1.76.0 + '@oxlint/binding-win32-ia32-msvc': 1.76.0 + '@oxlint/binding-win32-x64-msvc': 1.76.0 + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.31: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + readdirp@4.1.2: {} + + rolldown@1.2.14: + dependencies: + '@oxc-project/types': 0.154.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.14 + '@rolldown/binding-android-arm64': 1.2.14 + '@rolldown/binding-darwin-arm64': 1.2.14 + '@rolldown/binding-darwin-x64': 1.2.14 + '@rolldown/binding-freebsd-x64': 1.2.14 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.14 + '@rolldown/binding-linux-arm64-gnu': 1.2.14 + '@rolldown/binding-linux-arm64-musl': 1.2.14 + '@rolldown/binding-linux-ppc64-gnu': 1.2.14 + '@rolldown/binding-linux-s390x-gnu': 1.2.14 + '@rolldown/binding-linux-x64-gnu': 1.2.14 + '@rolldown/binding-linux-x64-musl': 1.2.14 + '@rolldown/binding-openharmony-arm64': 1.2.14 + '@rolldown/binding-win32-arm64-msvc': 1.2.14 + '@rolldown/binding-win32-x64-msvc': 1.2.14 + + sade@1.8.1: + dependencies: + mri: 1.2.0 + + seedrandom@3.0.5: {} + + source-map-js@1.2.2: {} + + svelte-check@4.7.4(picomatch@4.0.7)(svelte@5.56.8)(typescript@5.9.3): + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@sveltejs/load-config': 0.2.3 + chokidar: 4.0.3 + fdir: 6.5.0(picomatch@4.0.7) + picocolors: 1.1.1 + sade: 1.8.1 + svelte: 5.56.8 + typescript: 5.9.3 + transitivePeerDependencies: + - picomatch + + svelte@5.56.8: + dependencies: + '@jridgewell/remapping': 2.3.5 + '@jridgewell/sourcemap-codec': 1.6.0 + '@sveltejs/acorn-typescript': 1.0.13(acorn@8.19.0) + '@types/estree': 1.0.9 + '@types/trusted-types': 2.0.7 + acorn: 8.19.0 + aria-query: 5.3.1 + axobject-query: 4.1.0 + clsx: 2.1.1 + devalue: 5.9.4 + esm-env: 1.2.2 + esrap: 2.4.0 + is-reference: 3.0.3 + locate-character: 3.0.0 + magic-string: 0.30.21 + zimmerframe: 1.1.5 + transitivePeerDependencies: + - '@typescript-eslint/types' + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinypool@2.1.0: {} + + typescript@5.9.3: {} + + undici-types@7.16.0: {} + + vite@8.2.0(@types/node@24.10.1): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.31 + rolldown: 1.2.14 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.10.1 + fsevents: 2.3.3 + + vitefu@1.1.3(vite@8.2.0(@types/node@24.10.1)): + optionalDependencies: + vite: 8.2.0(@types/node@24.10.1) + + zimmerframe@1.1.5: {} + + zod@4.6.7: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..dee51e9 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,2 @@ +packages: + - "packages/*" diff --git a/rules.md b/rules.md new file mode 100644 index 0000000..e115dab --- /dev/null +++ b/rules.md @@ -0,0 +1,365 @@ +# Acquire — Rules Specification for the BGS Engine + +The rules the engine implements, written so each one can be coded and tested. Where the +original 1976 rules were silent or ambiguous, the choice made here is marked +**[DECISION]**. Tests cite these section numbers. + +--- + +## 1. Components + +- **Board:** 12 columns × 9 rows. Columns are numbered 1–12, rows lettered A–I. + A square is written as number then letter, e.g. `1A`, `12I`. +- **Tiles:** 108 hotel tiles, exactly one per square. A tile can only ever be placed on + its own square. +- **Chains:** 7 hotel chains, each with a name and a price tier (see §8). +- **Stock:** 25 shares per chain, held by the bank until bought or awarded. +- **Money:** The bank's money is unlimited. All money is integer dollars, always a + multiple of $100. Never use floating point. +- **Players:** 2 to 6. Each starts with **$6,000**. + +## 2. Definitions + +- **Adjacent:** Two squares are adjacent if they share an edge (same row and + neighbouring column, or same column and neighbouring row). Diagonals are never adjacent. +- **Loose tile:** A tile on the board that is not part of any chain. +- **Chain:** A connected group of two or more tiles (connected via adjacency) that has + been assigned a chain name. Its **size** is the number of tiles in it. +- **Active chain:** A chain currently on the board. +- **Safe chain:** An active chain of size **11 or more**. A safe chain can never be + taken over. +- **Open chain:** An active chain of size 10 or less. +- **Defunct chain:** A chain that has just been taken over in a merger. Its name + becomes available again immediately after the merger resolves. + +## 3. Setup + +1. Shuffle all 108 tiles into a face-down draw pool using the game's seeded PRNG. +2. **Turn order:** Each player draws one tile and places it on the board. These tiles + stay on the board as loose tiles. They never form a chain at this point, even if + adjacent to one another. +3. The player who placed the **lowest** tile goes first. Compare by number first, then + letter: `2B` beats `2E` and `3A`. Play then proceeds clockwise (in seat order) from + that player. **[DECISION]** "Clockwise" means ascending seat order, wrapping around. +4. Each player then draws **6** tiles into their private hand. +5. **[DECISION]** Options are never rejected at setup. An option that does not apply to + the player count (see §15) is ignored, and the game log records that it was ignored. + +## 4. Turn Structure + +A turn is a sequence of phases. Model it as a state machine; several phases need input +from a player, and the merger phase needs input from players *other than* the active +player. + +1. **Place tile** (§5). May trigger **Found chain** (§6) or **Merger** (§7), which fully + resolve before continuing. +2. **Buy stock** (§9). Optional, up to 3 shares. +3. **End-of-game announcement** (§11). Optional. **[DECISION]** Allowed at exactly two + points: before placing a tile, and during the buy step (§11.1). +4. **Replace dead tiles** (§5.3). +5. **Draw** one tile to bring the hand back to 6, if the pool is not empty. + +If the game was announced as over during this turn, run final scoring (§11.2) after +the turn completes instead of passing to the next player. + +**[DECISION]** Steps where a player has nothing to decide are skipped automatically, but +an announcement point is never skipped. If an end condition (§11.1) holds before placing, +the player gets the placement step even with no playable tile (they may announce, then +pass). If an end condition holds at the buy step, the player gets the buy step even if +they cannot buy anything. + +## 5. Placing a Tile + +### 5.1 Effects of a placement + +When a tile is placed, look at the chains and loose tiles adjacent to it: + +- **No adjacent tiles:** It becomes a loose tile. +- **Adjacent only to loose tiles:** It **founds a new chain** (§6), if legal. +- **Adjacent to exactly one chain:** It joins that chain. **All loose tiles connected + to the placed tile also join the chain.** +- **Adjacent to two or more different chains:** It causes a **merger** (§7). + +### 5.2 Legality + +A tile in hand is **playable** unless one of these applies: + +- **Permanently unplayable:** Placing it would merge two or more **safe** chains. This + is true even if it would also touch an open chain. +- **Temporarily unplayable:** Placing it would found a new chain (§5.1, adjacent only to + loose tiles) while all 7 chains are already active. A tile that touches an existing + chain is *not* blocked by this rule, even if it also touches loose tiles. + +Legality must be recomputed every time it is needed. A tile's status changes as the board +changes (e.g. a temporarily unplayable tile becomes playable when a merger frees a name). + +### 5.3 Dead and stuck hands + +- If **none** of a player's tiles are playable, they skip the placement phase but may + still buy stock. +- At the end of their turn, a player discards all **permanently** unplayable tiles from + their hand (removed from the game) and draws replacements. Temporarily unplayable tiles + are never replaced. **[DECISION]** This is automatic, not a player choice. +- If the draw pool is empty, no replacement or regular draw happens; hands simply shrink. + +## 6. Founding a Chain + +1. The active player (the **founder**) chooses the name of any chain not currently on + the board. +2. The new chain consists of the placed tile plus **all loose tiles connected to it**. +3. The founder receives **1 free share** of that chain from the bank (the **founder's + bonus**). If the bank has no shares left in that chain, no bonus is given. +4. A previously defunct chain can be founded again. Players still holding its stock + from an earlier merger now hold stock in the new chain. + +## 7. Mergers + +### 7.1 Determining the survivor + +1. Sizes are measured **before** the merging tile is placed. +2. The largest chain survives and takes over all others simultaneously. +3. If two or more chains tie for largest, the active player (the **mergermaker**) + chooses the survivor from among them. +4. A safe chain can take over open chains. Two safe chains can never merge (§5.2). + +### 7.2 Resolving each defunct chain + +Defunct chains are resolved one at a time, **largest first** (by pre-merger size). If +defunct chains tie in size, the mergermaker chooses the order. **[DECISION]** The full +order is chosen once, up front, right after the survivor is known and before any bonuses +are paid; it cannot be changed partway through the merger. + +For each defunct chain, in that order: + +1. **Pay majority bonuses** (§10), using the defunct chain's pre-merger size for prices. +2. **Stock disposal:** Starting with the mergermaker and going clockwise through **all** + players, each player holding stock in the defunct chain decides what to do with it. + They may split their holding among these options in any amounts: + - **Sell** shares to the bank at the defunct chain's pre-merger share price. + - **Trade** shares 2-for-1 for shares of the **survivor**. The number of trades is + limited by the survivor shares left in the bank. + - **Hold** the rest. Held shares keep no value unless the chain is founded again. + - Players holding no stock in the defunct chain are skipped automatically. + +### 7.3 Board update + +After all defunct chains are resolved, the survivor absorbs every tile from every +defunct chain, the merging tile, and all loose tiles connected to the merging tile. +Defunct chain names return to the pool of available names. + +**[DECISION]** The disposal decisions of one defunct chain are fully completed (all +players) before the next defunct chain's bonuses are paid. + +## 8. Price Table + +Taken from the official Information Card. Chains fall into three tiers: + +| Tier | Chains | +|---|---| +| Minor | Tower, Luxor | +| Medium | Worldwide, American, Festival | +| Major | Imperial, Continental | + +Find the chain's size in its tier's column; that row gives the share price and bonuses. + +| Minor size | Medium size | Major size | Share price | 1st (majority) bonus | 2nd (minority) bonus | +|---|---|---|---|---|---| +| 2 | — | — | $200 | $2,000 | $1,000 | +| 3 | 2 | — | $300 | $3,000 | $1,500 | +| 4 | 3 | 2 | $400 | $4,000 | $2,000 | +| 5 | 4 | 3 | $500 | $5,000 | $2,500 | +| 6–10 | 5 | 4 | $600 | $6,000 | $3,000 | +| 11–20 | 6–10 | 5 | $700 | $7,000 | $3,500 | +| 21–30 | 11–20 | 6–10 | $800 | $8,000 | $4,000 | +| 31–40 | 21–30 | 11–20 | $900 | $9,000 | $4,500 | +| 41+ | 31–40 | 21–30 | $1,000 | $10,000 | $5,000 | +| — | 41+ | 31–40 | $1,100 | $11,000 | $5,500 | +| — | — | 41+ | $1,200 | $12,000 | $6,000 | + +Equivalently: the medium tier's price is the minor price for the same size plus $100, and +the major tier's is plus $200. The 1st bonus is always 10 × the share price and the 2nd +bonus is 5 × the share price. The engine may compute prices from this formula, but tests +must check every row of the table above. + +**[DECISION]** Chain names and tier assignments live in a single config table so they +can be renamed later without touching game logic. + +## 9. Buying Stock + +1. After placing (or skipping placement), the active player may buy **0 to 3 shares** + in total, across one, two, or three active chains. +2. Shares can only be bought in chains that are on the board and have shares left in the + bank. +3. The price of each share is based on the chain's size **after** this turn's placement + and any merger. Prices do not change partway through the buy phase. +4. A player cannot buy shares they cannot afford. There is no borrowing. +5. Players can never sell stock except during merger disposal (§7.2) and final scoring + (§11.2). There is no trading between players. +6. **[DECISION]** The buy step is skipped automatically only for public reasons: no chain + is on the board, or the bank has no shares left in any active chain. When + `publicHoldings` is off (§13), it is never skipped because the player cannot afford a + share, since that would reveal their cash; they get the step and may buy nothing. When + `publicHoldings` is on, it is also skipped when the player cannot afford any share. + +## 10. Majority Bonuses + +Bonuses are paid by the bank, based on how many shares each player holds in the chain +being scored. + +- **Single holder:** They receive both the majority and minority bonus. +- **Clear first and clear second:** First gets the majority bonus, second gets the + minority bonus. +- **Tie for first:** Add majority + minority bonuses together and split equally among + the tied players. No minority bonus is paid to anyone else. +- **Clear first, tie for second:** First gets the majority bonus. The minority bonus is + split equally among the players tied for second. +- **Rounding:** Any split share that is not a multiple of $100 is rounded **up** to the + next $100. **[DECISION]** The original rules only specify rounding for a first-place + tie; this applies the same rule to second-place ties. +- Players with zero shares never receive a bonus. + +## 11. Ending the Game + +### 11.1 Announcement + +The game may be ended when either condition is true: + +- **Any** active chain has size **41 or more**, or +- There is at least one active chain and **every** active chain is safe. + +During their own turn, once a condition holds, the active player may announce the end +of the game. Announcing is **optional**; a player may keep playing if it benefits them. +After announcing, they finish the rest of their turn normally. + +**[DECISION]** The announcement can be made before placing a tile or during the buy step, +and the end condition is checked at the moment of announcing. A condition that held at +the start of the turn but no longer holds (e.g. a newly founded chain is not safe) does +not allow an announcement. With the `autoEnd` option (§15), the condition is checked at +the end of the turn instead. + +**[DECISION] Stall rule:** If a full round passes in which no tile was placed, the game +ends automatically at the end of the turn that completes that round, even if no end +condition has been met. A full round means as many consecutive turns as there are seats, +counted from any turn (not only from the first player). This covers both an empty draw +pool and hands that hold only unplayable tiles. + +### 11.2 Final scoring + +1. Pay majority bonuses (§10) for every active chain. +2. Every player sells all stock in active chains to the bank at current prices. +3. Stock in chains that are not on the board is worthless. +4. The player with the most money wins. **[DECISION]** Ties are shared victories. + +## 12. Two-Player Rules + +With exactly 2 players, the bank acts as a third shareholder whenever bonuses are paid. + +### 12.1 At each merger + +1. Before paying bonuses for a defunct chain, draw one tile from the pool. The bank is + treated as holding a number of shares equal to that tile's **column number** + (e.g. `9F` means 9 shares). +2. Pay bonuses (§10) as if the bank were a player. Any bonus the bank "wins" is simply + not paid out. **[DECISION]** If the bank ties with a player, the split is computed + normally and the bank's portion is not paid out. +3. The bank never disposes of stock; its holding is fictional. +4. After all defunct chains are resolved, and **before** the active player's buy phase, + place the bank's tile(s) on the board: + - If it would cause another merger, resolve that merger fully (with a fresh bank + draw), then place that tile too. Repeat until no further merger occurs. + - If it is permanently unplayable, remove it from the game. + - If it would found a chain, place it as a loose tile. No chain is founded until a + player later adds an adjacent tile (and that player gets the founder's bonus). + - **[DECISION]** For a merger caused by a bank tile, the active player is the + mergermaker: they break survivor and defunct-order ties, and stock disposal starts + with them. + - **[DECISION]** Waiting bank tiles are placed in the order they were drawn. Tiles + drawn during a merger caused by a bank tile join the back of that queue. +5. **[DECISION]** One bank tile is drawn per defunct chain (so a three-way merger draws + twice). If the pool is empty, the bank holds 0 shares. + +### 12.2 At final scoring + +Draw a tile for each active chain to set the bank's holding as above, pay bonuses, and +set the tiles aside without placing them. Tiles set aside count as removed from the game. + +## 13. Hidden Information + +Each viewer must only receive information their player is entitled to. + +- **Always private:** each player's hand of tiles, and the order of the draw pool. +- **Always public:** the board, chain names and sizes, current prices, and the number of + shares left in the bank for each chain. +- **[DECISION] Game option `publicHoldings` (default: `false`):** When off, each player's + current share holdings and cash are visible only to that player. When on, they are + public. +- **[DECISION] The game log is always public.** It records every action: tile + placements, stock purchases, bonuses paid, and each player's disposal choices. Only + the *current* holdings and cash are hidden, even though they can be reconstructed + from the log. +- **[DECISION] Scores during play:** When `publicHoldings` is off, every player's score + is 0 until the game ends. When it is on, the score is the player's live cash. + +Hidden information must be stripped on the engine side, not merely hidden in the viewer. + +## 14. Required Invariants (for tests) + +These must hold after every move in every game: + +1. For each chain, bank shares + all players' shares = 25. +2. Every player's cash is a non-negative multiple of $100. +3. Each of the 108 tiles is in exactly one place: the pool, one hand, the board, + removed from the game, or (two-player bank mode only) **[DECISION]** waiting to be + placed as a bank tile (§12.1.4). Waiting bank tiles are public. +4. Every active chain has size ≥ 2 and is one connected group; no two active chains are + adjacent to each other. +5. At most 7 chains are active, and no name is used twice. +6. The full game state is JSON-serializable. +7. Replaying the same moves from the same seed produces an identical state. +8. Random legal play always reaches a finished game (2–6 players). + +## 15. Game Options + +Options are chosen when a game is created and apply to every player. Implement them as +switches on one engine, not as separate code paths. Defaults reproduce the standard game. + +| Option | Values | Default | Effect | +|---|---|---|---| +| `publicHoldings` | true / false | false | See §13. When false, share holdings and cash are private. | +| `teamPlay` | true / false | false | Only applies with exactly 4 players. Seats 1 and 3 form one team, seats 2 and 4 the other. All rules are unchanged; at final scoring each team's cash is added together and the team with more wins. **[DECISION]** With `publicHoldings` off, teammates still cannot see each other's holdings. | +| `twoPlayerMode` | `bank` / `fourHands` | `bank` | Only has an effect with exactly 2 players. `bank` uses §12. `fourHands` runs a normal 4-seat game where each player controls two seats (player A has seats 1 and 3, player B has seats 2 and 4), with no bank shareholder. **[DECISION]** The player who controls the single richest seat wins; seats are not combined. | +| `autoEnd` | true / false | false | When true, the game ends automatically at the end of the turn in which an end condition (§11.1) first holds, instead of waiting for an announcement. | +| `endSize` | 41 / 31 | 41 | The chain size that triggers the end condition in §11.1. Setting 31 gives a shorter game (house rule). Does not change the safe size (11) or the price table. | + +**[DECISION]** Invalid combinations are never rejected. An option that does not apply to +the player count (e.g. `teamPlay` with 5 players, or `twoPlayerMode: fourHands` with 3 +players) is ignored, and the game log records that it was ignored. The default +`twoPlayerMode: bank` is not logged as ignored, since it is always sent. + +## 16. Dropped Players + +**[DECISION]** When a player drops out (quits or runs out of time), the game continues +and the engine plays for them automatically. The dropped player's seat keeps its tiles, +stock and cash and is scored normally. For every decision it uses these defaults: + +| Decision | Default | +|---|---| +| Place tile | The first playable tile in hand, with the hand in board order (§3.3: by number, then letter). If none is playable, skip placement. | +| Name a new chain | The first available chain in config order (§8). | +| Choose merger survivor (tie) | The first tied chain in config order. | +| Choose defunct order (tie) | Tied chains in config order. | +| Stock disposal | Hold all defunct stock. | +| Buy stock | Buy nothing. | +| Announce the end | Never. | + +**[DECISION]** Auto-play applies only while two or more players remain who have not +dropped. As soon as a drop leaves one or none, the game ends at once, even in the middle +of a turn or a merger, and is scored as usual (§11.2). An unfinished merger is abandoned: +bonuses already paid stand, chains not yet taken over are scored as active chains, and +bank tiles still waiting to be placed (§12.1.4) are removed from the game. With two +players, including `fourHands`, any drop therefore ends the game; in `fourHands` the +dropping player loses both seats at once. + +**[DECISION]** Dropped players always rank below every player who did not drop, whatever +their cash. Players who dropped share the rank just below the last remaining player. +Their cash is still shown as their score. diff --git a/tsconfig.base.json b/tsconfig.base.json new file mode 100644 index 0000000..015d680 --- /dev/null +++ b/tsconfig.base.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2022"], + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + } +}