Add Puerto Rico Special Edition playable preview and modular engine

This commit is contained in:
coyotte508 2026-10-01 12:46:56 +02:00
commit 274d5c0d1f
21 changed files with 5342 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
node_modules/
dist/
.local/
test-results/

47
README.md Normal file
View file

@ -0,0 +1,47 @@
# Puerto Rico: Special Edition
Local implementation for Boardgamers Space, targeting **Puerto Rico 1897: Special Edition** and the official June 2026 errata. Nothing has been uploaded or published.
```sh
pnpm install
pnpm dev
# http://127.0.0.1:5251/?locale=fr
```
The local preview lets you play one seat with two ordinary bots. Its initial building selection is performed automatically so you can start with role selection. The actual engine has the full shared building selection phase. Local progress is saved in the browser. The small local toolbar offers undo, opponent turns, restart and light/dark; it is absent from the hosted viewer.
## Edition configuration
`release-config.js` defines one fixed Special Edition configuration. `bgs/engine.js` uses it regardless of creation-form expansion fields; the BGS metadata intentionally exposes **no expansion picker or game options**. The core engine in `engine/index.js` accepts independent expansion switches for future configuration, simulation and tests.
Implemented modules:
- Base game, 2–5 players, including the classic two-player rules.
- New Buildings: all 14 building types and cost-constrained shared market selection.
- Citizens: 20 citizens, 8 building types, occupancy-dependent effects and scoring.
- Smuggler: all four actions, role capture, surplus worker/citizen choices.
- Festival: three shared objectives and physical resource reservations.
- Festival Activities: all 12 activity definitions, three drawn per game.
**Not complete:** the 30-card Achievements deck has not been found in the official resources. It is deliberately not enabled or replaced with invented cards. Puertoma is not implemented; the preview bots use the normal human rules. See [source notes](docs/sources.md), including a Festival/unique-building ambiguity that needs a ruling before release.
The engine accepts the optional `costSwap`, `alternativeStart`, `tailorLimit` and `pairingRestrictions` balance variants internally. They are disabled in the fixed configuration and not exposed in the UI.
## Viewer and integration
- French and English, using the platform locale; no language controls.
- Distinct goods pictograms; color is supplementary.
- Editable worker allocation, goods storage, building details, private shipping, final scoring.
- Desktop and mobile layout, incremental DOM updates, native page and modal scrolling.
- BGS chat and replay, concealed VP totals, server-only randomness and future draws.
- Deterministic ordinary bots for local testing and BGS bot seats.
## Validation
```sh
pnpm test # rule scenarios, legal complete games, resource conservation, replay
pnpm build # dist/engine.js, dist/viewer.js, local sandbox
pnpm test:browser # 320/390/768/1440px, real viewer events, chat/journal scrolling
```
The implementation remains a preview pending playtesting, the missing card data, and the rule ambiguity noted above. Original vector UI artwork is in `viewer/icons.js`; reference scans in `.local/` are ignored and never bundled.

6
bgs/engine.js Normal file
View file

@ -0,0 +1,6 @@
export * from "../engine/index.js";
import { init as create } from "../engine/index.js";
import { RELEASE } from "../release-config.js";
export function init(players, _expansions, _options, seed) {
return create(players, RELEASE.expansions, RELEASE.options, seed);
}

11
bgs/game.json Normal file
View file

@ -0,0 +1,11 @@
{
"name": "Puerto Rico: Special Edition",
"players": [2, 3, 4, 5],
"topLevelVariable": "puertorico",
"options": [],
"expansions": [],
"preferences": [],
"settings": [],
"status": "local-preview",
"locales": ["en", "fr"]
}

22
docs/sources.md Normal file
View file

@ -0,0 +1,22 @@
# Edition and rule sources
Target: **Puerto Rico 1897: Special Edition** (Awaken Realms / Ravensburger).
- [Publisher](https://awakenrealms.com/games/awaken-realms/puerto-rico)
- [English rulebook, 44 pages](https://awakenrealms.com/images/download/puerto-rico/EN/EN_PR_Rulebook_210x285mm_bleed3mm%20%5B44%20pages%5D.pdf)
- [Official errata v1.0, 2 June 2026](https://awakenrealms.com/images/download/puerto-rico/EN/PR_Others_Errata_297x210mm_bleed3mm.pdf)
- [Publisher downloads and translated rulebooks](https://awakenrealms.com/download)
Apply the errata: game-end triggers finish the **round**, including VP depletion outside the Captain phase; replace a worker with a citizen before withdrawing workers from the supply; Publishing House's second estate does not receive a Hospital worker; Lighthouse's Captain coin requires an occupied Lighthouse.
New Buildings and Citizens use the cost-constrained building selection described in this edition. Two-player games use the classic two-player rules on page 22. Optional balance variants remain separate options.
## Outstanding source data
The book describes Achievements but does not supply the complete 30-card deck. Do not invent replacement objectives or advertise this module as complete. Puertoma also needs its exact tiebreaker deck verified. Ordinary bots play the human rules and are not presented as Puertoma.
### Festival building markers: unresolved rulebook conflict
Pages 29–31 reserve a building as an objective marker and return it after the objective is completed. Town Patron requires an expanded building, of which only one copy exists; two-player setup also has only one copy of each commercial building. Removing that copy makes its own objective impossible. The preview uses a reference marker in those cases, keeping the unique building purchasable. With multiple copies it reserves one as written. This is an explicit implementation interpretation, **not a verified publisher ruling**, and needs confirmation before a release claiming exact rules compliance.
Reference PDFs live only in ignored `.local/rules/`; they are not shipped as game assets. UI illustrations are original code-generated vectors.

149
engine/catalog.js Normal file
View file

@ -0,0 +1,149 @@
export const GOODS = ["corn", "fruit", "sugar", "tobacco", "coffee"];
export const ESTATES = {
corn: 10,
fruit: 12,
sugar: 11,
tobacco: 9,
coffee: 8,
};
export const CRATES = { corn: 10, fruit: 11, sugar: 11, tobacco: 9, coffee: 9 };
export const ROLES = [
"planter",
"recruiter",
"builder",
"craftsman",
"trader",
"captain",
];
// Cost, printed points, worker capacity, copies; expanded buildings use two city spaces.
const rows = [
["smallFruit", 1, 1, 1, 4, "fruit"],
["smallSugar", 2, 1, 1, 4, "sugar"],
["largeFruit", 3, 2, 3, 3, "fruit"],
["largeSugar", 4, 2, 3, 3, "sugar"],
["tobaccoStorage", 5, 3, 3, 3, "tobacco"],
["coffeeRoaster", 6, 3, 2, 3, "coffee"],
["smallMarket", 1, 1],
["buildersYard", 2, 1],
["hacienda", 2, 1],
["smallWarehouse", 3, 1],
["hospital", 4, 2],
["office", 5, 2],
["largeMarket", 5, 2],
["largeWarehouse", 6, 2],
["factory", 7, 3],
["school", 8, 3],
["harbor", 8, 3],
["wharf", 9, 3],
["fireStation", 10, 4],
["residence", 10, 4],
["fortress", 10, 4],
["customsHouse", 10, 4],
["cityHall", 10, 4],
["canal", 1, 1],
["lumberyard", 2, 1],
["hiddenMarket", 2, 1],
["storehouse", 3, 1],
["bohio", 4, 2, 2],
["merchantOutpost", 5, 2],
["church", 5, 2],
["smallWharf", 6, 2],
["lighthouse", 7, 3],
["distillery", 8, 3],
["publishingHouse", 8, 3],
["assemblyHall", 9, 3],
["monument", 10, 8],
["cathedral", 10, 4],
["zoningOffice", 2, 1],
["chapel", 3, 1],
["parkAuthority", 4, 2],
["notary", 5, 2],
["pensionOffice", 6, 2],
["villa", 7, 3],
["tailorShop", 8, 3, 1, 2, "tailor"],
["townSquare", 10, 4],
];
export const BUILDINGS = Object.fromEntries(
rows.map(([id, cost, vp, workers = 1, copies, good], i) => [
id,
{
id,
cost,
vp,
workers,
copies: copies ?? (cost === 10 ? 1 : 2),
good: good ?? null,
size: cost === 10 ? 2 : 1,
expansion: i < 23 ? "base" : i < 37 ? "new-buildings" : "citizens",
},
]),
);
export const MARKET_SLOTS = {
1: 1,
2: 2,
3: 1,
4: 1,
5: 2,
6: 1,
7: 1,
8: 2,
9: 1,
10: 5,
};
export const EXPANSIONS = [
"new-buildings",
"citizens",
"smuggler",
"festival",
"festival-cards",
];
export const FESTIVALS = [
{
id: "weightOff",
goods: 1,
goal: "produce",
amount: 3,
reward: { workers: 1, coins: 1, vp: 1 },
},
{
id: "cocktail",
goods: 3,
goal: "produce",
amount: 1,
reward: { coins: 3 },
},
{ id: "closingShops", goods: 1, goal: "tradeFull", reward: { workers: 2 } },
{
id: "connoisseur",
estates: 1,
goal: "estates",
amount: 3,
reward: { workers: 3 },
},
{
id: "farming",
estates: 2,
goods: 2,
goal: "farmProduce",
amount: 1,
reward: { coins: 3 },
},
{
id: "delivery",
goods: 2,
goal: "ship",
amounts: [1, 2],
reward: { workers: 2, vp: 2 },
},
{ id: "twins", estates: 2, goal: "estates", amount: 2, reward: { vp: 3 } },
{ id: "baskets", goods: 2, goal: "produce", amount: 2, reward: { coins: 3 } },
{ id: "grandSendoff", goods: 1, goal: "dispatchBig", reward: { workers: 3 } },
{ id: "pioneer", building: 3, goal: "build", reward: { vp: 3 } },
{ id: "patron", building: 4, goal: "build", reward: { vp: 3 } },
{
id: "traditionalSendoff",
goods: 1,
goal: "dispatchSmall",
reward: { coins: 2 },
},
];

1612
engine/index.js Normal file

File diff suppressed because it is too large Load diff

23
package.json Normal file
View file

@ -0,0 +1,23 @@
{
"name": "@boardgamers/puerto-rico",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",
"scripts": {
"test": "node --test test/*.test.js",
"build": "node scripts/build.mjs",
"dev": "node scripts/dev.mjs",
"test:browser": "node test/browser.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.8.0",
"@noble/hashes": "2.0.1",
"morphdom": "2.7.8"
},
"devDependencies": {
"esbuild": "0.28.2",
"playwright": "1.62.1",
"prettier": "3.6.2"
}
}

357
pnpm-lock.yaml generated Normal file
View file

@ -0,0 +1,357 @@
lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
importers:
.:
dependencies:
'@boardgamers/protocol':
specifier: 0.8.0
version: 0.8.0
'@noble/hashes':
specifier: 2.0.1
version: 2.0.1
morphdom:
specifier: 2.7.8
version: 2.7.8
devDependencies:
esbuild:
specifier: 0.28.2
version: 0.28.2
playwright:
specifier: 1.62.1
version: 1.62.1
prettier:
specifier: 3.6.2
version: 3.6.2
packages:
'@boardgamers/protocol@0.8.0':
resolution: {integrity: sha512-5Wm5ExUwe0NDFRxCKgnPkMdvgpDgGF+0Z/lvSVox0/1pDEHB/fMx+YHMrBMKSIRp2j//ibiSC5U1BX24wdO0Mw==}
'@esbuild/aix-ppc64@0.28.2':
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
'@esbuild/android-arm64@0.28.2':
resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
'@esbuild/android-arm@0.28.2':
resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
'@esbuild/android-x64@0.28.2':
resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
'@esbuild/darwin-arm64@0.28.2':
resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
'@esbuild/darwin-x64@0.28.2':
resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
'@esbuild/freebsd-arm64@0.28.2':
resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
'@esbuild/freebsd-x64@0.28.2':
resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
'@esbuild/linux-arm64@0.28.2':
resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
'@esbuild/linux-arm@0.28.2':
resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
'@esbuild/linux-ia32@0.28.2':
resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
'@esbuild/linux-loong64@0.28.2':
resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
'@esbuild/linux-mips64el@0.28.2':
resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
'@esbuild/linux-ppc64@0.28.2':
resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
'@esbuild/linux-riscv64@0.28.2':
resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
'@esbuild/linux-s390x@0.28.2':
resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
'@esbuild/linux-x64@0.28.2':
resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
'@esbuild/netbsd-arm64@0.28.2':
resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
'@esbuild/netbsd-x64@0.28.2':
resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
'@esbuild/openbsd-arm64@0.28.2':
resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
'@esbuild/openbsd-x64@0.28.2':
resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
'@esbuild/openharmony-arm64@0.28.2':
resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
'@esbuild/sunos-x64@0.28.2':
resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
'@esbuild/win32-arm64@0.28.2':
resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
'@esbuild/win32-ia32@0.28.2':
resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
'@esbuild/win32-x64@0.28.2':
resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
'@noble/hashes@2.0.1':
resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==}
engines: {node: '>= 20.19.0'}
esbuild@0.28.2:
resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}
engines: {node: '>=18'}
hasBin: true
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
morphdom@2.7.8:
resolution: {integrity: sha512-D/fR4xgGUyVRbdMGU6Nejea1RFzYxYtyurG4Fbv2Fi/daKlWKuXGLOdXtl+3eIwL110cI2hz1ZojGICjjFLgTg==}
playwright-core@1.62.1:
resolution: {integrity: sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==}
engines: {node: '>=20'}
hasBin: true
playwright@1.62.1:
resolution: {integrity: sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==}
engines: {node: '>=20'}
hasBin: true
prettier@3.6.2:
resolution: {integrity: sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==}
engines: {node: '>=14'}
hasBin: true
zod@4.6.5:
resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}
snapshots:
'@boardgamers/protocol@0.8.0':
dependencies:
zod: 4.6.5
'@esbuild/aix-ppc64@0.28.2':
optional: true
'@esbuild/android-arm64@0.28.2':
optional: true
'@esbuild/android-arm@0.28.2':
optional: true
'@esbuild/android-x64@0.28.2':
optional: true
'@esbuild/darwin-arm64@0.28.2':
optional: true
'@esbuild/darwin-x64@0.28.2':
optional: true
'@esbuild/freebsd-arm64@0.28.2':
optional: true
'@esbuild/freebsd-x64@0.28.2':
optional: true
'@esbuild/linux-arm64@0.28.2':
optional: true
'@esbuild/linux-arm@0.28.2':
optional: true
'@esbuild/linux-ia32@0.28.2':
optional: true
'@esbuild/linux-loong64@0.28.2':
optional: true
'@esbuild/linux-mips64el@0.28.2':
optional: true
'@esbuild/linux-ppc64@0.28.2':
optional: true
'@esbuild/linux-riscv64@0.28.2':
optional: true
'@esbuild/linux-s390x@0.28.2':
optional: true
'@esbuild/linux-x64@0.28.2':
optional: true
'@esbuild/netbsd-arm64@0.28.2':
optional: true
'@esbuild/netbsd-x64@0.28.2':
optional: true
'@esbuild/openbsd-arm64@0.28.2':
optional: true
'@esbuild/openbsd-x64@0.28.2':
optional: true
'@esbuild/openharmony-arm64@0.28.2':
optional: true
'@esbuild/sunos-x64@0.28.2':
optional: true
'@esbuild/win32-arm64@0.28.2':
optional: true
'@esbuild/win32-ia32@0.28.2':
optional: true
'@esbuild/win32-x64@0.28.2':
optional: true
'@noble/hashes@2.0.1': {}
esbuild@0.28.2:
optionalDependencies:
'@esbuild/aix-ppc64': 0.28.2
'@esbuild/android-arm': 0.28.2
'@esbuild/android-arm64': 0.28.2
'@esbuild/android-x64': 0.28.2
'@esbuild/darwin-arm64': 0.28.2
'@esbuild/darwin-x64': 0.28.2
'@esbuild/freebsd-arm64': 0.28.2
'@esbuild/freebsd-x64': 0.28.2
'@esbuild/linux-arm': 0.28.2
'@esbuild/linux-arm64': 0.28.2
'@esbuild/linux-ia32': 0.28.2
'@esbuild/linux-loong64': 0.28.2
'@esbuild/linux-mips64el': 0.28.2
'@esbuild/linux-ppc64': 0.28.2
'@esbuild/linux-riscv64': 0.28.2
'@esbuild/linux-s390x': 0.28.2
'@esbuild/linux-x64': 0.28.2
'@esbuild/netbsd-arm64': 0.28.2
'@esbuild/netbsd-x64': 0.28.2
'@esbuild/openbsd-arm64': 0.28.2
'@esbuild/openbsd-x64': 0.28.2
'@esbuild/openharmony-arm64': 0.28.2
'@esbuild/sunos-x64': 0.28.2
'@esbuild/win32-arm64': 0.28.2
'@esbuild/win32-ia32': 0.28.2
'@esbuild/win32-x64': 0.28.2
fsevents@2.3.2:
optional: true
morphdom@2.7.8: {}
playwright-core@1.62.1: {}
playwright@1.62.1:
dependencies:
playwright-core: 1.62.1
optionalDependencies:
fsevents: 2.3.2
prettier@3.6.2: {}
zod@4.6.5: {}

2
pnpm-workspace.yaml Normal file
View file

@ -0,0 +1,2 @@
allowBuilds:
esbuild: true

16
release-config.js Normal file
View file

@ -0,0 +1,16 @@
// Game creation uses this fixed edition. Expansion switches are engine configuration,
// intentionally not exposed in the published viewer or the BGS game creation form.
export const MODULES = {
"new-buildings": true,
citizens: true,
smuggler: true,
festival: true,
"festival-cards": true,
// Reserved switch; enabling it is blocked until the complete official deck is verified.
achievements: false,
};
export const RELEASE = {
name: "Puerto Rico: Special Edition",
expansions: Object.keys(MODULES).filter((id) => MODULES[id]),
options: {},
};

36
scripts/build.mjs Normal file
View file

@ -0,0 +1,36 @@
import { build } from "esbuild";
import { mkdir, writeFile } from "node:fs/promises";
await mkdir("dist", { recursive: true });
const common = {
bundle: true,
minify: true,
target: ["chrome109", "firefox115", "safari15.4"],
loader: { ".css": "text" },
};
await Promise.all([
build({
...common,
entryPoints: ["viewer/index.js"],
outfile: "dist/viewer.js",
format: "iife",
}),
build({
...common,
entryPoints: ["viewer/preview.js"],
outfile: "dist/preview.js",
format: "esm",
}),
build({
...common,
entryPoints: ["bgs/engine.js"],
outfile: "dist/engine.js",
platform: "node",
format: "esm",
target: "node20",
}),
]);
await writeFile(
"dist/index.html",
`<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#254c4e"><title>Puerto Rico · Preview</title><style>body{margin:0}button,input{font:inherit}</style></head><body><main id="game"></main><script type="module" src="/preview.js"></script></body></html>`,
);
console.log("Built engine, BGS viewer and local preview.");

34
scripts/dev.mjs Normal file
View file

@ -0,0 +1,34 @@
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { resolve, extname } from "node:path";
import "./build.mjs";
const root = resolve("dist"),
port = Number(process.env.PORT ?? 5251);
createServer(async (req, res) => {
try {
const pathname = decodeURIComponent(
new URL(req.url, "http://localhost").pathname,
),
path = resolve(root, pathname === "/" ? "index.html" : pathname.slice(1));
if (!path.startsWith(root + "/")) {
res.writeHead(403).end();
return;
}
const content = await readFile(path);
res
.writeHead(200, {
"Content-Type":
{
".js": "text/javascript",
".css": "text/css",
".html": "text/html",
}[extname(path)] ?? "application/octet-stream",
"Cache-Control": "no-store",
})
.end(content);
} catch {
res.writeHead(404).end();
}
}).listen(port, "127.0.0.1", () =>
console.log(`Puerto Rico preview: http://127.0.0.1:${port}/?locale=fr`),
);

154
test/browser.mjs Normal file
View file

@ -0,0 +1,154 @@
import assert from "node:assert/strict";
import { chromium } from "playwright";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import * as E from "../engine/index.js";
import { RELEASE } from "../release-config.js";
const server = createServer(async (req, res) => {
res.setHeader(
"Content-Type",
req.url.endsWith(".js") ? "text/javascript" : "text/html",
);
res.end(
req.url === "/viewer.js"
? await readFile(new URL("../dist/viewer.js", import.meta.url))
: '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><style>body{margin:0}</style><div id="game"></div><script src="/viewer.js"></script>',
);
});
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const url = `http://127.0.0.1:${server.address().port}`;
const browser = await chromium.launch();
await mkdir(".local/qa", { recursive: true });
let original = E.init(3, RELEASE.expansions, RELEASE.options, "browser");
while (original.tasks[0].kind === "draft") original = E.moveAI(original);
const full = (() => {
let s = original;
while (!s.finished) s = E.moveAI(s);
return s;
})();
try {
for (const width of [320, 390, 768, 1440]) {
const page = await browser.newPage({
viewport: { width, height: 844 },
hasTouch: true,
});
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(url);
await page.evaluate(
(s) => {
window.host = puertorico.launch("#game");
window.played = [];
host.on("move", (m) => played.push(m));
host.emit("player", { index: 0 });
host.emit("preferences", { locale: "fr" });
host.emit("state", s);
},
E.stripSecret(original, 0),
);
const overflow = () =>
page.evaluate(
() => document.documentElement.scrollWidth > innerWidth + 1,
);
assert.equal(await overflow(), false, `No page overflow at ${width}`);
await page.locator('[data-panel="rules"]').click();
assert.equal(await page.locator("dialog[open]").count(), 1);
await page.keyboard.press("Escape");
await page.locator('[data-panel="journal"]').click();
await page.keyboard.press("Escape");
const m = { type: "role", id: "recruiter" };
await page
.locator(`[data-move="${encodeURIComponent(JSON.stringify(m))}"]`)
.click();
assert.deepEqual(await page.evaluate(() => played.at(-1)), m);
let s = E.move(original, m, 0);
while (s.tasks[0].kind !== "assign") s = E.moveAI(s);
s.tasks[0].p = 0;
await page.evaluate((s) => host.emit("state", s), E.stripSecret(s, 0));
await page.locator("[data-confirm-assign]").waitFor({ state: "visible" });
assert.ok(await page.locator("[data-slot]").count());
await page.locator("[data-confirm-assign]").click();
const allocation = await page.evaluate(() => played.at(-1));
assert.equal(allocation.type, "assign");
s = E.move(s, allocation, 0);
await page.evaluate((s) => host.emit("state", s), E.stripSecret(s, 0));
await page.screenshot({
path: `.local/qa/${width}-board.png`,
fullPage: true,
});
// Identical state notifications preserve the SVG/board nodes instead of redrawing them.
await page.evaluate(
(s) => {
window.shipNode = document.querySelector(".ship-art");
host.emit("state", s);
},
E.stripSecret(s, 0),
);
assert.ok(
await page.evaluate(
() => shipNode === document.querySelector(".ship-art"),
),
);
// Journal and final scoring remain scrollable even on the smallest viewport.
await page.evaluate((s) => host.emit("state", s), E.stripSecret(full, 0));
await page.locator('[data-panel="journal"]').click();
const log = page.locator(".pr-modal .modal-body");
await log.evaluate((el) => (el.scrollTop = 0));
await log.hover();
await page.mouse.wheel(0, 520);
await page.waitForTimeout(120);
assert.ok((await log.evaluate((el) => el.scrollTop)) > 0);
await page.keyboard.press("Escape");
await page.locator("[data-scores]").click();
assert.equal(await overflow(), false);
assert.ok((await page.locator(".scores article").count()) === 3);
await page.keyboard.press("Escape");
// Scroll starts on disabled controls without interception.
await page.evaluate(
(s) => host.emit("state", s),
E.stripSecret(original, 0),
);
await page.evaluate(() => scrollTo(0, 0));
const disabled = page.locator(".offer:disabled").first();
const box = await disabled.boundingBox();
await page.mouse.move(box.x + 10, box.y + 10);
await page.mouse.wheel(0, 400);
await page.waitForTimeout(120);
assert.ok((await page.evaluate(() => scrollY)) > 0);
// Chat uses the platform's messages and a scrolling native viewport.
await page.evaluate(() => {
host.emit("chat:state", { enabled: true, canSend: true, mentions: [] });
host.emit(
"chat:messages",
Array.from({ length: 70 }, (_, i) => ({
_id: `message-${i}`,
type: "text",
author: "Isabel",
playerIndex: 1,
text: `Message ${i}: plenty of chat history to scroll.`,
createdAt: new Date(1700000000000 + i * 1000).toISOString(),
})),
);
});
await page.locator('[data-panel="chat"]').click();
await page.waitForTimeout(100);
const chat = page.locator('.pr-chat [role="log"]');
assert.ok(await chat.evaluate((el) => el.scrollHeight > el.clientHeight));
await chat.evaluate((el) => (el.scrollTop = 0));
await chat.hover();
await page.mouse.wheel(0, 400);
await page.waitForTimeout(150);
assert.ok((await chat.evaluate((el) => el.scrollTop)) > 0);
const composer = await page.locator(".chat-composer").boundingBox();
assert.ok(composer.y + composer.height <= 844);
await page.keyboard.press("Escape");
assert.deepEqual(errors, [], `No browser errors at ${width}`);
console.log(
`Browser ${width}px: actions, allocation, layout, journal, chat and scrolling OK`,
);
await page.close();
}
} finally {
await browser.close();
server.close();
}

461
test/engine.test.js Normal file
View file

@ -0,0 +1,461 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as e from "../engine/index.js";
import { BUILDINGS as B, GOODS, CRATES, ESTATES } from "../engine/catalog.js";
const empty = () => Object.fromEntries(GOODS.map((g) => [g, 0]));
const tile = (id, w = 1, c = 0) => ({ id, w, c });
function phase(role, owner = 0) {
let s = e.init(3, [], {}, "fixture");
s = e.move(s, { type: "role", id: role }, owner);
return s;
}
function invariant(s) {
for (const g of GOODS) {
const total =
s.supply[g] +
s.players.reduce((n, p) => n + p.goods[g], 0) +
s.trade.filter((x) => x === g).length +
s.ships.reduce((n, sh) => n + (sh.good === g ? sh.amount : 0), 0) +
(s.privateCargo?.[g] ?? 0) +
s.festivals
.filter((f) => f.claimed === undefined)
.reduce((n, f) => n + f.targets.goods.filter((x) => x === g).length, 0);
assert.equal(
total,
CRATES[g] - (s.players.length === 2 ? 2 : 0),
`Conserve ${g}, ${s.role}`,
);
const estates =
s.bag.filter((x) => x === g).length +
s.discard.filter((x) => x === g).length +
s.offer.filter((x) => x === g).length +
s.players.reduce(
(n, p) => n + p.estates.filter((t) => (t.source ?? t.id) === g).length,
0,
) +
s.festivals
.filter((f) => f.claimed === undefined)
.reduce(
(n, f) => n + f.targets.estates.filter((x) => x === g).length,
0,
) +
(s.tasks[0]?.kind === "forest" && s.tasks[0].id === g ? 1 : 0);
assert.equal(
estates,
ESTATES[g] - (s.players.length === 2 ? 3 : 0),
`Conserve ${g} estates`,
);
}
const workerTotal =
s.workerSupply +
s.register.w +
(s.discardedPeople?.w ?? 0) +
s.players.reduce(
(n, p) =>
n +
p.reserve.w +
[...p.estates, ...p.buildings].reduce((v, t) => v + t.w, 0),
0,
);
const citizenTotal =
s.citizenSupply +
s.register.c +
(s.discardedPeople?.c ?? 0) +
s.players.reduce(
(n, p) =>
n +
p.reserve.c +
[...p.estates, ...p.buildings].reduce((v, t) => v + t.c, 0),
0,
);
assert.equal(workerTotal, { 2: 42, 3: 58, 4: 79, 5: 100 }[s.players.length]);
assert.equal(citizenTotal, s.expansions.includes("citizens") ? 20 : 0);
for (const p of s.players) {
assert.ok(p.coins >= 0);
assert.ok(e.citySize(p) <= 12);
assert.ok(p.estates.length <= 12);
for (const t of p.buildings) assert.ok(t.w + t.c <= B[t.id].workers);
for (const t of p.estates)
assert.ok(t.w + t.c <= (t.id === "forest" ? 0 : 1));
}
}
test("setup and secret state are deterministic", () => {
const s = e.init(5, ["citizens"], {}, "same");
assert.deepEqual(s, e.init(5, ["citizens"], {}, "same"));
assert.notDeepEqual(s.bag, e.init(5, ["citizens"], {}, "different").bag);
const spectator = e.stripSecret(s);
assert.equal(spectator.random, undefined);
assert.equal(spectator.config, undefined);
assert.equal(spectator.bag, undefined);
assert.deepEqual(spectator.legal, []);
assert.ok(spectator.players.every((p) => p.vp === null));
assert.equal(e.stripSecret(s, 1).players[1].vp, 0);
});
test("moves are immutable and enforce seat and legal prices", () => {
const s = phase("builder");
const before = structuredClone(s);
assert.throws(() => e.move(s, { type: "build", id: "cityHall" }, 0), {
name: "InvalidMoveError",
});
assert.throws(() => e.move(s, { type: "pass" }, 1));
assert.deepEqual(s, before);
const result = e.move(s, { type: "build", id: "smallFruit" }, 0);
assert.equal(result.players[0].coins, 2);
assert.equal(result.players[0].buildings[0].w, 0);
assert.deepEqual(s, before);
});
test("production requires both estate and matching factory workers", () => {
const p = {
estates: [
tile("corn"),
tile("corn", 0),
tile("fruit"),
tile("fruit"),
tile("fruit"),
],
buildings: [tile("largeFruit", 2)],
};
assert.deepEqual(e.production(p), {
corn: 1,
fruit: 2,
sugar: 0,
tobacco: 0,
coffee: 0,
});
});
test("mandatory shipping uses a matching ship, or an empty one maximizing that good", () => {
const s = phase("captain");
s.players[0].goods = { ...empty(), corn: 5, coffee: 2 };
assert.deepEqual(
e
.shipping(s, 0)
.filter((m) => m.good === "corn")
.map((m) => m.ship),
[1, 2],
);
s.ships[0] = { capacity: 4, good: "corn", amount: 4 };
assert.equal(
e.shipping(s, 0).some((m) => m.good === "corn"),
false,
);
assert.equal(
e.legal(s).some((m) => m.type === "pass"),
false,
);
});
test("Captain privilege applies once per phase and ships unload after storage", () => {
let s = phase("captain");
s.players[0].goods = { ...empty(), corn: 4, sugar: 1 };
s.ships[1] = { capacity: 5, good: "sugar", amount: 3 };
s = e.move(s, { type: "ship", ship: 0, good: "corn" }, 0);
assert.equal(s.players[0].vp, 5);
assert.equal(s.ships[0].amount, 4);
s = e.move(s, { type: "pass" }, 1);
s = e.move(s, { type: "pass" }, 2);
s = e.move(s, { type: "ship", ship: 1, good: "sugar" }, 0);
assert.equal(s.players[0].vp, 6);
});
test("storage covers whole types plus one crate; quantities cannot be forged", () => {
let s = phase("captain");
s.players[0].goods = { ...empty(), corn: 4, sugar: 3, coffee: 2 };
s.players[0].buildings = [tile("smallWarehouse")];
s.tasks = [{ kind: "store", p: 0 }, { kind: "phaseEnd" }];
assert.throws(() =>
e.move(
s,
{ type: "store", types: ["corn", "sugar"], goods: s.players[0].goods },
0,
),
);
assert.throws(() =>
e.move(
s,
{ type: "store", types: ["corn"], goods: { ...empty(), corn: -1 } },
0,
),
);
s = e.move(
s,
{
type: "store",
types: ["corn"],
goods: { ...empty(), corn: 4, coffee: 1 },
},
0,
);
assert.deepEqual(s.players[0].goods, { ...empty(), corn: 4, coffee: 1 });
});
test("workers must fill all usable slots and cannot be duplicated", () => {
let s = phase("recruiter");
s.tasks = [{ kind: "assign", p: 0 }, { kind: "phaseEnd" }];
s.players[0].reserve = { w: 2, c: 1 };
s.players[0].buildings = [tile("smallFruit", 0)];
assert.throws(() =>
e.move(
s,
{
type: "assign",
estates: [{ w: 0, c: 0 }],
buildings: [{ w: 0, c: 0 }],
},
0,
),
);
assert.throws(() =>
e.move(
s,
{
type: "assign",
estates: [{ w: 1, c: 0 }],
buildings: [{ w: 2, c: 0 }],
},
0,
),
);
s = e.move(
s,
{ type: "assign", estates: [{ w: 1, c: 0 }], buildings: [{ w: 0, c: 1 }] },
0,
);
assert.deepEqual(s.players[0].reserve, { w: 1, c: 0 });
});
test("quarry discounts are capped by building column and stack with privilege", () => {
const s = phase("builder");
s.players[0].estates = Array.from({ length: 5 }, () => tile("quarry"));
assert.equal(e.cost(s, 0, "smallWarehouse"), 1);
assert.equal(e.cost(s, 0, "wharf"), 5);
assert.equal(e.cost(s, 0, "monument"), 5);
});
test("official errata: filling a city ends the round, not the Builder phase", () => {
let s = phase("builder");
s.players[0].coins = 30;
s.players[0].buildings = [
"smallFruit",
"smallSugar",
"largeFruit",
"largeSugar",
"tobaccoStorage",
"coffeeRoaster",
"smallMarket",
"buildersYard",
"hacienda",
"hospital",
"office",
].map((id) => tile(id, 0));
s = e.move(s, { type: "build", id: "factory" }, 0);
assert.equal(s.endReason, "city");
assert.equal(e.ended(s), false);
assert.equal(e.currentPlayer(s), 1);
while (!s.finished) s = e.moveAI(s);
assert.equal(s.round, 1);
assert.equal(s.choices, 3);
});
test("official errata: VP depletion outside Captain also finishes the round", () => {
let s = phase("builder");
s.vpSupply = 1;
s.players[0].coins = 20;
s.players[0].buildings = [tile("church")];
s.market.hospital = 2;
s = e.move(s, { type: "build", id: "hospital" }, 0);
assert.equal(s.endReason, "points");
assert.equal(s.finished, false);
while (!s.finished) s = e.moveAI(s);
assert.equal(s.round, 1);
});
test("citizens replace a worker in the register and do not cause worker-endgame", () => {
const s = e.init(3, ["citizens"]);
assert.equal(s.register.w, 2);
assert.equal(s.register.c, 1);
assert.equal(s.workerSupply, 56);
assert.equal(s.citizenSupply, 19);
});
test("hidden market only pays an actual shortfall and does not sacrifice its sole worker", () => {
const s = phase("builder");
s.players[0].coins = 0;
s.players[0].buildings = [tile("hiddenMarket")];
s.players[0].goods.corn = 1;
s.players[0].vp = 1;
const moves = e.buildOptions(s, 0).filter((m) => m.id === "smallWarehouse");
assert.ok(moves.length);
assert.ok(moves.every((m) => !m.worker));
const after = e.move(s, moves[0], 0);
assert.equal(after.players[0].coins, 0);
assert.ok(e.active(after.players[0], "hiddenMarket"));
assert.equal(after.players[0].vp, 0);
});
test("small wharf accepts mixed partial cargo; bonuses count per shipment", () => {
let s = phase("captain");
s.players[0].buildings = [tile("smallWharf"), tile("harbor")];
s.players[0].goods = { ...empty(), corn: 3, coffee: 2 };
s = e.move(
s,
{ type: "smallWharf", goods: { ...empty(), corn: 2, coffee: 1 } },
0,
);
assert.equal(s.players[0].vp, 3);
assert.equal(s.players[0].goods.corn, 1);
assert.equal(s.players[0].goods.coffee, 1);
});
test("captured role executes at round end if nobody selected it", () => {
let s = e.init(3, ["smuggler"]);
s.choices = 2;
s = e.move(s, { type: "role", id: "smuggler" }, 0);
s = e.move(s, { type: "capture", id: "builder" }, 0);
assert.equal(s.role, "builder");
assert.equal(s.owner, 0);
assert.equal(s.round, 1);
assert.equal(s.choices, 3);
});
test("smuggler cannot be reselected by its token holder", () => {
const s = e.init(3, ["smuggler"]);
s.smuggler = 0;
assert.ok(!e.legal(s).some((m) => m.id === "smuggler"));
assert.throws(() => e.move(s, { type: "role", id: "smuggler" }, 0));
});
test("public metadata does not enable HTML or change game mechanics", () => {
const s = e.init(3);
const renamed = e.setPlayerMetaData(s, 0, {
name: "<script>alert(1)</script>",
});
assert.equal(renamed.players[0].name, "<script>alert(1)</script>");
assert.deepEqual(e.scores(renamed), e.scores(s));
});
test("Bohío can move workers out of turn without consuming the active turn", () => {
const s = e.init(3);
s.players[1].buildings = [tile("bohio", 1), tile("smallFruit", 0)];
const m = { type: "bohio", kind: "w", target: "b1" };
assert.equal(e.canMoveOutOfTurn(s, m, 1), true);
const after = e.move(s, m, 1);
assert.equal(e.currentPlayer(after), 0);
assert.equal(after.players[1].buildings[0].w, 0);
assert.equal(after.players[1].buildings[1].w, 1);
assert.throws(() => e.move(s, { type: "role", id: "builder" }, 1));
});
test("School worker is optional and goes only on the newly built building", () => {
let s = phase("builder");
s.players[0].coins = 20;
s.players[0].buildings = [tile("school")];
s = e.move(s, { type: "build", id: "smallFruit" }, 0);
assert.equal(s.tasks[0].kind, "school");
assert.equal(s.players[0].buildings[1].w, 0);
const passed = e.move(s, { type: "pass" }, 0);
assert.equal(passed.players[0].buildings[1].w, 0);
const used = e.move(s, { type: "school" }, 0);
assert.equal(used.players[0].buildings[1].w, 1);
assert.equal(used.workerSupply, s.workerSupply - 1);
});
test("Poaching lets the smuggler choose surplus citizens to discard", () => {
let s = e.init(3, ["smuggler", "citizens"]);
s.tasks = [{ kind: "role", p: 0 }];
s.register = { w: 4, c: 1 };
s = e.move(s, { type: "role", id: "smuggler" }, 0);
s = e.move(s, { type: "poach" }, 0);
s = e.move(s, { type: "pass" }, 0);
assert.equal(s.tasks[0].kind, "poachDiscard");
s = e.move(s, { type: "discardWorker", kind: "c" }, 0);
assert.equal(s.register.c, 0);
s = e.move(s, { type: "discardWorker", kind: "w" }, 0);
assert.equal(s.register.w, 3);
});
test("all twelve Festival activities can be drawn and reserve their components", () => {
const seen = new Set();
for (let i = 0; i < 30; i++) {
const s = e.init(3, ["festival-cards"], {}, `fest-${i}`);
invariant(s);
for (const f of s.festivals) seen.add(f.id);
}
assert.equal(seen.size, 12);
});
test("a Festival objective never locks away the only purchasable copy of its building", () => {
for (const n of [2, 3])
for (let i = 0; i < 12; i++) {
const s = e.init(n, ["festival-cards"], {}, `marker-${i}`);
for (const f of s.festivals)
if (f.targets.building) assert.ok(s.market[f.targets.building] > 0);
}
});
test("Church and Harbor points can be declined to avoid ending the game early", () => {
let s = phase("builder");
s.players[0].coins = 20;
s.players[0].buildings = [tile("church")];
s.vpSupply = 1;
s = e.move(s, { type: "build", id: "hospital", decline: ["church"] }, 0);
assert.equal(s.endReason, null);
assert.equal(s.players[0].vp, 0);
let c = phase("captain");
c.players[0].goods.corn = 1;
c.players[0].buildings = [tile("harbor")];
c.vpSupply = 3;
c = e.move(
c,
{ type: "ship", ship: 0, good: "corn", decline: ["harbor"] },
0,
);
assert.equal(c.players[0].vp, 2);
assert.equal(c.endReason, null);
});
test("Chapel VP can be declined independently of production", () => {
let s = phase("craftsman");
s.players[0].buildings = [tile("chapel", 0, 1)];
s.players[0].estates = [tile("corn")];
s.vpSupply = 1;
s = e.move(
s,
{ type: "produce", goods: { ...empty(), corn: 1 }, decline: ["chapel"] },
0,
);
assert.equal(s.players[0].goods.corn, 1);
assert.equal(s.players[0].vp, 0);
assert.equal(s.endReason, null);
});
test("invalid bonus opt-outs cannot bypass mandatory Captain points", () => {
const s = phase("captain");
s.players[0].goods.corn = 1;
s.players[0].buildings = [tile("smallWharf")];
assert.throws(() =>
e.move(
s,
{
type: "smallWharf",
goods: { ...empty(), corn: 1 },
decline: ["captain"],
},
0,
),
);
});
test("replay restores each playable boundary and log slices omit secrets", () => {
let s = e.init(3, ["smuggler"], {}, "replay");
const states = [s];
for (let i = 0; i < 35; i++) {
s = e.moveAI(s);
states.push(s);
}
for (const i of [1, 5, 13, 36])
assert.deepEqual(e.replay(s, { to: i }), states[i - 1]);
const slice = e.logSlice(s, { player: 0, start: 5, end: 5 });
assert.equal(slice.frames.length, 1);
assert.equal(slice.frames[0].history, undefined);
assert.equal(slice.frames[0].players[1].vp, null);
});
for (const n of [2, 3, 4, 5])
for (const expansions of [
[],
["new-buildings"],
["citizens"],
["smuggler", "festival"],
["new-buildings", "citizens", "smuggler", "festival-cards"],
])
test(`${n} players / ${expansions.join("+") || "base"}: complete game, finite supplies, deterministic replay`, () => {
let s = e.init(n, expansions, {}, `full-${n}`);
invariant(s);
let moves = 0;
while (!e.ended(s) && moves++ < 1500) {
s = e.moveAI(s);
invariant(s);
}
assert.ok(e.ended(s), "Bots finish a legal game");
assert.deepEqual(e.replay(s), s);
assert.equal(e.currentPlayer(s), undefined);
assert.equal(e.rankings(s).length, n);
});

415
viewer/i18n.js Normal file
View file

@ -0,0 +1,415 @@
const labels = {
income: ["Income", "Revenus"],
draft: ["Market selection", "Choix du marché"],
end: ["Game over", "Fin de partie"],
plus: ["Increase", "Augmenter"],
minus: ["Decrease", "Réduire"],
message: ["Message", "Message"],
send: ["Send", "Envoyer"],
sending: ["Sending…", "Envoi…"],
noMessages: ["No messages yet", "Aucun message"],
messagePlaceholder: ["Message…", "Message…"],
readOnly: ["Read-only chat", "Discussion en lecture seule"],
withoutBonus: ["Without bonus", "Sans bonus"],
parkReward: ["Collect 2 VP", "Recevoir 2 PV"],
assembly: ["Assembly hall", "Salle d’assemblée"],
corn: ["Corn", "Maïs"],
fruit: ["Fruit", "Fruits"],
sugar: ["Sugar", "Sucre"],
tobacco: ["Tobacco", "Tabac"],
coffee: ["Coffee", "Café"],
quarry: ["Quarry", "Carrière"],
forest: ["Forest", "Forêt"],
planter: ["Planter", "Planteur"],
recruiter: ["Recruiter", "Recruteur"],
builder: ["Builder", "Bâtisseur"],
craftsman: ["Craftsman", "Artisan"],
trader: ["Trader", "Marchand"],
captain: ["Captain", "Capitaine"],
adventurer: ["Adventurer", "Aventurier"],
adventurer2: ["Adventurer", "Aventurier"],
smuggler: ["Smuggler", "Contrebandier"],
smallFruit: ["Small fruit depot", "Petit dépôt de fruits"],
smallSugar: ["Small sugar mill", "Petite sucrerie"],
largeFruit: ["Large fruit depot", "Grand dépôt de fruits"],
largeSugar: ["Large sugar mill", "Grande sucrerie"],
tobaccoStorage: ["Tobacco storage", "Entrepôt de tabac"],
coffeeRoaster: ["Coffee roaster", "Brûlerie de café"],
smallMarket: ["Small market", "Petit marché"],
buildersYard: ["Builder’s yard", "Chantier"],
hacienda: ["Hacienda", "Hacienda"],
smallWarehouse: ["Small warehouse", "Petit entrepôt"],
hospital: ["Hospital", "Hôpital"],
office: ["Office", "Comptoir"],
largeMarket: ["Large market", "Grand marché"],
largeWarehouse: ["Large warehouse", "Grand entrepôt"],
factory: ["Factory", "Manufacture"],
school: ["School", "École"],
harbor: ["Harbor", "Port"],
wharf: ["Wharf", "Quai"],
fireStation: ["Fire station", "Caserne de pompiers"],
residence: ["Residence", "Résidence"],
fortress: ["Fortress", "Forteresse"],
customsHouse: ["Customs house", "Douane"],
cityHall: ["City hall", "Hôtel de ville"],
canal: ["Canal", "Canal"],
lumberyard: ["Lumberyard", "Scierie"],
hiddenMarket: ["Hidden market", "Marché clandestin"],
storehouse: ["Storehouse", "Réserve"],
bohio: ["Bohío", "Bohío"],
merchantOutpost: ["Merchant outpost", "Relais commercial"],
church: ["Church", "Église"],
smallWharf: ["Small wharf", "Petit quai"],
lighthouse: ["Lighthouse", "Phare"],
distillery: ["Distillery", "Distillerie"],
publishingHouse: ["Publishing house", "Maison d’édition"],
assemblyHall: ["Assembly hall", "Salle d’assemblée"],
monument: ["Monument", "Monument"],
cathedral: ["Cathedral", "Cathédrale"],
zoningOffice: ["Zoning office", "Bureau d’urbanisme"],
chapel: ["Chapel", "Chapelle"],
parkAuthority: ["Park authority", "Service des parcs"],
notary: ["Notary", "Notaire"],
pensionOffice: ["Pension office", "Caisse de retraite"],
villa: ["Villa", "Villa"],
tailorShop: ["Large tailor shop", "Grand atelier de tailleur"],
townSquare: ["Town square", "Place de la ville"],
city: ["City", "Ville"],
countryside: ["Countryside", "Campagne"],
market: ["Buildings", "Bâtiments"],
harborTitle: ["Harbor", "Port"],
tradingHouse: ["Trading house", "Marché de vente"],
workers: ["Workers", "Ouvriers"],
citizens: ["Citizens", "Citoyens"],
reserve: ["Reserve", "Réserve"],
vp: ["Victory points", "Points de victoire"],
coins: ["Coins", "Pièces"],
round: ["Round", "Manche"],
governor: ["Governor", "Gouverneur"],
you: ["You", "Vous"],
rules: ["Rules", "Règles"],
journal: ["Journal", "Journal"],
chat: ["Chat", "Discussion"],
close: ["Close", "Fermer"],
cancel: ["Cancel", "Annuler"],
confirm: ["Confirm", "Confirmer"],
pass: ["Pass", "Passer"],
finish: ["Finish", "Terminer"],
waiting: ["Waiting for", "Au tour de"],
yourTurn: ["Your turn", "À vous"],
chooseRole: ["Choose a role", "Choisissez un rôle"],
chooseDraft: [
"Choose a building for the shared market",
"Choisissez un bâtiment pour le marché commun",
],
choosePlant: ["Choose an estate", "Choisissez un domaine"],
chooseBuild: ["Choose a building", "Choisissez un bâtiment"],
chooseRecruit: ["Choose a worker", "Choisissez un ouvrier"],
assign: ["Assign workers", "Affectez les ouvriers"],
autoAssign: ["Suggest allocation", "Proposer une répartition"],
erase: ["Unassign", "Retirer"],
produce: ["Produce goods", "Produire"],
produceBonus: ["Choose your extra crate", "Choisissez votre caisse bonus"],
trade: ["Sell one crate", "Vendre une caisse"],
ship: ["Load a ship", "Charger un bateau"],
store: ["Store your remaining goods", "Conservez vos marchandises"],
keep: ["Keep", "Garder"],
types: ["Whole types", "Types complets"],
wharfShip: ["Private ship", "Bateau privé"],
smallWharfShip: ["Mixed cargo", "Chargement mixte"],
claim: ["Collect", "Recevoir"],
haciendaHint: [
"Draw an extra estate before choosing.",
"Piochez un domaine avant de choisir.",
],
forestHint: [
"Keep this estate or make it a forest.",
"Gardez ce domaine ou transformez-le en forêt.",
],
hospitalHint: [
"Place the Hospital worker.",
"Placez l’ouvrier de l’hôpital.",
],
bonusAssign: ["Place your bonus workers", "Placez vos ouvriers bonus"],
recruitBonus: ["Recruit your extra worker", "Recrutez votre ouvrier bonus"],
villaHint: [
"Receive a citizen, or a worker if none remain.",
"Recevez un citoyen, ou un ouvrier s’il n’en reste plus.",
],
park: ["Remove an estate", "Retirer un domaine"],
zoneBuy: ["Buy a random estate · 1 coin", "Domaine aléatoire · 1 pièce"],
zoneSell: ["Return an estate · +1 coin", "Rendre un domaine · +1 pièce"],
pension: [
"Exchange different goods for VP",
"Échangez des marchandises différentes contre des PV",
],
raid: ["Raid a ship", "Piller un bateau"],
plunder: ["Plunder the trading house", "Piller le marché"],
poach: ["Poach workers", "Débaucher des ouvriers"],
capture: ["Capture a role", "Capturer un rôle"],
bohioMove: ["Move a Bohío worker", "Déplacer un ouvrier du Bohío"],
outpost: ["Outpost", "Relais"],
finalScore: ["Final scores", "Scores finaux"],
tie: ["Coins + crates (tiebreak)", "Pièces + caisses (départage)"],
tokens: ["VP tokens", "Jetons PV"],
bonuses: ["Bonifications", "Bonus"],
finished: ["Game over", "Partie terminée"],
abilities: ["Building abilities", "Effets des bâtiments"],
occupied: ["Occupied", "Occupé"],
empty: ["Empty", "Libre"],
workerTool: [
"Tap a slot to assign the selected worker. Tap an occupied slot to remove it.",
"Touchez une case pour y affecter l’ouvrier choisi. Touchez une case occupée pour le retirer.",
],
noWorkers: [
"All available workers assigned",
"Tous les ouvriers sont affectés",
],
unassigned: ["Unassigned", "À affecter"],
storageHint: [
"Keep one crate, plus the storage provided by occupied buildings.",
"Gardez une caisse, plus le stockage de vos bâtiments occupés.",
],
full: ["Full", "Plein"],
dispatch: ["Dispatched", "Expédié"],
festival: ["Festival", "Festival"],
objective: ["Objective", "Objectif"],
reward: ["Reward", "Récompense"],
claimed: ["Completed by", "Remporté par"],
weightOff: ["Crop weight-off", "Concours des récoltes"],
cocktail: ["Carnival cocktail", "Cocktail du carnaval"],
closingShops: ["Closing time", "Dernière vente"],
connoisseur: ["Connoisseur prize", "Prix du connaisseur"],
farming: ["Farming festival", "Fête agricole"],
delivery: ["Festival delivery", "Livraison de fête"],
twins: ["Twin farmers", "Domaines jumeaux"],
baskets: ["Two baskets", "Deux paniers"],
grandSendoff: ["Grand send-off", "Grand départ"],
pioneer: ["Pioneer’s tribute", "Hommage aux pionniers"],
patron: ["Town patron", "Mécène de la ville"],
traditionalSendoff: ["Traditional send-off", "Départ traditionnel"],
newGame: ["New game", "Nouvelle partie"],
local: ["Local table", "Table locale"],
undo: ["Undo", "Annuler le coup"],
opponents: ["Play opponents", "Jouer les adversaires"],
error: ["Unable to play this move", "Ce coup n’a pas pu être joué"],
inspect: ["Details", "Détails"],
schoolWorker: ["Include the School worker", "Placer l’ouvrier de l’école"],
ruleEnd: [
"Finish the current round when a city fills, the VP supply runs out, or the work register cannot be refilled. Worker shortage does not end a Citizens game.",
"Terminez la manche lorsqu’une ville est pleine, que les PV sont épuisés ou que le registre ne peut plus être rempli. Avec les Citoyens, le manque d’ouvriers ne termine pas la partie.",
],
ruleFlow: [
"The Governor chooses first. Pick a role: everyone performs its action, starting with you, and you receive its privilege. Each player chooses once per round (three times with two players). Unchosen roles gain a coin; the Governor moves clockwise.",
"Le Gouverneur choisit en premier. Choisissez un rôle : chacun en joue l’action en commençant par vous, et vous recevez son privilège. Chacun choisit un rôle par manche (trois à deux joueurs). Les rôles non choisis gagnent une pièce ; le Gouverneur passe au suivant.",
],
ruleShipping: [
"You must load when a public ship can accept your goods. Choose one type and load as much as possible. A type cannot occupy two public ships. Only full ships leave at the end of the phase.",
"Vous devez charger si un bateau public accepte vos marchandises. Choisissez un type et chargez-en le maximum. Un type ne peut occuper deux bateaux publics. Seuls les bateaux pleins partent en fin de phase.",
],
ruleWorkers: [
"Workers activate estates and building effects. Non-corn goods require a worker on an estate and one in the matching production building. Reassign everyone during the Recruiter phase; citizens also score 1 VP each.",
"Les ouvriers activent les domaines et les bâtiments. Hors maïs, chaque caisse exige un ouvrier sur un domaine et un dans le bâtiment de production correspondant. Réaffectez-les au Recruteur ; chaque citoyen rapporte aussi 1 PV.",
],
discardWorker: [
"Discard surplus workers",
"Retirez les ouvriers excédentaires",
],
selectQty: ["Choose quantities", "Choisissez les quantités"],
cost: ["Cost", "Coût"],
discount: ["After discounts", "Après réductions"],
available: ["Available", "Disponible"],
selected: ["Selected", "Choisi"],
};
const effects = {
smallMarket: ["+1 coin when selling.", "+1 pièce par vente."],
buildersYard: [
"May take a quarry during Planter.",
"Permet de prendre une carrière au Planteur.",
],
hacienda: [
"Optional extra estate from the bag before choosing.",
"Un domaine pioché en plus, avant votre choix.",
],
smallWarehouse: [
"Store every crate of one type, plus the usual crate.",
"Conservez un type complet, plus la caisse habituelle.",
],
hospital: [
"One worker on an estate or quarry gained this phase.",
"Un ouvrier sur un domaine ou une carrière acquis cette phase.",
],
office: [
"May sell a type already in the trading house.",
"Permet de vendre un type déjà au marché.",
],
largeMarket: ["+2 coins when selling.", "+2 pièces par vente."],
largeWarehouse: [
"Store every crate of two types, plus the usual crate.",
"Conservez deux types complets, plus la caisse habituelle.",
],
factory: [
"Produce 2/3/4/5 types: +1/2/3/5 coins.",
"Produisez 2/3/4/5 types : +1/2/3/5 pièces.",
],
school: [
"A newly built building receives one worker.",
"Un ouvrier dans votre nouveau bâtiment.",
],
harbor: ["+1 VP per shipment.", "+1 PV par chargement."],
wharf: [
"Once per Captain: ship all crates of one type privately.",
"Une fois au Capitaine : expédiez un type complet sur votre bateau privé.",
],
fireStation: [
"Score 1 VP per small production building, 2 per large.",
"1 PV par petit bâtiment de production, 2 par grand.",
],
residence: [
"Score 4/5/6/7 VP for 1–9/10/11/12 countryside tiles.",
"4/5/6/7 PV pour 1–9/10/11/12 tuiles de campagne.",
],
fortress: [
"Score 1 VP per three workers and citizens.",
"1 PV par groupe de trois ouvriers ou citoyens.",
],
customsHouse: [
"Score 1 VP per four VP tokens earned.",
"1 PV par groupe de quatre PV gagnés.",
],
cityHall: [
"Score 1 VP per commercial building, including this one.",
"1 PV par bâtiment commercial, celui-ci compris.",
],
canal: [
"Large fruit and sugar buildings can produce one extra crate each.",
"Les grands bâtiments de fruits et de sucre produisent chacun une caisse en plus.",
],
lumberyard: [
"May turn newly gained estates into forests. Two forests reduce building costs by 1.",
"Transformez de nouveaux domaines en forêts. Deux forêts réduisent de 1 le coût des bâtiments.",
],
hiddenMarket: [
"If short of cash, return at most one worker, one crate and one VP; each pays 1 coin.",
"Si l’argent manque, rendez au plus un ouvrier, une caisse et un PV ; chacun paie une pièce.",
],
storehouse: [
"Keep three additional crates of any types.",
"Gardez trois caisses supplémentaires, de types libres.",
],
bohio: [
"Move its workers into empty slots to activate them.",
"Déplacez ses ouvriers vers des cases libres pour les activer.",
],
merchantOutpost: [
"Sell directly to the supply, without market bonuses.",
"Vendez directement à la réserve, sans bonus des marchés.",
],
church: [
"Build a 2/3 VP building: +1 VP. Expanded building: +2 VP.",
"Bâtiment de 2/3 PV construit : +1 PV. Grand bâtiment : +2 PV.",
],
smallWharf: [
"Once per Captain: ship any mixed cargo, for 1 VP per two crates.",
"Une fois au Capitaine : cargaison mixte, 1 PV par deux caisses.",
],
lighthouse: [
"+1 coin per shipment; +1 coin if you are Captain.",
"+1 pièce par chargement ; +1 pièce si vous êtes Capitaine.",
],
distillery: [
"Earn coins equal to your largest non-corn production, minus one.",
"Votre plus grande production hors maïs rapporte autant de pièces, moins une.",
],
publishingHouse: [
"Double the chosen role’s privilege. Planter gets a second pick after everyone.",
"Double le privilège choisi. Au Planteur, choisissez une seconde tuile après les autres.",
],
assemblyHall: [
"At Captain start: +1 VP per pair of crates of the same type.",
"Au début du Capitaine : +1 PV par paire de caisses du même type.",
],
monument: [
"Worth 8 VP without needing a worker.",
"Vaut 8 PV, même sans ouvrier.",
],
cathedral: [
"Sets of three matching countryside tiles score 1/3/6/10 VP for 1/2/3/4 sets.",
"1/2/3/4 groupes de trois tuiles identiques : 1/3/6/10 PV.",
],
zoningOffice: [
"Trader: worker buys a random estate for 1 coin; citizen discards an estate for 1 coin.",
"Marchand : l’ouvrier achète un domaine pioché pour 1 pièce ; le citoyen vend un domaine pour 1 pièce.",
],
chapel: [
"Craftsman: worker earns 1 coin; citizen earns 1 VP.",
"Artisan : l’ouvrier gagne 1 pièce ; le citoyen gagne 1 PV.",
],
parkAuthority: [
"Planter: worker may discard an estate/forest; citizen earns 2 VP with strictly fewest countryside tiles.",
"Planteur : l’ouvrier peut retirer un domaine/forêt ; le citoyen gagne 2 PV si vous avez strictement le moins de tuiles de campagne.",
],
notary: [
"Worker: regular buildings cost 1 less. Citizen: expanded buildings cost 2 less.",
"Ouvrier : −1 pièce sur les bâtiments simples. Citoyen : −2 sur les grands bâtiments.",
],
pensionOffice: [
"Before shipping, exchange distinct goods for 1 VP each, up to your citizen count.",
"Avant de charger, échangez des types différents contre 1 PV chacun, au plus autant que vos citoyens.",
],
villa: [
"Recruiter: receive one citizen, or one worker if citizens have run out.",
"Recruteur : recevez un citoyen, ou un ouvrier si les citoyens sont épuisés.",
],
tailorShop: [
"Craftsman: gain 1 coin per citizen. Counts as a large production building.",
"Artisan : 1 pièce par citoyen. Compte comme grand bâtiment de production.",
],
townSquare: [
"Each citizen scores one extra VP.",
"Chaque citoyen rapporte un PV supplémentaire.",
],
};
const roleHelp = {
planter: [
"Each player takes an estate. You may choose a quarry instead.",
"Chacun prend un domaine. Vous pouvez choisir une carrière à la place.",
],
recruiter: [
"Share the workers on the register, then reassign everyone. You may recruit one extra worker from the supply.",
"Répartissez les ouvriers du registre, puis réaffectez-les tous. Vous pouvez recruter un ouvrier supplémentaire dans la réserve.",
],
builder: [
"Each player may buy one building. Yours costs one coin less; active quarries also give discounts.",
"Chacun peut acheter un bâtiment. Le vôtre coûte une pièce de moins ; les carrières occupées donnent aussi des réductions.",
],
craftsman: [
"Everyone produces with occupied estates and production buildings. You may take one extra crate of a type you produced, after everyone.",
"Chacun produit avec ses domaines et bâtiments occupés. Après les autres, prenez une caisse supplémentaire d’un type que vous avez produit.",
],
trader: [
"Each player may sell one crate. The trading house accepts four crates, all of different types. Your sale earns one extra coin.",
"Chacun peut vendre une caisse. Le marché accepte quatre caisses de types différents. Votre vente rapporte une pièce supplémentaire.",
],
captain: [
"Take turns shipping goods for VP until nobody can load. Your first shipment earns one extra VP. Store goods, then empty full ships.",
"Expédiez chacun votre tour jusqu’à ne plus pouvoir charger. Votre premier chargement rapporte un PV en plus. Stockez vos marchandises, puis videz les bateaux pleins.",
],
adventurer: [
"Only you act: gain one coin, plus any coins on this role.",
"Vous seul agissez : gagnez une pièce, en plus de celles présentes sur le rôle.",
],
smuggler: [
"Only you act: raid a ship, plunder the trading house, poach surplus workers, or capture a role. You cannot choose Smuggler again until someone else does.",
"Vous seul agissez : pillez un bateau ou le marché, débauchez des ouvriers ou capturez un rôle. Vous ne pourrez reprendre ce rôle qu’après un autre joueur.",
],
};
export function translator(locale = "en") {
const fr = locale.toLowerCase().startsWith("fr");
const t = (key) => labels[key]?.[fr ? 1 : 0] ?? key;
t.effect = (id) => effects[id]?.[fr ? 1 : 0] ?? "";
t.role = (id) =>
roleHelp[id === "adventurer2" ? "adventurer" : id]?.[fr ? 1 : 0] ?? "";
t.fr = fr;
return t;
}

62
viewer/icons.js Normal file
View file

@ -0,0 +1,62 @@
const paths = {
corn: '<path fill="#e9b74b" d="M12 5c-4 0-5 4-5 8s2 6 5 6 5-2 5-6-1-8-5-8Z"/><path d="m6 12 6 9 6-9M10 8h4m-4 4h4m-4 4h4"/>',
fruit:
'<path fill="#79a965" d="M12 7C3 2 1 18 10 21c2 1 2-1 4 0 9-3 7-19-2-14Z"/><path d="M12 7V3m0 2c4 0 5-2 5-3"/>',
sugar:
'<path fill="#f2ede0" d="m5 7 7-4 7 4v11l-7 4-7-4Z"/><path d="m5 7 7 4 7-4m-7 4v11"/>',
tobacco:
'<path fill="#b78665" d="M4 19C2 9 10 3 21 3c0 12-7 18-17 16Z"/><path d="M4 19 18 6m-8 6V8m3 1h4"/>',
coffee:
'<path fill="#806959" d="M17 3c6 4 4 12-2 17S3 21 3 15 10-2 17 3Z"/><path stroke="#f8ead4" d="M17 4c-1 7-8 6-10 15"/>',
quarry:
'<path fill="#abbac0" d="m2 18 5-9 6 1 3-6 6 14-5 3H6Z"/><path d="m7 9 4 12m2-11 4 11"/>',
forest:
'<path fill="#64957c" d="m12 2-8 11h4l-5 6h18l-5-6h4Z"/><path d="M12 19v4"/>',
worker:
'<circle cx="12" cy="5" r="3" fill="#dec594"/><path fill="#dec594" d="M8 10h8l4 11H4Z"/>',
citizen:
'<circle cx="12" cy="7" r="3" fill="#d19c48"/><path fill="#d19c48" d="M7 12h10l3 10H4ZM7 2h10v3H7Z"/>',
coin: '<circle fill="#e7be63" cx="12" cy="12" r="10"/><path d="M12 6v12m3-10c-6-4-8 4-3 4s3 8-3 4"/>',
vp: '<path fill="#60a0bb" d="m12 2 9 5v10l-9 5-9-5V7Z"/><path stroke="#fff" d="m6 12 4 4 8-8"/>',
building:
'<path fill="#d6b994" d="M4 10h16v12H4Z"/><path fill="#b16b4e" d="m2 10 10-8 10 8Z"/><path d="M10 22v-7h4v7M7 13v3m10-3v3"/>',
planter:
'<path d="M12 22V10"/><path fill="#72a47b" d="M12 12C3 12 2 7 3 4c6 0 9 3 9 8Zm0-2c7 0 10-4 9-8-6 0-9 3-9 8Z"/>',
recruiter:
'<circle cx="8" cy="6" r="3" fill="#d6b994"/><path fill="#d6b994" d="M4 11h8l3 10H1Z"/><path d="M19 7v10m-5-5h10"/>',
builder:
'<path fill="#b87955" d="m4 18 10-11 3 3L7 21Z"/><path fill="#abbac0" d="m10 5 4-4 9 8-5 4Z"/>',
craftsman:
'<path fill="#d6b994" d="M3 7h18v14H3Z"/><path d="M3 12h18M8 7v14m8-14v14m-9-17h10"/>',
trader:
'<path fill="#d6b994" d="M5 9h14v13H5Z"/><path fill="#c27952" d="M2 3h20v6H2Z"/><path d="M8 3v6m8-6v6M10 22v-8h4v8"/>',
captain:
'<path fill="#bb8d60" d="m2 16 4 6h13l3-6Z"/><path fill="#f3e6c9" d="M12 2v13H3Zm2 2v11h7Z"/>',
adventurer:
'<circle fill="#e7be63" cx="12" cy="13" r="8"/><path d="m12 9 1 3 3 1-3 1-1 3-1-3-3-1 3-1ZM5 3h14"/>',
smuggler:
'<path fill="#738896" d="M3 7c3-7 15-7 18 0l-4 12H7Z"/><path d="m7 10 3 2m7-2-3 2m-4 5h4"/>',
ship: '<path fill="#bb8d60" d="m2 16 4 6h13l3-6Z"/><path fill="#f3e6c9" d="M12 2v13H3Zm2 2v11h7Z"/>',
governor:
'<path fill="#d8ba65" d="m2 6 5 4 5-8 5 8 5-4-3 13H5Z"/><path d="M5 22h14"/>',
rules:
'<path d="M12 5C8 2 4 2 1 4v17c3-2 7-2 11 1 4-3 8-3 11-1V4c-3-2-7-2-11 1Zm0 0v17"/>',
journal: '<path d="M5 2h16v20H5ZM1 6h7M1 12h7M1 18h7m2-10h8m-8 5h8m-8 5h5"/>',
chat: '<path d="M3 3h18v14H9l-6 5Zm4 5h10M7 12h7"/>',
close: '<path d="m5 5 14 14M19 5 5 19"/>',
check: '<path d="m3 12 6 6L21 4"/>',
pass: '<path d="m7 5 9 7-9 7m12-14v14"/>',
plus: '<path d="M12 3v18M3 12h18"/>',
minus: '<path d="M3 12h18"/>',
undo: '<path d="M4 9h10a7 7 0 1 1 0 14M4 9l6-6M4 9l6 6"/>',
eye: '<path d="M1 12S5 4 12 4s11 8 11 8-4 8-11 8S1 12 1 12Z"/><circle cx="12" cy="12" r="4"/>',
festival:
'<path fill="#d8ba65" d="m12 2 3 6 7 1-5 5 1 8-6-4-6 4 1-8-5-5 7-1Z"/>',
reset: '<path d="M3 10a9 9 0 1 1 2 9M3 3v7h7"/>',
arrow: '<path d="M2 12h19m-7-7 7 7-7 7"/>',
erase: '<path d="m4 14 11-11 7 7-11 11H8Zm3-3 7 7m-3 3h12"/>',
dark: '<path fill="#d8ba65" d="M18 2C6-1-1 14 8 21c5 4 13 1 15-5C12 18 7 9 18 2Z"/>',
};
export function icon(id, size = 24) {
return `<svg class="icon" width="${size}" height="${size}" viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">${paths[id] ?? paths.building}</svg>`;
}

92
viewer/index.js Normal file
View file

@ -0,0 +1,92 @@
import { registerViewer } from "@boardgamers/protocol/viewer";
import { ChatController } from "@boardgamers/protocol/chat";
import { mountGame } from "./ui.js";
registerViewer("puertorico", (ctx) => {
const chat = new ChatController();
let live,
replaying = false,
position = 1,
pending,
timer;
const ui = mountGame(ctx.target, {
chat,
onOpenPlayer: ctx.openPlayer,
onMove: (m) =>
new Promise((resolve, reject) => {
pending = { resolve, reject };
timer = setTimeout(() => {
pending = null;
ctx.fetchState();
reject(Error("No confirmation received. Please try again."));
}, 15000);
ctx.move(m);
}),
});
const info = () => {
if (live)
ctx.setReplayInfo({
start: 1,
current: position,
end: live.historyLength,
});
};
const seek = (to) => {
if (!live) return;
position = Math.max(1, Math.min(live.historyLength, to));
ctx.fetchLog({ start: position - 1, end: position - 1 });
info();
};
return {
chat,
onState(s) {
live = s;
if (!replaying) {
position = s.historyLength;
ui.render(s);
}
if (pending) {
clearTimeout(timer);
pending.resolve();
pending = null;
}
},
onPlayer(p) {
ui.setPlayer(p.index);
},
onPreferences: (p) => ui.setPreferences(p),
onTheme: (p) => ui.setPreferences(p),
onError(err) {
clearTimeout(timer);
pending?.reject(Error(String(err)));
pending = null;
},
onMoveResult(result) {
if (result.ok || !pending) return;
clearTimeout(timer);
pending.reject(Error(result.error || "Move rejected"));
pending = null;
ctx.fetchState();
},
onReplayStart() {
replaying = true;
ui.setEnabled(false);
info();
},
onReplayTo: seek,
onReplayEnd() {
replaying = false;
ui.setEnabled(true);
if (live) ui.render(live);
},
onLog(log) {
if (replaying && log.start === position - 1 && log.data?.frames?.[0])
ui.render(log.data.frames[0]);
else if (!replaying) ctx.fetchState();
},
destroy() {
clearTimeout(timer);
pending?.reject(Error("Viewer closed"));
ui.destroy();
},
};
});

96
viewer/preview.js Normal file
View file

@ -0,0 +1,96 @@
import * as engine from "../engine/index.js";
import { RELEASE } from "../release-config.js";
import { mountGame } from "./ui.js";
const KEY = "puerto-rico-preview-v1";
const params = new URLSearchParams(location.search);
let state,
undo = [],
generation = 0,
dark = matchMedia("(prefers-color-scheme: dark)").matches;
function newGame() {
let s = engine.init(
3,
RELEASE.expansions,
RELEASE.options,
`preview-${Date.now()}`,
);
s.players.forEach((p, i) => (p.name = ["Vous", "Isabel", "Rafael"][i]));
while (s.tasks[0]?.kind === "draft") s = engine.moveAI(s);
return s;
}
try {
state = JSON.parse(localStorage.getItem(KEY));
if (state?.version !== 1 || !state.config) state = null;
} catch {}
state ??= newGame();
const ui = mountGame(document.getElementById("game"), {
async onMove(move) {
undo.push(structuredClone(state));
state = engine.move(state, move, 0);
display();
setTimeout(opponents, 180);
},
localControls(command) {
if (command === "undo" && undo.length) {
generation++;
state = undo.pop();
display();
}
if (command === "opponents") opponents();
if (command === "reset") {
generation++;
undo = [];
state = newGame();
display();
}
if (command === "dark") {
dark = !dark;
ui.setPreferences({
locale: params.get("locale") ?? navigator.language,
dark,
});
}
},
});
ui.setPreferences({ locale: params.get("locale") ?? navigator.language, dark });
ui.setPlayer(0);
function display() {
localStorage.setItem(KEY, JSON.stringify(state));
ui.render(engine.stripSecret(state, 0));
}
let running = false;
async function opponents() {
if (running) return;
running = true;
const token = generation;
try {
while (
!engine.ended(state) &&
engine.currentPlayer(state) !== 0 &&
generation === token
) {
state = engine.moveAI(state);
display();
await new Promise((r) => setTimeout(r, 220));
}
} finally {
running = false;
}
}
display();
opponents();
// Only the standalone local sandbox exposes these hooks, never the BGS bundle.
window.prPreview = {
getState: () => structuredClone(state),
setState(s) {
generation++;
state = structuredClone(s);
display();
},
playAI() {
state = engine.moveAI(state);
display();
},
engine,
ui,
};

1078
viewer/style.css Normal file

File diff suppressed because it is too large Load diff

665
viewer/ui.js Normal file
View file

@ -0,0 +1,665 @@
import morphdom from "morphdom";
import { mountChat } from "@boardgamers/protocol/chat/dom";
import { BUILDINGS as B, GOODS } from "../engine/catalog.js";
import {
autoAssignment,
autoStorage,
cost,
production,
citySize,
} from "../engine/index.js";
import { translator } from "./i18n.js";
import { icon } from "./icons.js";
import css from "./style.css";
const esc = (x) =>
String(x ?? "").replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
c
],
);
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
const encode = (m) => esc(encodeURIComponent(JSON.stringify(m)));
const metric = (id, n) =>
`<span class="metric">${icon(id, 20)}<b>${esc(n)}</b></span>`;
const goodsRow = (goods) =>
GOODS.filter((g) => goods[g])
.map((g) => metric(g, goods[g]))
.join("");
const spriteFor = (id) =>
B[id]?.good && B[id].good !== "tailor" ? B[id].good : "building";
export function mountGame(
target,
{ onMove, chat, onOpenPlayer, localControls } = {},
) {
const shell = document.createElement("div");
shell.className = "pr-game";
shell.innerHTML = `<style>${css}</style><div class="pr-content"></div><dialog class="pr-modal"><header><h2></h2><button type="button" class="icon-button" data-close aria-label="Close">${icon("close")}</button></header><div class="modal-body"></div></dialog><dialog class="pr-chat"><header><h2>Chat</h2><button type="button" class="icon-button" data-close aria-label="Close">${icon("close")}</button></header><div class="chat-mount"></div></dialog><p class="pr-error" role="alert" hidden></p>`;
target.append(shell);
const content = shell.querySelector(".pr-content"),
modal = shell.querySelector(".pr-modal"),
chatDialog = shell.querySelector(".pr-chat"),
body = modal.querySelector(".modal-body"),
error = shell.querySelector(".pr-error");
let state,
seat = 0,
view = 0,
t = translator("en"),
preferences = {},
enabled = true,
pending = false,
draft = null,
draftKey = "",
tool = "w",
lastFocus,
modalMode = "",
scrollLog = 0;
let chatView;
function configureChat() {
if (!chat) return;
chatView?.destroy();
chatView = mountChat(shell.querySelector(".chat-mount"), {
chat,
openPlayer: onOpenPlayer,
styles: true,
labels: {
title: t("chat"),
message: t("message"),
placeholder: t("messagePlaceholder"),
send: t("send"),
sending: t("sending"),
empty: t("noMessages"),
edited: t.fr ? "modifié" : "edited",
game: t.fr ? "Jeu" : "Game",
suggestions: t.fr ? "Joueurs" : "Players",
unread: (n) => `${n}`,
date: (d) => d.toLocaleDateString(t.fr ? "fr" : "en"),
status: (s) => s.reason || (s.canSend ? "" : t("readOnly")),
},
});
const chatBody = document.createElement("div");
chatBody.className = "chat-body";
for (const child of [...chatView.element.children])
if (!child.matches("summary,style")) chatBody.append(child);
chatView.element.append(chatBody);
chatDialog.querySelector("h2").textContent = t("chat");
}
configureChat();
const allowed = () => enabled && !pending && seat === state?.tasks[0]?.p;
const moveButton = (m, label, pictogram, classes = "") =>
`<button type="button" class="move ${classes}" data-move="${encode(m)}" ${allowed() || (enabled && !pending && m.type === "bohio") ? "" : "disabled"}>${pictogram ? icon(pictogram, 26) : ""}<span>${label}${m.decline?.length ? `<small>${t("withoutBonus")} · ${m.decline.map((id) => t(id)).join(", ")}</small>` : ""}</span></button>`;
function show(title, html, mode = "") {
lastFocus = document.activeElement;
modalMode = mode;
modal.querySelector("h2").textContent = title;
body.innerHTML = html;
if (!modal.open) modal.showModal();
modal.querySelector("[data-close]").focus();
}
function hide(d) {
d.close();
if (d === chatDialog) chat?.setOpen(false);
lastFocus?.focus?.();
}
function draftInit() {
const task = state.tasks[0],
key = `${state.historyLength}:${task?.kind}:${task?.p}`;
if (key === draftKey) return;
draftKey = key;
draft = null;
if (enabled && seat === task?.p && task?.kind === "assign")
draft = autoAssignment(state, seat);
if (enabled && seat === task?.p && task?.kind === "store")
draft = autoStorage(state, seat);
}
const currentName = () => state.players[state.tasks[0]?.p]?.name ?? "";
function title() {
if (state.finished) return t("finished");
if (!allowed()) return `${t("waiting")} ${esc(currentName())}`;
const task = state.tasks[0];
return t(
{
role: "chooseRole",
draft: "chooseDraft",
plant: "choosePlant",
build: "chooseBuild",
recruit: "chooseRecruit",
assign: "assign",
produce: "produce",
produceBonus: "produceBonus",
trade: "trade",
ship: "ship",
store: "store",
hacienda: "haciendaHint",
forest: "forestHint",
hospital: "hospitalHint",
school: "schoolWorker",
bonusAssign: "bonusAssign",
recruitBonus: "recruitBonus",
villa: "villaHint",
park: "park",
pension: "pension",
smuggle: "smuggler",
poach: "poach",
poachDiscard: "discardWorker",
assembly: "assemblyHall",
}[task.kind] ?? task.kind,
);
}
function moveLabel(m) {
switch (m.type) {
case "plant":
return `${t(m.id)}${m.forest ? ` → ${t("forest")}` : ""}`;
case "forest":
return t(m.forest ? "forest" : state.tasks[0].id);
case "hacienda":
case "recruitBonus":
case "villa":
case "school":
return t("claim");
case "discardWorker":
return t(m.kind === "c" ? "citizens" : "workers");
case "recruit":
return t(m.kind === "c" ? "citizens" : "workers");
case "produce":
return goodsRow(m.goods) || t("pass");
case "produceBonus":
return t(m.good);
case "trade":
return `${t(m.good)} ${metric("coin", GOODS.indexOf(m.good) + (seat === state.owner ? (has("publishingHouse") ? 2 : 1) : 0) + (m.outpost ? 0 : (has("smallMarket") ? 1 : 0) + (has("largeMarket") ? 2 : 0)))}${m.outpost ? ` · ${t("outpost")}` : ""}`;
case "ship":
return `${t(m.good)} ${m.ship === "wharf" ? t("wharfShip") : `→ ${state.ships[m.ship].capacity}`} <b>×${m.ship === "wharf" ? state.players[seat].goods[m.good] : Math.min(state.players[seat].goods[m.good], state.ships[m.ship].capacity - state.ships[m.ship].amount)}</b>`;
case "smallWharf":
return t("smallWharfShip");
case "hospital":
case "bonusAssign":
case "poachWorker":
case "bohio":
return targetLabel(m.target);
case "pension":
return `${t(m.good)} → ${metric("vp", 1)}`;
case "park":
case "zoneSell":
return `${t(m.type === "park" ? "park" : "zoneSell")} · ${t(state.players[seat].estates[m.estate].id)}`;
case "raid":
return `${t("raid")} · ${state.ships[m.ship].capacity} ${metric(state.ships[m.ship].good, m.amount)}`;
case "capture":
return `${t("capture")} · ${t(m.id)}`;
default:
return t(m.type);
}
}
function targetLabel(key) {
if (key === "reserve") return t("reserve");
const collection = key[0] === "e" ? "estates" : "buildings";
return t(state.players[seat][collection][Number(key.slice(1))]?.id);
}
function has(id) {
return state.players[seat]?.buildings.some(
(b) => b.id === id && b.w + b.c > 0,
);
}
function actionPanel() {
if (!allowed()) return "";
const task = state.tasks[0],
moves = state.legal.filter(
(m) => m.type !== "bohio" && (m.type !== "pass" || m.decline?.length),
);
if (task.kind === "assign")
return `<div class="assignment-tools" role="group" aria-label="${esc(t("workers"))}">${["w", "c", "erase"].map((k) => `<button data-tool="${k}" class="${tool === k ? "selected" : ""}" aria-pressed="${tool === k}">${icon(k === "w" ? "worker" : k === "c" ? "citizen" : "erase")}${k === "erase" ? "" : remaining()[k]}</button>`).join("")}<button data-auto>${t("autoAssign")}</button><span>${t("workerTool")}</span></div>`;
if (task.kind === "store") return storageEditor();
if (["role", "draft", "build", "plant"].includes(task.kind)) return "";
return `<div class="action-choices">${moves.map((m) => moveButton(m, moveLabel(m), m.good ?? { recruit: m.kind === "c" ? "citizen" : "worker", produce: "craftsman", hacienda: "planter", villa: "citizen", recruitBonus: "worker", raid: "smuggler", plunder: "smuggler", poach: "recruiter", capture: m.id, forest: m.forest ? "forest" : task.id }[m.type])).join("")}</div>`;
}
function remaining() {
const a = state.players[seat];
let w = a.reserve.w,
c = a.reserve.c;
for (const x of [...a.estates, ...a.buildings]) {
w += x.w;
c += x.c;
}
for (const x of [...draft.estates, ...draft.buildings]) {
w -= x.w;
c -= x.c;
}
return { w, c };
}
function storageEditor() {
const slots =
(has("smallWarehouse") ? 1 : 0) + (has("largeWarehouse") ? 2 : 0);
return `<div class="storage-editor"><p>${t("storageHint")}</p>${GOODS.filter(
(g) => state.players[seat].goods[g],
)
.map(
(g) =>
`<div>${icon(g, 28)}<strong>${t(g)}</strong>${slots ? `<button data-storetype="${g}" class="${draft.types.includes(g) ? "selected" : ""}" aria-pressed="${draft.types.includes(g)}">${t("full")}</button>` : ""}<button class="icon-button" data-qty="${g}:-1" aria-label="${esc(t("minus"))}">${icon("minus")}</button><b>${draft.goods[g]} / ${state.players[seat].goods[g]}</b><button class="icon-button" data-qty="${g}:1" aria-label="${esc(t("plus"))}">${icon("plus")}</button></div>`,
)
.join("")}</div>`;
}
function peopleSlots(key, x, n = 1) {
const editable =
allowed() && state.tasks[0].kind === "assign" && view === seat,
values = editable
? draft[key[0] === "e" ? "estates" : "buildings"][Number(key.slice(1))]
: x;
return `<div class="worker-slots">${Array.from({ length: n }, (_, i) => {
const k = i < values.c ? "c" : i < values.c + values.w ? "w" : null;
return editable
? `<button class="worker-slot ${k ?? ""}" data-slot="${key}:${i}" aria-label="${esc(`${t(k === "c" ? "citizens" : k === "w" ? "workers" : "empty")} · ${t(x.id)}`)}">${k ? icon(k === "c" ? "citizen" : "worker", 20) : "+"}</button>`
: `<span class="worker-slot ${k ?? ""}">${k ? icon(k === "c" ? "citizen" : "worker", 20) : "·"}</span>`;
}).join("")}</div>`;
}
function playerBoard() {
const a = state.players[view];
return `<section class="player-board panel" id="own-board"><header><h2>${esc(a.name)}</h2><div>${metric("coin", a.coins)}${metric("vp", a.vp ?? "?")}${metric("worker", a.reserve.w)}${a.reserve.c ? metric("citizen", a.reserve.c) : ""}</div></header><div class="inventory">${GOODS.map((g) => metric(g, a.goods[g])).join("")}</div><h3>${t("countryside")} <small>${a.estates.length}/12</small></h3><div class="estates">${a.estates.map((x, i) => `<article class="estate ${x.id}" title="${esc(t(x.id))}">${icon(x.id, 31)}${x.id !== "forest" ? peopleSlots(`e${i}`, x) : ""}</article>`).join("")}${Array.from({ length: Math.max(0, 12 - a.estates.length) }, () => '<span class="estate empty-estate"></span>').join("")}</div><h3>${t("city")} <small>${citySize(a)}/12</small></h3><div class="city-grid">${a.buildings.map((x, i) => `<article class="owned-building ${B[x.id].size === 2 ? "expanded" : ""}"><button type="button" data-building="${x.id}" class="building-face" title="${esc(t.effect(x.id))}">${icon(spriteFor(x.id), 28)}<span>${t(x.id)}</span>${metric("vp", B[x.id].vp)}</button>${peopleSlots(`b${i}`, x, B[x.id].workers)}</article>`).join("")}${a.buildings.length ? "" : `<div class="empty-city">${icon("building", 40)}<span>${t("chooseBuild")}</span></div>`}</div><button class="mobile-market-launch" data-market>${icon("building")} ${t("market")}</button></section>`;
}
function shipGraphic(sh) {
return `<svg class="ship-art" viewBox="0 0 200 112" aria-hidden="true"><path fill="#edf0d4" stroke="#b6a37b" d="M96 6v58H42Zm10 9v49h43Z"/><path fill="#80614b" d="m12 66 17 31q75 22 143-3l18-28Z"/><path fill="none" stroke="#d7ac75" stroke-width="3" d="m28 77 144 0m-70-74v65"/>${Array.from({ length: sh.capacity }, (_, i) => `<rect x="${22 + i * (155 / sh.capacity)}" y="72" width="${Math.min(18, 140 / sh.capacity)}" height="17" rx="2" fill="${i < sh.amount ? "#e6c06f" : "#483e38"}" stroke="#bfa587"/>`).join("")}<path d="M5 105q20-10 40 0t40 0t40 0t40 0t30 0" fill="none" stroke="#9bbebc" stroke-width="2"/></svg>`;
}
function sharedBoard() {
const acting = allowed(),
task = state.tasks[0];
return `<section class="shared-board"><div class="roles">${state.roles
.map((r) => {
const m = state.legal.find((m) => m.type === "role" && m.id === r.id),
selected = r.taken !== null;
return `<button class="role ${selected ? "taken" : ""} ${m ? "available" : ""}" ${m && acting ? `data-move="${encode(m)}"` : `data-role="${r.id}"`}><span class="role-icon">${icon(r.id === "adventurer2" ? "adventurer" : r.id, 32)}${r.coins ? `<span class="coin-badge">${r.coins}</span>` : ""}</span><b>${t(r.id)}</b>${selected ? `<small>${esc(state.players[r.taken].name)}</small>` : ""}</button>`;
})
.join(
"",
)}</div><div class="port panel"><header><h2>${t("harborTitle")}</h2><div>${metric("vp", Math.max(0, state.vpSupply))}${metric("worker", state.register.w)}${state.register.c ? metric("citizen", state.register.c) : ""}</div></header><div class="ships">${state.ships.map((sh, i) => `<article class="ship ${sh.amount === sh.capacity ? "full" : ""}">${shipGraphic(sh)}<div>${sh.good ? icon(sh.good, 25) : icon("ship", 25)}<b>${sh.amount}<small> / ${sh.capacity}</small></b></div></article>`).join("")}</div><div class="trade-row"><span>${t("tradingHouse")}</span>${Array.from({ length: 4 }, (_, i) => `<span class="trade-slot">${state.trade[i] ? icon(state.trade[i], 26) : "·"}</span>`).join("")}</div><div class="estate-offer">${state.offer
.map((id, i) => {
const m = state.legal.find(
(m) => m.type === "plant" && m.id === id && !m.forest,
);
return `<button class="offer ${id}" ${m && acting ? `data-move="${encode(m)}"` : "disabled"} title="${esc(t(id))}">${icon(id, 28)}</button>`;
})
.join("")}${(() => {
const m = state.legal.find(
(m) => m.type === "plant" && m.id === "quarry",
);
return `<button class="offer quarry" ${m && acting ? `data-move="${encode(m)}"` : "disabled"} title="${esc(t("quarry"))}">${icon("quarry", 28)}<small>${state.quarries}</small></button>`;
})()}${acting && task.kind === "plant" && state.legal.some((m) => m.forest) ? `<button data-forests>${icon("forest")} ${t("forest")}</button>` : ""}</div></div>${state.festivals.length ? `<section class="festival-strip">${state.festivals.map((f, i) => `<button data-festival="${i}" class="festival ${f.claimed !== undefined ? "claimed" : ""}">${icon(f.claimed !== undefined ? "check" : "festival", 20)}<span>${t(f.id)}</span><span class="festival-target">${[...f.targets.goods, ...f.targets.estates].map((g) => icon(g, 22)).join("")}${f.targets.building ? icon("building", 22) : ""}</span></button>`).join("")}</section>` : ""}</section>`;
}
function market() {
const task = state.tasks[0],
isDraft = task?.kind === "draft",
ids = isDraft
? [
...new Set(
state.legal.filter((m) => m.type === "draft").map((m) => m.id),
),
...Object.keys(state.market),
]
: Object.keys(state.market);
return `<section class="building-market panel"><header><h2>${isDraft ? t("chooseDraft") : t("market")}</h2><span>${icon("building")}</span></header><div class="market-grid">${ids
.sort((a, b) => B[a].cost - B[b].cost || a.localeCompare(b))
.map((id) => {
const b = B[id],
m = state.legal.find(
(m) =>
(isDraft ? m.type === "draft" : m.type === "build") &&
m.id === id,
),
n = state.market[id] ?? b.copies;
return `<button class="bcard ${b.good ? "production" : "commercial"} ${m && allowed() ? "affordable" : ""} ${!n ? "sold-out" : ""}" data-building="${id}" ${!n && !m ? 'aria-disabled="true"' : ""}><span class="bcard-icon">${icon(spriteFor(id), 32)}</span><strong>${t(id)}</strong><span class="price">${metric("coin", !isDraft && task?.kind === "build" && Number.isInteger(seat) ? cost(state, seat, id) : b.cost)}</span><span class="building-info">${metric("vp", b.vp)}<span>${icon("worker", 16)}${b.workers}</span>${b.size === 2 ? '<span class="double-space">▭▭</span>' : ""}<small>×${n}</small></span></button>`;
})
.join("")}</div></section>`;
}
function bottom() {
if (state.finished)
return `<div class="action-dock"><strong>${t("finished")}</strong><button class="primary" data-scores>${t("finalScore")}</button></div>`;
const can = allowed(),
task = state.tasks[0],
pass = state.legal.find((m) => m.type === "pass");
let confirm = "";
if (can && ["build", "draft"].includes(task.kind))
confirm = `<button class="primary" data-market>${icon("building")} ${t("market")}</button>`;
if (can && task.kind === "assign") {
const rest = remaining(),
a = state.players[seat],
capacity =
a.estates.filter((e) => e.id !== "forest").length +
sum(a.buildings.map((b) => B[b.id].workers)),
assigned = sum(
[...draft.estates, ...draft.buildings].map((x) => x.w + x.c),
),
valid = assigned === Math.min(capacity, assigned + rest.w + rest.c);
confirm = `<button class="primary" data-confirm-assign ${valid ? "" : "disabled"}>${icon("check")} ${t("confirm")}</button>`;
}
if (can && task.kind === "store") {
const n = sum(
GOODS.filter((g) => !draft.types.includes(g)).map(
(g) => draft.goods[g],
),
);
confirm = `<button class="primary" data-confirm-store ${n <= 1 + (has("storehouse") ? 3 : 0) ? "" : "disabled"}>${icon("check")} ${t("confirm")}</button>`;
}
const special =
enabled && !pending && state.legal.some((m) => m.type === "bohio")
? `<button class="icon-button" data-bohio title="${esc(t("bohioMove"))}">${icon("worker")}</button>`
: "";
return `<div class="action-dock"><div>${icon(task?.kind === "role" ? "governor" : (state.role ?? "building"), 26)}<strong>${title()}</strong></div>${special}${pass && can ? moveButton(pass, t(task?.kind === "trade" && task.acted ? "finish" : "pass"), "pass", "quiet") : ""}${confirm}</div>`;
}
function render(s) {
if (s) state = s;
if (!state) return;
view = Math.min(view, state.players.length - 1);
draftInit();
shell.classList.toggle(
"is-building",
allowed() && ["build", "draft"].includes(state.tasks[0]?.kind),
);
const html = `<div class="pr-content"><header class="game-header"><div class="wordmark"><span>PUERTO RICO</span><small>1897 · Special Edition</small></div><span class="round-indicator">${t("round")} <b>${state.round}</b></span><nav>${["rules", "journal", ...(chat ? ["chat"] : [])].map((id) => `<button class="icon-button" data-panel="${id}" title="${esc(t(id))}" aria-label="${esc(t(id))}">${icon(id)}</button>`).join("")}</nav></header><div class="player-strip">${state.players.map((p, i) => `<button data-player="${i}" class="player-tab ${i === view ? "selected" : ""} ${i === state.tasks[0]?.p ? "turn" : ""}"><span class="player-name">${i === state.governor ? icon("governor", 18) : ""}${esc(p.name)}</span><span>${metric("coin", p.coins)}${metric("vp", p.vp ?? "?")}</span></button>`).join("")}</div>${localControls ? `<div class="local-controls"><span>${t("local")}</span><button data-local="undo" title="${esc(t("undo"))}" aria-label="${esc(t("undo"))}">${icon("undo", 18)}</button><button data-local="opponents" title="${esc(t("opponents"))}" aria-label="${esc(t("opponents"))}">${icon("pass", 18)}</button><button data-local="reset" title="${esc(t("newGame"))}" aria-label="${esc(t("newGame"))}">${icon("reset", 18)}</button><button data-local="dark" title="Light / dark" aria-label="Light / dark">${icon("dark", 18)}</button></div>` : ""}<div class="board-layout">${sharedBoard()}${playerBoard()}<section class="action-panel" aria-live="polite">${allowed() && !["role", "draft", "build", "plant"].includes(state.tasks[0]?.kind) ? `<h2>${title()}</h2>` : ""}${actionPanel()}</section>${market()}</div>${bottom()}</div>`;
morphdom(content, html, {
childrenOnly: true,
onBeforeElUpdated(from, to) {
return !from.isEqualNode(to);
},
});
if (modal.open && modalMode === "journal") {
scrollLog = body.scrollTop;
body.innerHTML = journal();
body.scrollTop = scrollLog;
}
}
function journal() {
return `<ol class="journal-list">${state.events
.map((e) => {
if (e.type === "round")
return `<li class="round-divider">${t("round")} ${e.round}</li>`;
return `<li>${e.p !== null && e.p !== undefined ? `<strong>${esc(state.players[e.p].name)}</strong>` : ""}<span>${e.type === "role" ? `${icon(e.id, 21)} ${t(e.id)}` : e.type === "estate" ? `${icon("planter", 20)} ${icon(e.id, 22)} ${t(e.id)}` : e.type === "build" ? `${icon("builder", 20)} ${t(e.id)}` : e.type === "festival" ? `${icon("festival", 20)} ${t(e.id)}` : esc(t(e.type))}${e.goods ? goodsRow(e.goods) : ""}${e.good ? icon(e.good, 23) : ""}${e.coins ? metric("coin", e.coins) : ""}${e.vp ? metric("vp", e.vp) : ""}</span></li>`;
})
.join("")}</ol>`;
}
function buildingInfo(id) {
const b = B[id],
moves = state.legal.filter(
(m) => ["build", "draft"].includes(m.type) && m.id === id,
);
show(
t(id),
`<div class="building-detail">${icon(spriteFor(id), 72)}<div>${metric("coin", b.cost)}${metric("vp", b.vp)}${metric("worker", b.workers)}</div></div><p>${esc(b.good && b.good !== "tailor" ? `${t("produce")} : ${t(b.good)}.` : t.effect(id))}</p>${moves.length && allowed() ? `<div class="action-choices">${moves.map((m) => moveButton(m, `${t(m.type === "draft" ? "selected" : "builder")} ${metric("coin", m.type === "draft" ? b.cost : cost(state, seat, id))}${m.worker ? ` − ${icon(m.worker.kind === "c" ? "citizen" : "worker")} ${targetLabel(m.worker.key)}` : ""}${m.good ? ` − ${icon(m.good)}` : ""}${m.point ? ` − ${metric("vp", 1)}` : ""}`, "check", "primary")).join("")}</div>` : ""}`,
);
}
function festivalInfo(i) {
const f = state.festivals[i],
goals = {
produce: t("produce"),
estates: t("countryside"),
farmProduce: `${t("countryside")} + ${t("produce")}`,
build: t("builder"),
tradeFull: `${t("trade")} · 4 / 4`,
ship: t("ship"),
dispatchBig: `${t("dispatch")} · ${Math.max(...state.ships.map((s) => s.capacity))}`,
dispatchSmall: `${t("dispatch")} · ${Math.min(...state.ships.map((s) => s.capacity))}`,
};
show(
t(f.id),
`<p>${goals[f.goal]}</p><div class="festival-details">${f.targets.estates.map((g) => metric(g, f.amount ?? 1)).join("")}${f.targets.goods.map((g, j) => metric(g, f.amounts?.[j] ?? f.amount ?? 1)).join("")}${f.targets.building ? t(f.targets.building) : ""}</div><h3>${t("reward")}</h3><div>${f.reward.coins ? metric("coin", f.reward.coins) : ""}${f.reward.vp ? metric("vp", f.reward.vp) : ""}${f.reward.workers ? metric("worker", f.reward.workers) : ""}</div>${f.claimed !== undefined ? `<p>${t("claimed")} ${esc(state.players[f.claimed].name)}</p>` : ""}`,
);
}
function scores() {
show(
t("finalScore"),
`<div class="scores">${(state.results ?? [])
.map(
(r, i) =>
`<article><header><h3>${esc(state.players[i].name)}</h3>${metric("vp", r.total)}</header><p>${t("tokens")} <b>${r.tokens}</b></p><p>${t("market")} <b>${r.buildings}</b></p><p>${t("citizens")} <b>${r.citizens}</b></p>${Object.entries(
r.bonus,
)
.map(([id, n]) => `<p>${t(id)} <b>${n}</b></p>`)
.join("")}<p>${t("tie")} <b>${r.tie}</b></p></article>`,
)
.join("")}</div>`,
);
}
async function send(m) {
if (
!allowed() &&
!(
enabled &&
!pending &&
m.type === "bohio" &&
state.legal.some((x) => JSON.stringify(x) === JSON.stringify(m))
)
)
return;
pending = true;
error.hidden = true;
render();
try {
await onMove(m);
if (modal.open && modalMode !== "journal") hide(modal);
} catch (err) {
error.textContent = err.message || t("error");
error.hidden = false;
} finally {
pending = false;
render();
}
}
function click(event) {
const el = event.target.closest("button");
if (!el || el.disabled) return;
if (el.hasAttribute("data-close")) {
hide(el.closest("dialog"));
return;
}
if (el.dataset.panel) {
if (el.dataset.panel === "chat") {
lastFocus = el;
chatDialog.showModal();
chat?.setOpen(true);
return;
}
if (el.dataset.panel === "journal") {
show(t("journal"), journal(), "journal");
body.scrollTop = body.scrollHeight;
return;
}
show(
t("rules"),
`<div class="rules-content"><p>${t("ruleFlow")}</p>${state.roles
.filter((r) => r.id !== "adventurer2")
.map((r) => `<h3>${icon(r.id)} ${t(r.id)}</h3><p>${t.role(r.id)}</p>`)
.join(
"",
)}<h3>${icon("worker")} ${t("workers")}</h3><p>${t("ruleWorkers")}</p><h3>${icon("ship")} ${t("ship")}</h3><p>${t("ruleShipping")}</p><h3>${icon("vp")} ${t("finalScore")}</h3><p>${t("ruleEnd")}</p><h3>${t("abilities")}</h3>${Object.keys(
state.market,
)
.map(
(id) =>
`<p><strong>${t(id)}</strong> — ${esc(t.effect(id) || t("produce") + " : " + t(B[id].good))}</p>`,
)
.join("")}</div>`,
);
return;
}
if (el.dataset.role) {
show(t(el.dataset.role), `<p>${t.role(el.dataset.role)}</p>`);
return;
}
if (el.dataset.building) {
buildingInfo(el.dataset.building);
return;
}
if (el.hasAttribute("data-market")) {
show(t("market"), market(), "market");
return;
}
if (el.dataset.festival !== undefined) {
festivalInfo(Number(el.dataset.festival));
return;
}
if (el.dataset.player !== undefined) {
view = Number(el.dataset.player);
render();
return;
}
if (el.dataset.local) {
localControls?.(el.dataset.local);
return;
}
if (el.hasAttribute("data-scores")) {
scores();
return;
}
if (
!allowed() &&
!el.hasAttribute("data-bohio") &&
!(
el.dataset.move &&
JSON.parse(decodeURIComponent(el.dataset.move)).type === "bohio"
)
)
return;
if (el.dataset.move) {
const m = JSON.parse(decodeURIComponent(el.dataset.move));
if (["smallWharf", "produce"].includes(m.type)) {
cargoDialog(m);
return;
}
send(m);
return;
}
if (el.hasAttribute("data-bohio")) {
show(
t("bohioMove"),
`<div class="action-choices">${state.legal
.filter((m) => m.type === "bohio")
.map((m) =>
moveButton(m, moveLabel(m), m.kind === "c" ? "citizen" : "worker"),
)
.join("")}</div>`,
);
return;
}
if (el.hasAttribute("data-forests")) {
show(
t("forest"),
`<div class="action-choices">${state.legal
.filter((m) => m.forest)
.map((m) => moveButton(m, moveLabel(m), m.id))
.join("")}</div>`,
);
return;
}
if (el.hasAttribute("data-confirm-assign")) {
send({ type: "assign", ...draft });
return;
}
if (el.hasAttribute("data-confirm-store")) {
send({ type: "store", ...draft });
return;
}
if (el.hasAttribute("data-auto")) {
draft = autoAssignment(state, seat);
render();
return;
}
if (el.dataset.tool) {
tool = el.dataset.tool;
render();
return;
}
if (el.dataset.slot) {
const [key, ix] = el.dataset.slot.split(":"),
x =
draft[key[0] === "e" ? "estates" : "buildings"][Number(key.slice(1))],
index = Number(ix);
const occupied = index < x.c ? "c" : index < x.c + x.w ? "w" : null;
if (occupied) x[occupied]--;
else if (tool !== "erase" && remaining()[tool] > 0) x[tool]++;
render();
return;
}
if (el.dataset.qty) {
const [g, n] = el.dataset.qty.split(":");
draft.goods[g] = Math.max(
0,
Math.min(state.players[seat].goods[g], draft.goods[g] + Number(n)),
);
render();
return;
}
if (el.dataset.storetype) {
const g = el.dataset.storetype;
if (draft.types.includes(g))
draft.types = draft.types.filter((x) => x !== g);
else if (
draft.types.length <
(has("smallWarehouse") ? 1 : 0) + (has("largeWarehouse") ? 2 : 0)
) {
draft.types.push(g);
draft.goods[g] = state.players[seat].goods[g];
}
render();
}
}
function cargoDialog(m) {
show(
t(m.type === "produce" ? "produce" : "smallWharfShip"),
`<form class="cargo-form"><p>${t("selectQty")}</p>${GOODS.filter(
(g) => m.goods[g],
)
.map(
(g) =>
`<label>${icon(g, 26)}${t(g)}<input type="number" min="0" max="${m.goods[g]}" value="${m.goods[g]}" name="${g}" inputmode="numeric"></label>`,
)
.join(
"",
)}<button type="submit" class="primary">${t("confirm")}</button></form>`,
);
body.querySelector("form").onsubmit = (ev) => {
ev.preventDefault();
const data = new FormData(ev.currentTarget),
goods = Object.fromEntries(
GOODS.map((g) => [g, Number(data.get(g) ?? 0)]),
);
if (m.type === "produce" || sum(Object.values(goods)))
send({ ...m, goods });
};
}
function onCancel(ev) {
ev.preventDefault();
hide(ev.target);
}
shell.addEventListener("click", click);
modal.addEventListener("cancel", onCancel);
chatDialog.addEventListener("cancel", onCancel);
return {
render,
setPlayer(p) {
seat = p;
view = p ?? 0;
draftKey = "";
render();
},
setEnabled(value) {
enabled = value;
render();
},
setPreferences(p) {
const previousLocale = t.fr;
preferences = { ...preferences, ...p };
t = translator(preferences.locale ?? preferences.language ?? "en");
if (previousLocale !== t.fr) configureChat();
for (const b of shell.querySelectorAll("[data-close]"))
b.setAttribute("aria-label", t("close"));
shell.classList.toggle(
"dark",
preferences.dark ?? preferences.theme === "dark",
);
render();
},
destroy() {
shell.removeEventListener("click", click);
chatView?.destroy();
shell.remove();
},
};
}