Acquire for boardgamers.space

Rules engine and viewer implementing the BGS Engine and Viewer APIs,
with tests, a local test page, registration guide and admin-panel
content.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mike Isom 2026-10-22 09:53:39 -06:00
parent a48b6f2dba
commit 096f8cc54b
119 changed files with 13271 additions and 0 deletions

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
* text=auto eol=lf

7
.githooks/pre-commit Normal file
View file

@ -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

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
node_modules
dist
dist-test
.vite
.pnpm-store
*.local
*.tgz
release/

1
.nvmrc Normal file
View file

@ -0,0 +1 @@
24.2.0

10
.oxfmtrc.json Normal file
View file

@ -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"]
}

7
.oxlintrc.json Normal file
View file

@ -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/**"]
}

55
README.md Normal file
View file

@ -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).

42
docs/admin/README.md Normal file
View file

@ -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).

3
docs/admin/credits.md Normal file
View file

@ -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.

View file

@ -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.

14
docs/admin/pictogram.svg Normal file
View file

@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="512" height="512">
<title>Acquire</title>
<!-- A corner of the board: a Tower group (orange) and a Continental group (cyan) with the
loose tile between them that will merge them. Our own chain colours, no edition artwork. -->
<rect x="0" y="0" width="30" height="30" fill="#a6a6a6" />
<rect x="35" y="0" width="30" height="30" fill="#a6a6a6" />
<rect x="70" y="0" width="30" height="30" fill="#21c5e2" />
<rect x="0" y="35" width="30" height="30" fill="#b44906" />
<rect x="36.5" y="36.5" width="27" height="27" fill="#1e1e1e" stroke="#a6a6a6" stroke-width="3" />
<rect x="70" y="35" width="30" height="30" fill="#21c5e2" />
<rect x="0" y="70" width="30" height="30" fill="#b44906" />
<rect x="35" y="70" width="30" height="30" fill="#a6a6a6" />
<rect x="70" y="70" width="30" height="30" fill="#21c5e2" />
</svg>

After

Width:  |  Height:  |  Size: 900 B

111
docs/admin/rules.md Normal file
View file

@ -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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 184 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

154
docs/registering.md Normal file
View file

@ -0,0 +1,154 @@
# Registering Acquire on boardgamers.space
How to publish the engine and viewer to BGS, following the BGS guide
(<https://docs.boardgamers.space/guide/adding-a-game.md>). 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-<version>.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-<version>.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.

28
package.json Normal file
View file

@ -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"
}

18
packages/engine/index.ts Normal file
View file

@ -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";

View file

@ -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"
}
}

View file

@ -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<LogEntry, { type: "move" }> => 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<string, unknown>[] = [
{},
{ 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);
}
}
}
});

View file

@ -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}`);
}
}

View file

@ -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<string, number> = {}) => ({ type: "buy", shares });
function entries<T extends LogEntry["type"]>(state: GameState, type: T): Extract<LogEntry, { type: T }>[] {
return state.log.filter((e): e is Extract<LogEntry, { type: T }> => 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);
});

View file

@ -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<BankHolding, "amount"> | 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);
}

View file

@ -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<string, Exclude<Cell, null>>): 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");
});

View file

@ -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>([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));
}

View file

@ -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]);
});

View file

@ -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;
}

View file

@ -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);
}

View file

@ -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<string, number> = {}) => ({ type: "buy", shares });
const announce = { type: "announce" };
function entries<T extends LogEntry["type"]>(state: GameState, type: T): Extract<LogEntry, { type: T }>[] {
return state.log.filter((e): e is Extract<LogEntry, { type: T }> => 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/);
});

View file

@ -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);
});

View file

@ -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<string, unknown>[] = [
{},
{ 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<string, unknown>,
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<string, unknown>;
const expected = withoutSecrets(state, player) as Record<string, unknown>;
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));
});

View file

@ -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<Shares>[] {
const result: Partial<Shares>[] = [];
const visit = (from: number, remaining: number, current: Partial<Shares>) => {
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<T>(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;
}
});
}

View file

@ -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<T extends LogEntry["type"]>(state: GameState, type: T): Extract<LogEntry, { type: T }>[] {
return state.log.filter((e): e is Extract<LogEntry, { type: T }> => 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);
});

View file

@ -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);
}

View file

@ -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<string, unknown> {
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<Shares> = {};
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<Shares>): 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 });
}

View file

@ -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<LogEntry, { type: "optionIgnored" }>[] {
return state.log.filter((e): e is Extract<LogEntry, { type: "optionIgnored" }> => 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]);
});

View file

@ -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<string, unknown>
): { 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);
}

View file

@ -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<string, unknown>][] = [
[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`
);
}
}
});

View file

@ -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 };
}

View file

@ -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));
});

View file

@ -0,0 +1,32 @@
import { chainTier, type ChainId, type Tier } from "./config.js";
const TIER_OFFSET: Record<Tier, number> = { 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;
}

View file

@ -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<T>(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;
}

View file

@ -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);
});

View file

@ -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}`);
}
}
}

View file

@ -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);
}

View file

@ -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"));
});

View file

@ -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<string, unknown>, 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;
}

View file

@ -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<string, unknown>[] {
const combos: Record<string, unknown>[] = [];
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<string, unknown>, 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]
);
});

View file

@ -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<string, unknown> = {}): 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");
});

View file

@ -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<Record<ChainId, number>>): 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<LogEntry, { type: "turn" }>).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 "";
}

View file

@ -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<string, Exclude<Cell, null>>;
/** 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<Shares>[];
activeSeat?: number;
options?: Record<string, unknown>;
}
/**
* 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<Tile>([
...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<string, ChainId> {
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<Tile>([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");
}

View file

@ -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"]);
});

View file

@ -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);
}

View file

@ -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<string, number> = {}) => ({ 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");
});

107
packages/engine/src/turn.ts Normal file
View file

@ -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;
}

View file

@ -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<ChainId, number>;
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<Shares> };
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<Record<ChainId, number>>;
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<string, unknown> }
| { 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<Record<ChainId, number>>; 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<Shares>; 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;
}

View file

@ -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 } }),
};
}),
};
}

View file

@ -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<GameState, unknown> = 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");
});

View file

@ -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/**"]
}

View file

@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts", "wrapper.ts", "index.ts"]
}

View file

@ -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"]
}

View file

@ -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<string, unknown>,
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);
}

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 2l3 7h7l-5.5 4.5 2 7.5-6.5-4.5-6.5 4.5 2-7.5L2 9h7z" fill="#d4a017"/></svg>

After

Width:  |  Height:  |  Size: 149 B

View file

@ -0,0 +1,16 @@
<!doctype html>
<html lang="en" style="color-scheme: light dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Acquire viewer - dev harness</title>
</head>
<body style="margin: 0; background: Canvas">
<div
id="dev"
style="display: flex; gap: 8px; align-items: center; padding: 8px; background: #ddd; font: 13px system-ui"
></div>
<div id="app"></div>
<script type="module" src="/src/dev.ts"></script>
</body>
</html>

View file

@ -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"
}
}

View file

@ -0,0 +1,92 @@
<script lang="ts">
import ActionPanel from "./lib/ActionPanel.svelte";
import Board from "./lib/Board.svelte";
import ChainTable from "./lib/ChainTable.svelte";
import Chat from "./lib/Chat.svelte";
import Hand from "./lib/Hand.svelte";
import Log from "./lib/Log.svelte";
import Players from "./lib/Players.svelte";
import PriceTable from "./lib/PriceTable.svelte";
import Status from "./lib/Status.svelte";
import type { ViewerStore } from "./lib/store.svelte";
import { tileLabel } from "acquire-engine";
let { store }: { store: ViewerStore } = $props();
</script>
<main class="acquire" data-theme={store.theme} lang={store.locale} dir={store.rightToLeft ? "rtl" : "ltr"}>
{#if store.state}
{@const state = store.view!}
<div class="layout">
<div class="controls">
<Status {state} seats={store.seats} />
<ActionPanel {store} />
</div>
<div class="board">
<Board
{state}
selected={store.selected}
onconfirm={() =>
store.selected !== undefined && store.send({ type: "place", tile: tileLabel(store.selected) })}
/>
</div>
{#if store.seats.length > 0 && store.replayAt === undefined}
<div class="hand"><Hand {store} /></div>
{/if}
<div class="info">
<ChainTable {state} seats={store.seats} />
<PriceTable {state} />
<Players {state} seats={store.seats} />
{#if !store.analysis}
<Chat />
{/if}
<Log {state} />
</div>
</div>
{:else}
<p>{store.lang.t("loading")}</p>
{/if}
</main>
<style>
/* Narrow screens: one column, decision and board together so a selected square and its confirm
button are both visible. No viewport-height units: BGS sizes the iframe to its content. */
.layout {
display: grid;
gap: 12px 20px;
grid-template-columns: minmax(0, 1fr);
grid-template-areas: "controls" "board" "hand" "info";
align-items: start;
}
.controls {
grid-area: controls;
}
.board {
grid-area: board;
max-width: 660px;
}
.hand {
grid-area: hand;
}
.info {
grid-area: info;
display: grid;
gap: 16px;
}
/* Tablets and phones in landscape: the board beside the decision and hand. */
@media (min-width: 700px) {
.layout {
grid-template-columns: minmax(0, 1.4fr) minmax(260px, 1fr);
grid-template-areas: "board controls" "board hand" "info info";
grid-template-rows: auto 1fr auto;
}
}
/* Desktop: board, decision and hand, then the chain, player and log columns. */
@media (min-width: 1200px) {
.layout {
grid-template-columns: minmax(0, 620px) minmax(280px, 380px) minmax(320px, 1fr);
grid-template-areas: "board controls info" "board hand info";
grid-template-rows: auto 1fr;
}
}
</style>

252
packages/viewer/src/dev.ts Normal file
View file

@ -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<string, unknown> = {};
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(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">${body}</svg>`)}`;
const avatars = NAMES.slice(0, players).map(() =>
svg(
`<rect width="24" height="24" fill="#cfcfcf"/><circle cx="12" cy="9" r="5" fill="#888"/><path d="M3 24c1-6 5-8 9-8s8 2 9 8z" fill="#888"/>`
)
);
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();

View file

@ -0,0 +1,376 @@
<script lang="ts">
import {
CHAIN_IDS,
activeChains,
chainSize,
currentSeat,
merger,
sharePrice,
tileLabel,
type ChainId,
type Shares,
} from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import { adjustShares, canBuy, canDispose, describePlacement, nextDefunctChoices, ofType } from "./decisions";
import { chainName } from "./format";
import type { ViewerStore } from "./store.svelte";
let { store }: { store: ViewerStore } = $props();
const game = $derived(store.state!);
const moves = $derived(store.moves);
const seat = $derived(currentSeat(game));
const legal = (type: string) => moves.some((move) => move.type === type);
const lang = $derived(store.lang);
const t = $derived(lang.t);
const money = $derived(lang.money);
// Choices being built up before they are sent; reset whenever a new state arrives.
let confirmAnnounce = $state(false);
let order = $state<ChainId[]>([]);
let sell = $state(0);
let trade = $state(0);
let shares = $state<Partial<Shares>>({});
$effect(() => {
void store.state;
confirmAnnounce = false;
order = [];
sell = 0;
trade = 0;
shares = {};
});
const foundable = $derived(new Set(ofType(moves, "found").map((move) => move.chain)));
const survivors = $derived(new Set(ofType(moves, "survivor").map((move) => move.chain)));
const nextInOrder = $derived(new Set(nextDefunctChoices(moves, order)));
const orderComplete = $derived(ofType(moves, "defunctOrder").some((move) => move.chains.join() === order.join()));
const m = $derived(game.merger);
const disposing = $derived(game.phase === "dispose" && m ? m.current! : undefined);
const held = $derived(disposing && seat !== undefined ? game.seats[seat]!.shares[disposing] : 0);
const sellPrice = $derived(disposing ? sharePrice(disposing, m!.sizes[disposing]!) : 0);
const buyable = $derived(activeChains(game.board));
const price = (chain: ChainId) => sharePrice(chain, chainSize(game.board, chain));
const cost = $derived(Object.entries(shares).reduce((sum, [chain, n]) => sum + n * price(chain as ChainId), 0));
const total = $derived(Object.values(shares).reduce((sum, n) => sum + n, 0));
function placeSelected(): void {
if (store.selected !== undefined) {
store.send({ type: "place", tile: tileLabel(store.selected) });
}
}
</script>
{#if moves.length > 0 && !store.sending}
<section class="panel" aria-label={t("panel.label")}>
{#if legal("announce")}
<div class="announce">
{#if confirmAnnounce}
<p>{t("announce.ask")}</p>
<button type="button" class="actionable" onclick={() => store.send({ type: "announce" })}
>{t("announce.confirm")}</button
>
<button type="button" class="actionable" onclick={() => (confirmAnnounce = false)}
>{t("announce.cancel")}</button
>
{:else}
<button type="button" class="actionable" onclick={() => (confirmAnnounce = true)}>{t("announce.open")}</button
>
{/if}
</div>
{/if}
{#if game.phase === "place"}
{#if store.selected !== undefined}
<p>
{t("place.effect", {
tile: tileLabel(store.selected),
effect: describePlacement(game, store.selected, lang),
})}
</p>
<button type="button" class="actionable primary" onclick={placeSelected}
>{t("place.button", { tile: tileLabel(store.selected) })}</button
>
<button type="button" class="actionable" onclick={() => (store.selected = undefined)}
>{t("place.another")}</button
>
{:else if legal("place")}
<p>{t("place.choose")}</p>
{/if}
{#if legal("pass")}
<p>{t("place.none")}</p>
<button type="button" class="actionable" onclick={() => store.send({ type: "pass" })}>{t("place.pass")}</button>
{/if}
{:else if game.phase === "found"}
<p>{t("found.prompt")}</p>
<div class="choices">
{#each CHAIN_IDS as chain (chain)}
<button
type="button"
class="choice"
class:actionable={foundable.has(chain)}
disabled={!foundable.has(chain)}
onclick={() => store.send({ type: "found", chain })}><ChainMark {chain} withName /></button
>
{/each}
</div>
{:else if game.phase === "survivor" && m}
<p>{t("survivor.prompt")}</p>
<div class="choices">
{#each CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined) as chain (chain)}
<button
type="button"
class="choice"
class:actionable={survivors.has(chain)}
disabled={!survivors.has(chain)}
onclick={() => store.send({ type: "survivor", chain })}
><ChainMark {chain} withName /> <span class="size">{t("tiles", { count: m.sizes[chain]! })}</span></button
>
{/each}
</div>
{:else if game.phase === "defunctOrder" && m}
<p>{t("order.prompt", { survivor: chainName(m.survivor!) })}</p>
<div class="choices">
{#each CHAIN_IDS.filter((chain) => m.sizes[chain] !== undefined && chain !== m.survivor) as chain (chain)}
{@const position = order.indexOf(chain)}
<button
type="button"
class="choice"
class:actionable={nextInOrder.has(chain)}
disabled={!nextInOrder.has(chain)}
onclick={() => (order = [...order, chain])}
>
<ChainMark {chain} withName />
<span class="size">{t("tiles", { count: m.sizes[chain]! })}</span>
{#if position >= 0}<span class="position">#{position + 1}</span>{/if}
</button>
{/each}
</div>
<button
type="button"
class:actionable={orderComplete}
disabled={!orderComplete}
class="primary"
onclick={() => store.send({ type: "defunctOrder", chains: order })}>{t("order.confirm")}</button
>
<button
type="button"
class:actionable={order.length > 0}
disabled={order.length === 0}
onclick={() => (order = [])}>{t("order.reset")}</button
>
{:else if game.phase === "dispose" && disposing && m}
<p class="takeover">
<ChainMark chain={disposing} /><span class="arrow" aria-hidden="true">→</span><ChainMark chain={m.survivor!} />
</p>
<p>
{t("dispose.takenOver", { defunct: chainName(disposing), survivor: chainName(m.survivor!) })}
{t("dispose.holding", { count: held, chain: chainName(disposing) })}
</p>
<div class="steppers">
<span class="label">{t("dispose.sell", { price: money(sellPrice) })}</span>
<button
type="button"
class:actionable={canDispose(moves, sell - 1, trade)}
disabled={!canDispose(moves, sell - 1, trade)}
onclick={() => sell--}
aria-label={t("dispose.sellFewer")}>−</button
>
<span class="value">{sell}</span>
<button
type="button"
class:actionable={canDispose(moves, sell + 1, trade)}
disabled={!canDispose(moves, sell + 1, trade)}
onclick={() => sell++}
aria-label={t("dispose.sellMore")}>+</button
>
<span class="effect">+{money(sell * sellPrice)}</span>
<span class="label">{t("dispose.trade")}</span>
<button
type="button"
class:actionable={canDispose(moves, sell, trade - 2)}
disabled={!canDispose(moves, sell, trade - 2)}
onclick={() => (trade -= 2)}
aria-label={t("dispose.tradeFewer")}>−</button
>
<span class="value">{trade}</span>
<button
type="button"
class:actionable={canDispose(moves, sell, trade + 2)}
disabled={!canDispose(moves, sell, trade + 2)}
onclick={() => (trade += 2)}
aria-label={t("dispose.tradeMore")}>+</button
>
<span class="effect">{t("dispose.receive", { count: trade / 2, chain: chainName(m.survivor!) })}</span>
<span class="label">{t("dispose.keep")}</span>
<span></span>
<span class="value">{held - sell - trade}</span>
<span></span>
<span class="effect">{t("dispose.keepNote", { chain: chainName(disposing) })}</span>
</div>
<button type="button" class="actionable primary" onclick={() => store.send({ type: "dispose", sell, trade })}
>{t("dispose.confirm")}</button
>
{:else if game.phase === "buy"}
<p>{t("buy.prompt")}</p>
{#if buyable.length > 0}
<table class="buy">
<thead>
<tr>
<th>{t("buy.chain")}</th><th class="num">{t("buy.price")}</th><th class="num">{t("buy.bank")}</th><th
class="num">{t("buy.buy")}</th
>
</tr>
</thead>
<tbody>
{#each buyable as chain (chain)}
{@const fewer = adjustShares(shares, chain, -1)}
{@const more = adjustShares(shares, chain, 1)}
<tr>
<td><ChainMark {chain} withName /></td>
<td class="num">{money(price(chain))}</td>
<td class="num">{game.bank[chain]}</td>
<td class="num stepper">
<button
type="button"
class:actionable={canBuy(moves, fewer)}
disabled={!canBuy(moves, fewer)}
onclick={() => (shares = fewer)}
aria-label={t("buy.fewer", { chain: chainName(chain) })}>−</button
>
<span class="value">{shares[chain] ?? 0}</span>
<button
type="button"
class:actionable={canBuy(moves, more)}
disabled={!canBuy(moves, more)}
onclick={() => (shares = more)}
aria-label={t("buy.more", { chain: chainName(chain) })}>+</button
>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
<p class="total">
{t("buy.total", { count: total, cost: money(cost), cash: money(game.seats[seat!]!.cash - cost) })}
</p>
<button type="button" class="actionable primary" onclick={() => store.send({ type: "buy", shares })}>
{total === 0 ? t("buy.nothing") : t("buy.confirm", { cost: money(cost) })}
</button>
{/if}
</section>
{:else if store.sending}
<section class="panel"><p>{t("panel.sending")}</p></section>
{/if}
<style>
.panel {
background: var(--panel);
padding: 10px 12px 12px;
margin: 0 0 12px;
}
.panel p {
margin: 0 0 8px;
}
.panel button {
margin: 4px 8px 4px 0;
padding: 6px 12px;
min-height: 36px;
background: var(--page);
color: var(--ink);
font: inherit;
border: none;
}
.panel button:disabled {
background: transparent;
color: var(--ink-muted);
}
.panel button.primary.actionable {
background: var(--accent);
color: var(--on-accent);
font-weight: 600;
}
.takeover {
display: flex;
align-items: center;
gap: 6px;
}
/* The arrow runs from the defunct chain to the survivor in either reading direction. */
:global([dir="rtl"]) .arrow {
transform: scaleX(-1);
}
.announce {
margin: 0 0 10px;
}
.choices {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin: 0 0 6px;
}
.choice {
display: inline-flex;
align-items: center;
gap: 6px;
}
.size {
font-size: 13px;
color: var(--ink-muted);
}
.position {
font-weight: 700;
}
.steppers {
display: grid;
grid-template-columns: auto auto 32px auto 1fr;
align-items: center;
gap: 4px 6px;
margin: 0 0 8px;
}
.steppers button,
.stepper button {
width: 36px;
padding: 0;
margin: 0;
font-size: 18px;
}
.value {
text-align: center;
font-variant-numeric: tabular-nums;
font-weight: 600;
}
.effect {
font-size: 13px;
color: var(--ink-muted);
/* "+$600" and "+2 Tower" keep their order inside right-to-left text. */
direction: ltr;
unicode-bidi: isolate;
}
.buy {
margin: 0 0 6px;
}
.stepper {
white-space: nowrap;
}
.stepper .value {
display: inline-block;
width: 24px;
}
.total {
font-variant-numeric: tabular-nums;
}
/* Touch screens get 44px targets. */
@media (pointer: coarse) {
.panel button {
min-height: 44px;
}
.steppers button,
.stepper button {
width: 44px;
}
}
</style>

View file

@ -0,0 +1,205 @@
<script lang="ts">
import { BOARD_COLUMNS, BOARD_ROWS, tileLabel, type GameState, type Tile } from "acquire-engine";
import { chainName } from "./format";
import { CHAIN_STYLES, patternCss } from "./palette";
import { useStore } from "./store.svelte";
let {
state,
selected,
onconfirm,
}: {
state: GameState;
/** A tile selected in the hand: its square is highlighted and clicking it places the tile. */
selected?: Tile;
onconfirm?: () => void;
} = $props();
// Rows A-I down, columns 1-12 across, like the printed board. Tile index = (column - 1) * 9 + row.
const ROW_LETTERS = "ABCDEFGHI";
const rows = Array.from({ length: BOARD_ROWS }, (_, row) => row);
const columns = Array.from({ length: BOARD_COLUMNS }, (_, column) => column);
const tileAt = (row: number, column: number) => column * BOARD_ROWS + row;
const pendingTile = $derived(state.merger?.tile ?? state.pendingTile);
const store = useStore();
const t = $derived(store.lang.t);
</script>
<div class="frame" dir="ltr">
<div></div>
<div class="numbers" aria-hidden="true">
{#each columns as column (column)}<span>{column + 1}</span>{/each}
</div>
<div class="letters" aria-hidden="true">
{#each rows as row (row)}<span>{ROW_LETTERS[row]}</span>{/each}
</div>
<div class="board" aria-label={t("board.label")}>
{#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}
<button
type="button"
class="square empty selected actionable"
aria-label={t("board.place", { tile: label })}
onclick={() => onconfirm?.()}
>
<span class="coord">{label}</span>
</button>
{:else if cell === null}
<div class="square empty" aria-label={t("board.empty", { tile: label })}>
<span class="coord">{label}</span>
</div>
{:else if cell === "loose"}
<div class="square loose" class:pending={tile === pendingTile} aria-label={t("board.loose", { tile: label })}>
<span class="coord">{label}</span>
</div>
{:else}
{@const style = CHAIN_STYLES[cell]}
<div
class="square chain"
style:background={style.fill}
style:color={style.text}
aria-label={t("board.chain", { tile: label, chain: chainName(cell) })}
>
{#if store.colorBlind}
<!-- Colour-blind mode: the chain's pattern, with the letter on a solid patch so its
contrast never changes. Edge labels give the coordinate. -->
<span class="pattern" style:background={patternCss(style.pattern, style.patternInk)}></span>
<span class="letter patch" style:background={style.fill}>{style.letter}</span>
{:else}
<span class="corner-label">{label}</span>
<span class="letter">{style.letter}</span>
{/if}
</div>
{/if}
{/each}
{/each}
</div>
</div>
<style>
.frame {
display: grid;
grid-template-columns: 16px minmax(0, 1fr);
grid-template-rows: 18px auto;
width: 100%;
max-width: 660px;
}
/* Edge labels use the same 2px padding and gaps as the board so they line up with squares. */
.numbers,
.letters {
display: grid;
gap: 2px;
font-size: 12px;
font-weight: 600;
color: var(--ink-muted);
}
.numbers {
grid-template-columns: repeat(12, minmax(0, 1fr));
padding: 0 2px;
align-items: end;
text-align: center;
}
.letters {
grid-template-rows: repeat(9, minmax(0, 1fr));
padding: 2px 0;
align-items: center;
}
/* The dark board shows through 2px gaps between squares; the gaps are not outlines. */
.board {
display: grid;
grid-template-columns: repeat(12, minmax(0, 1fr));
gap: 2px;
padding: 2px;
background: var(--gap);
}
.square {
position: relative;
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
min-width: 0;
overflow: hidden;
margin: 0;
padding: 0;
border: none;
font: inherit;
}
/* An empty square only shows its small, muted coordinate, like the printed board. */
.empty {
background: var(--empty);
}
.empty .coord {
font-size: 10px;
color: var(--on-empty);
}
/* The selected tile's square: page colour plus an accent outline, since the accent is only
2.92:1 against the grey. */
.empty.selected {
background: var(--page);
outline: 4px solid var(--accent);
outline-offset: -4px;
}
.empty.selected .coord {
font-size: 12px;
font-weight: 700;
color: var(--ink);
}
/* A loose tile is black with a light coordinate. */
.loose {
background: var(--loose);
}
.loose .coord {
font-size: 11px;
font-weight: 600;
color: var(--on-loose);
}
/* The merging tile, or a tile waiting for a chain name: an accent stripe on a thin page-coloured
line, so the accent never sits directly on the black tile. */
.loose.pending {
box-shadow:
inset 0 -6px 0 var(--accent),
inset 0 -8px 0 var(--page);
}
/* Some chain colours are close to the grey in brightness; the bold letter tells them apart. */
.chain .letter {
font-weight: 800;
font-size: clamp(14px, 2.6vw, 22px);
line-height: 1;
}
/* On narrow screens the edge labels give the coordinates; corner labels would crowd the letter. */
@media (max-width: 520px) {
.chain .corner-label {
display: none;
}
.empty .coord {
font-size: 9px;
}
.loose .coord {
font-size: 10px;
}
}
.chain .pattern {
position: absolute;
inset: 0;
}
.chain .patch {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 58%;
height: 58%;
}
.chain .corner-label {
position: absolute;
top: 1px;
left: 2px;
font-size: 8px;
line-height: 1;
}
</style>

View file

@ -0,0 +1,82 @@
<script lang="ts">
import type { ChainId } from "acquire-engine";
import { chainName } from "./format";
import { CHAIN_STYLES, patternCss } from "./palette";
let {
chain,
withName = false,
small = false,
patterned = false,
}: { chain: ChainId; withName?: boolean; small?: boolean; patterned?: boolean } = $props();
const style = $derived(CHAIN_STYLES[chain]);
</script>
<span class="mark" class:small>
{#if patterned}
<!-- Colour-blind mode: the chain's pattern around a solid patch carrying the letter. -->
<span class="swatch patterned" style:background={style.fill} aria-hidden="true">
<span class="pattern" style:background={patternCss(style.pattern, style.patternInk)}></span>
<span class="patch" style:background={style.fill} style:color={style.text}>{style.letter}</span>
</span>
{:else}
<span class="swatch" style:background={style.fill} style:color={style.text} aria-hidden="true">{style.letter}</span>
{/if}
{#if withName}<span class="name">{chainName(chain)}</span>{:else}<span class="sr-only">{chainName(chain)}</span>{/if}
</span>
<style>
.mark {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
font-weight: 800;
font-size: 14px;
}
.patterned {
position: relative;
width: 26px;
height: 26px;
}
.pattern {
position: absolute;
inset: 0;
}
.patch {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
line-height: 1;
}
.small .patterned {
width: 21px;
height: 21px;
}
.small .patch {
width: 13px;
height: 13px;
}
.small .swatch {
width: 17px;
height: 17px;
font-size: 11px;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
</style>

View file

@ -0,0 +1,63 @@
<script lang="ts">
import { CHAIN_IDS, SAFE_SIZE, chainSize, sharePrice, type GameState } from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import { useStore } from "./store.svelte";
let { state, seats }: { state: GameState; seats: number[] } = $props();
const store = useStore();
const t = $derived(store.lang.t);
const rows = $derived(
CHAIN_IDS.map((chain) => {
const size = chainSize(state.board, chain);
const held = seats.reduce((sum, seat) => sum + Math.max(0, state.seats[seat]!.shares[chain]), 0);
return { chain, size, price: size >= 2 ? sharePrice(chain, size) : undefined, bank: state.bank[chain], held };
})
);
</script>
<section aria-label={t("chains.label")}>
<h2>{t("chains.title")}</h2>
<table>
<thead>
<tr>
<th>{t("chains.chain")}</th>
<th class="num">{t("chains.size")}</th>
<th class="num">{t("chains.price")}</th>
<th class="num">{t("chains.bank")}</th>
{#if seats.length > 0}<th class="num">{t("chains.yours")}</th>{/if}
</tr>
</thead>
<tbody>
{#each rows as row (row.chain)}
<tr class:inactive={row.size === 0}>
<td><ChainMark chain={row.chain} withName patterned={store.colorBlind} /></td>
<td class="num">
{#if row.size === 0}
{t("chains.notOnBoard")}
{:else}
{row.size}{#if row.size >= SAFE_SIZE}<span class="safe">{t("chains.safe")}</span>{/if}
{/if}
</td>
<td class="num">{row.price === undefined ? "" : store.lang.money(row.price)}</td>
<td class="num">{store.lang.count(row.bank)}</td>
{#if seats.length > 0}<td class="num">{row.held}</td>{/if}
</tr>
{/each}
</tbody>
</table>
</section>
<style>
.inactive td {
color: var(--ink-muted);
}
.safe {
margin-left: 6px;
padding: 0 4px;
font-size: 11px;
font-weight: 600;
background: var(--accent);
color: var(--on-accent);
}
</style>

View file

@ -0,0 +1,54 @@
<script lang="ts">
import { mountChat } from "@boardgamers/protocol/chat/dom";
import { useStore } from "./store.svelte";
const store = useStore();
let host: HTMLDivElement;
// The protocol library's chat panel, themed and labelled here. Labels are fixed at mount, so
// it is remounted when the language changes.
$effect(() => {
const t = store.lang.t;
// No openPlayer: authors stay plain text rather than a column of outlined buttons.
const panel = mountChat(host, {
chat: store.chat,
labels: {
title: t("chat.title"),
message: t("chat.message"),
placeholder: t("chat.placeholder"),
send: t("chat.send"),
sending: t("chat.sending"),
empty: t("chat.empty"),
edited: t("chat.edited"),
},
});
return () => panel.destroy();
});
</script>
<section class="chat" aria-label={store.lang.t("chat.label")}>
<div bind:this={host}></div>
</section>
<style>
.chat {
--chat-background: var(--panel);
--chat-color: var(--ink);
/* No frame or dividers: they would look clickable. */
--chat-border: transparent;
--chat-input-background: var(--page);
--chat-button-background: var(--accent);
--chat-link-color: var(--accent);
--chat-accent: var(--accent);
--chat-height: 320px;
}
.chat :global(.bgs-game-chat summary),
.chat :global(.bgs-game-chat input),
.chat :global(.bgs-game-chat button:not(:disabled)) {
outline: 2.5px solid var(--ink);
outline-offset: -2.5px;
}
.chat :global(.chat-composer button:not(:disabled)) {
color: var(--on-accent);
}
</style>

View file

@ -0,0 +1,111 @@
<script lang="ts">
import { HIDDEN, parseTile, sortTiles, tileLabel, tileLegality, type Tile } from "acquire-engine";
import { ofType } from "./decisions";
import { seatName } from "./format";
import type { ViewerStore } from "./store.svelte";
let { store }: { store: ViewerStore } = $props();
const t = $derived(store.lang.t);
const state = $derived(store.state!);
// Tiles the engine would accept right now; only these are actionable.
const playable = $derived(new Set(ofType(store.moves, "place").map((move) => parseTile(move.tile)!)));
function why(tile: Tile): string {
const legality = tileLegality(state.board, tile);
if (legality === "permanentlyUnplayable") {
return t("hand.dead");
}
if (legality === "temporarilyUnplayable") {
return t("hand.eighth");
}
return "";
}
function choose(tile: Tile): void {
store.selected = store.selected === tile ? undefined : tile;
}
</script>
{#each store.seats as seat (seat)}
<!-- Masked tiles can only appear while a new seat's state is still arriving; never show them. -->
{@const hand = sortTiles(state.seats[seat]!.hand.filter((tile) => tile !== HIDDEN))}
<section class="hand" aria-label={t("hand.of", { name: seatName(state, seat, store.lang) })}>
<h2>{store.seats.length > 1 ? t("hand.seat", { seat: seat + 1 }) : t("hand.yours")}</h2>
<div class="tiles">
{#each hand as tile, index (index)}
{#if playable.has(tile)}
<button
type="button"
class="tile"
class:actionable={!store.sending}
class:selected={store.selected === tile}
aria-pressed={store.selected === tile}
disabled={store.sending}
onclick={() => choose(tile)}>{tileLabel(tile)}</button
>
{:else}
<span class="tile" title={why(tile)}>
{tileLabel(tile)}
{#if why(tile)}<small>{why(tile)}</small>{/if}
</span>
{/if}
{:else}
<span class="none">{t("hand.none")}</span>
{/each}
</div>
</section>
{/each}
<style>
.hand {
margin: 12px 0 0;
}
/* Six tiles fit on one row; the 12px gaps leave room for outlines drawn outside the tiles. */
.tiles {
display: grid;
grid-template-columns: repeat(6, minmax(0, 52px));
gap: 12px;
padding: 8px;
background: var(--rack);
width: max-content;
max-width: 100%;
}
.tile {
position: relative;
display: inline-flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
aspect-ratio: 1;
min-height: 44px;
margin: 0;
padding: 0;
border: none;
background: var(--loose);
color: var(--on-loose);
font: inherit;
font-weight: 600;
font-size: 15px;
}
/* The outline sits outside the black tile, against the rack. */
.tile.actionable {
outline-offset: 3px;
}
/* The selected tile keeps its black face; the accent outline replaces the ink one. */
.tile.actionable.selected {
outline: 4px solid var(--accent);
}
.tile small {
font-size: 9px;
font-weight: 400;
line-height: 1.1;
text-align: center;
padding: 0 2px;
color: var(--on-loose);
}
.none {
color: var(--ink-muted);
}
</style>

View file

@ -0,0 +1,62 @@
<script lang="ts">
import type { GameState } from "acquire-engine";
import { describeEntry } from "./format";
import { useStore } from "./store.svelte";
let { state: game }: { state: GameState } = $props();
// The log has no scroll box of its own (nested scrolling traps touch users); it shows the most
// recent lines and expands in place.
const RECENT = 25;
const store = useStore();
const t = $derived(store.lang.t);
let showAll = $state(false);
// Newest first; "turn" entries become headings that group the lines below them.
const lines = $derived(
game.log
.map((entry, index) => ({ index, turn: entry.type === "turn", text: describeEntry(game, entry, store.lang) }))
.filter((line): line is { index: number; turn: boolean; text: string } => line.text !== undefined)
.reverse()
);
</script>
<section aria-label={t("log.label")}>
<h2>{t("log.title")}</h2>
<ol class="log">
{#each showAll ? lines : lines.slice(0, RECENT) as line (line.index)}
<li class:turn={line.turn}>{line.text}</li>
{/each}
</ol>
{#if lines.length > RECENT}
<button type="button" class="more actionable" onclick={() => (showAll = !showAll)}>
{showAll ? t("log.recent") : t("log.all", { count: lines.length - RECENT })}
</button>
{/if}
</section>
<style>
.log {
list-style: none;
margin: 0;
padding: 0;
font-size: 14px;
}
.log li {
padding: 2px 6px;
}
.log li.turn {
margin-top: 6px;
font-weight: 600;
background: var(--panel-alt);
}
.more {
margin: 8px 0 0;
padding: 6px 12px;
min-height: 44px;
background: var(--page);
color: var(--ink);
font: inherit;
border: none;
}
</style>

View file

@ -0,0 +1,59 @@
<script lang="ts">
import { playerSymbolSvg } from "@boardgamers/protocol/player-symbols";
import type { GameState } from "acquire-engine";
import { seatName } from "./format";
import { useStore } from "./store.svelte";
/** `playerOnly` names the player without a seat number (fourHands results are per player). */
let { state: game, seat, playerOnly = false }: { state: GameState; seat: number; playerOnly?: boolean } = $props();
const store = useStore();
// BGS appearance data is per real player; in fourHands two seats share one player.
const player = $derived(game.seatOwner[seat] ?? seat);
const avatar = $derived(store.avatars[player]);
const color = $derived(store.appearance?.playerColors[player]);
const symbol = $derived(store.appearance?.playerSymbols?.[player]);
const badge = $derived(store.appearance?.players[player]?.pro ? store.appearance.supporterBadge : undefined);
</script>
<span class="player">
{#if avatar}<img class="avatar" src={avatar} alt="" />{/if}
<!-- The player colour is only ever this narrow bar, never a fill, so it can't pass for a chain. -->
{#if color}<span class="color" style:background={color} aria-hidden="true"></span>{/if}
<!-- Catalogued symbol SVGs only: an unknown value renders nothing. -->
{#if symbol}<span class="symbol" aria-hidden="true">{@html playerSymbolSvg(symbol)}</span>{/if}
<span class="name">{playerOnly ? game.seats[seat]!.name : seatName(game, seat, store.lang)}</span>
{#if badge}<img class="badge" src={badge.url} alt={badge.label} title={badge.label} />{/if}
</span>
<style>
.player {
display: inline-flex;
align-items: center;
gap: 5px;
vertical-align: middle;
}
.avatar {
width: 22px;
height: 22px;
object-fit: cover;
}
.color {
width: 4px;
height: 16px;
}
.symbol {
display: inline-flex;
width: 12px;
height: 12px;
color: var(--ink);
}
.symbol :global(svg) {
width: 100%;
height: 100%;
}
.badge {
width: 16px;
height: 16px;
}
</style>

View file

@ -0,0 +1,90 @@
<script lang="ts">
import { CHAIN_IDS, HIDDEN, currentSeat, type GameState } from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import PlayerName from "./PlayerName.svelte";
import { useStore } from "./store.svelte";
let { state, seats }: { state: GameState; seats: number[] } = $props();
const acting = $derived(currentSeat(state));
const store = useStore();
const t = $derived(store.lang.t);
</script>
<section aria-label={t("players.label")}>
<h2>{t("players.title")}</h2>
<table>
<thead>
<tr>
<th>{t("players.player")}</th>
<th class="num">{t("players.cash")}</th>
<th>{t("players.stock")}</th>
<th class="num">{t("players.tiles")}</th>
</tr>
</thead>
<tbody>
{#each state.seats as seat, index (index)}
{@const held = CHAIN_IDS.filter((chain) => seat.shares[chain] !== 0)}
{@const hidden = seat.cash === HIDDEN}
<tr class:you={seats.includes(index)}>
<td>
{#if index === acting}<span class="turn" aria-label={t("players.acting")}>▶</span>{/if}
<PlayerName {state} seat={index} />
{#if seats.includes(index)}<span class="tag">{t("players.you")}</span>{/if}
{#if index === state.activeSeat && index !== acting && !state.ended}<span class="tag"
>{t("players.turn")}</span
>{/if}
{#if seat.dropped}<span class="tag">{t("players.left")}</span>{/if}
</td>
<td class="num" class:hidden-value={hidden}>{store.lang.money(seat.cash)}</td>
<td>
{#if hidden}
<span class="hidden-value">{t("hidden")}</span>
{:else if held.length === 0}
<span class="none">{t("players.none")}</span>
{:else}
<span class="stock">
{#each held as chain (chain)}
<span class="holding"><ChainMark {chain} />{seat.shares[chain]}</span>
{/each}
</span>
{/if}
</td>
<td class="num">{seat.hand.length}</td>
</tr>
{/each}
</tbody>
</table>
</section>
<style>
.you td {
font-weight: 600;
}
.turn {
color: var(--ink);
margin-right: 2px;
}
.tag {
margin-left: 6px;
padding: 0 4px;
font-size: 11px;
font-weight: 600;
background: var(--panel);
color: var(--ink-muted);
}
.stock {
display: inline-flex;
flex-wrap: wrap;
gap: 8px;
}
.holding {
display: inline-flex;
align-items: center;
gap: 3px;
font-variant-numeric: tabular-nums;
}
.none {
color: var(--ink-muted);
}
</style>

View file

@ -0,0 +1,123 @@
<script lang="ts">
import { activeChains, chainSize, chainTier, type GameState } from "acquire-engine";
import ChainMark from "./ChainMark.svelte";
import { useStore } from "./store.svelte";
import { TIERS, chainsInTier, priceTable, rangeLabel, rowIndexFor } from "./priceTable";
let { state: game }: { state: GameState } = $props();
const table = priceTable();
const store = useStore();
const t = $derived(store.lang.t);
const money = $derived(store.lang.money);
const TIER_KEYS = { minor: "prices.minor", medium: "prices.medium", major: "prices.major" } as const;
let open = $state(false);
// Each active chain is marked in its tier column, in the row matching its current size.
const marks = $derived(
activeChains(game.board).map((chain) => {
const tier = chainTier(chain);
return { chain, tier, row: rowIndexFor(table, tier, chainSize(game.board, chain)) };
})
);
</script>
<section aria-label={t("prices.label")}>
<button type="button" class="toggle actionable" aria-expanded={open} onclick={() => (open = !open)}>
{open ? t("prices.hide") : t("prices.show")}
</button>
{#if open}
<table class="prices">
<thead>
<tr>
{#each TIERS as tier (tier)}
<th class="tier" scope="col">
<span class="sr-only">{t(TIER_KEYS[tier])}</span>
<span class="heads">
{#each chainsInTier(tier) as chain (chain)}<ChainMark
{chain}
small
patterned={store.colorBlind}
/>{/each}
</span>
</th>
{/each}
<th class="num" scope="col">{t("prices.price")}</th>
<th class="num" scope="col">{t("prices.first")}</th>
<th class="num" scope="col">{t("prices.second")}</th>
</tr>
</thead>
<tbody>
{#each table as row, index (row.price)}
<tr>
{#each TIERS as tier (tier)}
{@const here = marks.filter((mark) => mark.tier === tier && mark.row === index)}
<td class="tier">
<span class="size">{rangeLabel(row.sizes[tier])}</span>
{#if here.length > 0}
<span class="heads">
{#each here as mark (mark.chain)}<ChainMark
chain={mark.chain}
small
patterned={store.colorBlind}
/>{/each}
</span>
{/if}
</td>
{/each}
<td class="num">{money(row.price)}</td>
<td class="num">{money(row.first)}</td>
<td class="num">{money(row.second)}</td>
</tr>
{/each}
</tbody>
</table>
<p class="note">{t("prices.note")}</p>
{/if}
</section>
<style>
.toggle {
padding: 6px 12px;
min-height: 44px;
background: var(--page);
color: var(--ink);
font: inherit;
border: none;
}
/* Six columns must fit a 375px phone: compact type, and markers wrap under the size. */
.prices {
margin: 8px 0 0;
table-layout: fixed;
font-size: 12px;
}
.prices th,
.prices td {
padding: 3px 3px;
vertical-align: top;
}
.tier {
width: 19%;
}
.heads {
display: flex;
flex-wrap: wrap;
gap: 2px;
margin-top: 2px;
}
.size {
font-variant-numeric: tabular-nums;
}
.note {
font-size: 12px;
color: var(--ink-muted);
margin: 4px 0 0;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
</style>

View file

@ -0,0 +1,92 @@
<script lang="ts">
import { currentSeat, playerRankings, playerScores, type GameState } from "acquire-engine";
import { pendingDecision } from "./format";
import PlayerName from "./PlayerName.svelte";
import { useStore } from "./store.svelte";
let { state, seats }: { state: GameState; seats: number[] } = $props();
const store = useStore();
const t = $derived(store.lang.t);
const replaying = $derived(store.replayAt !== undefined);
const replayTurn = $derived(state.log.filter((entry) => entry.type === "turn").length);
const yourMove = $derived(!replaying && seats.includes(currentSeat(state) ?? -1));
const results = $derived(
state.ended
? playerScores(state)
.map((score, player) => ({
player,
score,
rank: playerRankings(state)[player]!,
seat: state.seatOwner.indexOf(player),
}))
.sort((a, b) => a.rank - b.rank)
: []
);
</script>
<section class="status" class:yours={yourMove} aria-live="polite">
{#if replaying}
<p class="pending">{t("status.replay", { turn: replayTurn })}</p>
<p class="note">{t("status.replayNote")}</p>
{:else}
<p class="pending">
{pendingDecision(state, store.lang)}{#if yourMove}<span class="you">{t("status.yourDecision")}</span>{/if}
</p>
{/if}
{#if !replaying && state.endAnnounced !== null && !state.ended}
<p class="note">{t("status.announced")}</p>
{/if}
{#if !replaying && state.ended}
<ol class="results">
{#each results as result (result.player)}
<li>
<span class="rank">{result.rank}.</span>
<PlayerName {state} seat={result.seat} playerOnly />
<span class="score">{store.lang.money(result.score)}</span>
</li>
{/each}
</ol>
{/if}
</section>
<style>
.status {
background: var(--panel);
padding: 8px 10px;
margin: 0 0 12px;
box-shadow: inset 4px 0 0 var(--gap);
}
.status.yours {
box-shadow: inset 6px 0 0 var(--accent);
}
.pending {
margin: 0;
font-size: 17px;
font-weight: 600;
}
.you {
margin-left: 8px;
font-weight: 400;
font-size: 14px;
color: var(--ink-muted);
}
.note {
margin: 4px 0 0;
font-size: 14px;
}
.results {
margin: 6px 0 0;
padding: 0;
list-style: none;
}
.rank {
display: inline-block;
width: 24px;
font-weight: 700;
}
.score {
font-variant-numeric: tabular-nums;
margin-left: 6px;
}
</style>

View file

@ -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<Deficiency, number[][]> = {
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);
}

View file

@ -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<Move, { type: "buy" }>
).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"]);
});

View file

@ -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<T extends Move["type"]> = Extract<Move, { type: T }>;
/** 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<T extends Move["type"]>(moves: Move[], type: T): MoveOf<T>[] {
return moves.filter((move): move is MoveOf<T> => 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<Shares>, b: Partial<Shares>): 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<Shares>): 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<Shares>, chain: ChainId, delta: number): Partial<Shares> {
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<ChainId>();
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));
}

View file

@ -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<string, MessageKey>;
/** 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)}`)) });
}
}

View file

@ -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<string> => 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");
});

View file

@ -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<Record<Intl.LDMLPluralRule, string>> & { other: string };
export type Message = string | PluralMessage;
export type Catalog = Record<MessageKey, Message>;
// 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<Locale, Catalog> = {
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<string, string | number>;
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)}`;
}

View file

@ -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",
};

View file

@ -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",
};

View file

@ -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": "επεξεργάστηκε",
};

View file

@ -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;

View file

@ -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": "ویرایش‌شده",
};

View file

@ -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é",
};

View file

@ -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": "संपादित",
};

View file

@ -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",
};

View file

@ -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": "수정됨",
};

View file

@ -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",
};

View file

@ -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",
};

View file

@ -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",
};

View file

@ -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",
};

Some files were not shown because too many files have changed in this diff Show more