Complete Achievement deck and Puertoma solo playtest
This commit is contained in:
parent
1ccdc11936
commit
4b86bbf970
20 changed files with 2329 additions and 41 deletions
|
|
@ -3,7 +3,7 @@
|
|||
## Product decisions
|
||||
|
||||
- Target **Puerto Rico 1897: Special Edition**, including the June 2026 errata. Keep one fixed release configuration (`release-config.js`); expansion switches are internal, with no expansion picker in BGS or the viewer.
|
||||
- Read [source notes](docs/sources.md) before changing rules. Achievements lacks the exact deck, Puertoma is not implemented, and Festival's unique-building reservation is an explicit interpretation. Do not invent missing components or call ordinary bots Puertoma.
|
||||
- Read [source notes](docs/sources.md) before changing rules. Achievements and Puertoma use the sourced decks documented there. Festival's unique-building reservation remains an explicit interpretation. Keep local Puertoma separate from ordinary hosted bot seats, and do not invent components.
|
||||
- Use BGS locale and color-blind preferences, without duplicate controls. Favor readable pictograms with tooltips; colors must not be the only identifiers. Role warnings remain advisory, never forbidding a legal strategic choice.
|
||||
- The local preview skips the market draft and saves progress in the browser. Preserve the user's session; use a separate browser context for destructive playtests.
|
||||
|
||||
|
|
|
|||
16
README.md
16
README.md
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
[Play now at boardgamers.space](https://boardgamers.space/boardgame/puerto-rico)
|
||||
|
||||
Implementation for Boardgamers Space, targeting **Puerto Rico 1897: Special Edition** and the official June 2026 errata. Version 1 is published as a **private beta** on [BGS](https://boardgamers.space/boardgame/puerto-rico), with Unlisted disabled. The engine package is `@boardgamers/puerto-rico@0.1.1`; English and French are configured in the platform metadata.
|
||||
Implementation for Boardgamers Space, targeting **Puerto Rico 1897: Special Edition** and the official June 2026 errata. Version 1 is published as a **private beta** on [BGS](https://boardgamers.space/boardgame/puerto-rico), with Unlisted disabled. The engine package is `@boardgamers/puerto-rico@0.2.0`; English and French are configured in the platform metadata.
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
|
|
@ -10,7 +10,9 @@ 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.
|
||||
The local preview lets you play one seat with two ordinary bots. For the rules-based solo opponent, open `http://127.0.0.1:5251/?mode=puertoma&locale=fr` (optionally `&difficulty=easy` or `&difficulty=hard`). Solo begins by choosing four of six Achievement cards; its save is separate from the ordinary preview, whose existing session is preserved.
|
||||
|
||||
The 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
|
||||
|
||||
|
|
@ -24,17 +26,19 @@ Implemented modules:
|
|||
- 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.
|
||||
- Achievements: the complete 30-card deck, secret dealing, optional internal draft, automatic completion and endgame scoring.
|
||||
- Puertoma: exact eight-card tiebreaker deck, shared action tracker, permanent workers, estate production, building levels and reservations, all 12 ability types, three difficulty levels and expansion interactions. Available through local solo preview or internal `options.puertoma = { humans: 1, difficulty: "normal" }` with three total seats.
|
||||
|
||||
**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 fixed multiplayer BGS configuration includes all six expansion modules. Puertoma is available locally; hosted bot seats continue to use the human rules. See [source notes](docs/sources.md) for provenance and the Festival unique-building marker interpretation.
|
||||
|
||||
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.
|
||||
The engine accepts the optional `costSwap`, `alternativeStart`, `tailorLimit`, `pairingRestrictions` and `achievementDraft` 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.
|
||||
- Paper, terracotta and sea-green visual theme in light/dark modes; original vector town illustration, larger corn and a repeat-privilege pictogram.
|
||||
- Editable worker allocation, goods storage, building details, private shipping, final scoring.
|
||||
- Editable worker allocation, goods storage, building payment choices, private shipping, Achievement selection and final scoring.
|
||||
- Contextual role warnings explain unavailable actions before committing a choice, including role coins and building rewards. They remain advisory; legal strategic choices are preserved.
|
||||
- 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.
|
||||
|
|
@ -48,7 +52,7 @@ 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.
|
||||
The implementation remains a preview pending playtesting, and the Festival marker interpretation noted above. Original vector UI artwork is in `viewer/icons.js`; reference scans in `.local/` are ignored and never bundled.
|
||||
|
||||
## Private BGS publication
|
||||
|
||||
|
|
|
|||
|
|
@ -2,9 +2,9 @@
|
|||
"label": "Puerto Rico: Special Edition",
|
||||
"public": false,
|
||||
"players": [2, 3, 4, 5],
|
||||
"description": "Choose roles, develop your island, produce goods and ship them for points. This Special Edition adaptation includes New Buildings, Citizens, Smuggler, Festival and Festival Activities, in one fixed configuration for 2–5 players.",
|
||||
"description": "Choose roles, develop your island, produce goods and ship them for points. This Special Edition adaptation includes New Buildings, Citizens, Smuggler, Festival Festival Activities and Achievements, in one fixed configuration for 2–5 players.",
|
||||
"rules": "Choose a role, then all players carry out its action in turn; the player who chose it receives a privilege. Plant estates, recruit workers, construct buildings and produce goods. Sell goods for money or ship them for points. When everyone has chosen their roles, pass the governor marker and begin the next round. Most points from shipping, buildings and bonuses wins.\n\n[Official Special Edition rules (English)](https://awakenrealms.com/images/download/puerto-rico/EN/EN_PR_Rulebook_210x285mm_bleed3mm%20%5B44%20pages%5D.pdf). In-game help is available in English and French.",
|
||||
"credits": "Designed by **Andreas Seyfarth**. Based on **Puerto Rico 1897: Special Edition**, published by **Awaken Realms** and **Ravensburger**.\n\nOriginal vector interface illustrations for this digital adaptation. The private playtest includes the five modules listed above; Achievements and Puertoma are not included.",
|
||||
"credits": "Designed by **Andreas Seyfarth**. Based on **Puerto Rico 1897: Special Edition**, published by **Awaken Realms** and **Ravensburger**.\n\nOriginal vector interface illustrations for this digital adaptation. The private multiplayer playtest includes all six modules listed above. Puertoma solo mode is available in the local preview.",
|
||||
"links": {
|
||||
"publisher": "https://awakenrealms.com/games/awaken-realms/puerto-rico"
|
||||
},
|
||||
|
|
@ -16,7 +16,10 @@
|
|||
"replayable": true,
|
||||
"chat": true,
|
||||
"integratedControls": ["chat"],
|
||||
"dependencies": { "scripts": [], "stylesheets": [] }
|
||||
"dependencies": {
|
||||
"scripts": [],
|
||||
"stylesheets": []
|
||||
}
|
||||
},
|
||||
"options": [],
|
||||
"expansions": [],
|
||||
|
|
@ -27,8 +30,14 @@
|
|||
"type": "select",
|
||||
"default": "en",
|
||||
"items": [
|
||||
{ "name": "en", "label": "English" },
|
||||
{ "name": "fr", "label": "Français" }
|
||||
{
|
||||
"name": "en",
|
||||
"label": "English"
|
||||
},
|
||||
{
|
||||
"name": "fr",
|
||||
"label": "Français"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
|
|
|
|||
|
|
@ -11,12 +11,17 @@ Apply the errata: game-end triggers finish the **round**, including VP depletion
|
|||
|
||||
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
|
||||
## Achievement and Puertoma components
|
||||
|
||||
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.
|
||||
- [All 30 Achievement cards, transcribed by owner Ben Tinney](https://boardgamegeek.com/thread/3629370/article/47036030#47036030), 17 December 2025. This supplies the physical card names, objectives and VP values missing from the rulebook. Leading Producer uses the publisher errata: seven crates in one Craftsman phase.
|
||||
- [Achievement wording discussion](https://boardgamegeek.com/thread/3743692/translation-problems-with-achievement-cards-in-chi). Independent Shipper means filling an empty cargo ship in one action; dispatch means placing the last crate, as defined on rulebook page 30. Master Architect refers to an expanded building, not an expansion building. Deal Closer requires the role chooser to place the fourth Trading House good.
|
||||
- [Authorized Puertoma print-and-play adaptation](https://boardgamegeek.com/filepage/325253/puertoricoedition2002-fanmadepuertoma), posted by RandomObfuscation, states permission from Awaken Realms and Davíd. Its eight tiebreaker card numbers/orders match the visible official examples. Terminology is mapped from Mayor/Settler/Prospector to Recruiter/Planter/Adventurer. The Special Edition rulebook pp. 33–42 controls gameplay, abilities and expansion overrides; the older terminology and action board from this adaptation are not used as gameplay rules.
|
||||
- [Puertoma Builder clarification](https://boardgamegeek.com/thread/3656491/puertoma-builder-role-questions): published highest-affordable-level/random-building behavior is implemented, rather than the earlier highest-cost design intent.
|
||||
|
||||
### Festival building markers: unresolved rulebook conflict
|
||||
Repeated legal-move/state queries do not draw cards. Card draws are committed only when actions execute, so replays reproduce the shuffled deck. Counting tied building choices proceeds left to right in the digital market's price/name order. Festival worker ties use card numbers; ordinary worker priorities complete the estate with the fewest missing workers, then the best good. Unused workers remain permanently in the VP area. Puertoma incomplete Achievement scoring is separate from human card scoring and never removes VP tokens.
|
||||
|
||||
### Festival building markers: 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.
|
||||
Reference PDFs and downloaded component images are research material outside the shipped package or in ignored `.local/rules/`; they are not shipped as game assets. UI illustrations are original code-generated vectors.
|
||||
|
|
|
|||
333
engine/achievements.js
Normal file
333
engine/achievements.js
Normal file
|
|
@ -0,0 +1,333 @@
|
|||
import { BUILDINGS as B, GOODS } from "./catalog.js";
|
||||
|
||||
// All 30 physical cards, transcribed by an owner; see docs/sources.md.
|
||||
// Leading Producer includes the publisher's June 2026 correction.
|
||||
export const ACHIEVEMENTS = [
|
||||
{
|
||||
id: "bigSpender",
|
||||
name: "Big Spender",
|
||||
vp: 5,
|
||||
goal: "spendAll",
|
||||
text: "Build an expanded Building by paying all your Coins.",
|
||||
},
|
||||
{
|
||||
id: "caramelPopcorn",
|
||||
name: "Caramel Popcorn Inventor",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["corn", "sugar"],
|
||||
amount: 8,
|
||||
text: "Have at least 8 Crates of Corn and Sugar combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "coffeeDispatcher",
|
||||
name: "Coffee Dispatcher",
|
||||
vp: 5,
|
||||
goal: "dispatch",
|
||||
good: "coffee",
|
||||
text: "Dispatch a Cargo Ship containing Coffee.",
|
||||
},
|
||||
{
|
||||
id: "confectionerySupplier",
|
||||
name: "Confectionery Supplier",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["fruit", "sugar"],
|
||||
amount: 7,
|
||||
text: "Have at least 7 Crates of Fruit and Sugar combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "cornDispatcher",
|
||||
name: "Corn Dispatcher",
|
||||
vp: 3,
|
||||
goal: "dispatch",
|
||||
good: "corn",
|
||||
text: "Dispatch a Cargo Ship containing Corn.",
|
||||
},
|
||||
{
|
||||
id: "dealCloser",
|
||||
name: "Deal Closer",
|
||||
vp: 4,
|
||||
goal: "closeTrade",
|
||||
text: "Sell the last Good to the Trading House as the Trader.",
|
||||
},
|
||||
{
|
||||
id: "dockTycoon",
|
||||
name: "Dock Tycoon",
|
||||
vp: 5,
|
||||
goal: "shipTypes",
|
||||
text: "Load at least 3 different Goods during one Captain phase.",
|
||||
},
|
||||
{
|
||||
id: "fruitDispatcher",
|
||||
name: "Fruit Dispatcher",
|
||||
vp: 3,
|
||||
goal: "dispatch",
|
||||
good: "fruit",
|
||||
text: "Dispatch a Cargo Ship containing Fruit.",
|
||||
},
|
||||
{
|
||||
id: "headAdministrator",
|
||||
name: "Head Administrator",
|
||||
vp: 6,
|
||||
goal: "buildingWorkers",
|
||||
text: "Have at least 12 Workers placed on Buildings.",
|
||||
},
|
||||
{
|
||||
id: "independentShipper",
|
||||
name: "Independent Shipper",
|
||||
vp: 4,
|
||||
goal: "fillShip",
|
||||
text: "Fully load a Cargo Ship in one action, from empty to full.",
|
||||
},
|
||||
{
|
||||
id: "leadingEmployer",
|
||||
name: "Leading Employer",
|
||||
vp: 6,
|
||||
goal: "estateWorkers",
|
||||
text: "Have at least 9 Workers on Countryside tiles.",
|
||||
},
|
||||
{
|
||||
id: "leadingProducer",
|
||||
name: "Leading Producer",
|
||||
vp: 6,
|
||||
goal: "produce",
|
||||
text: "Produce at least 7 Crates during one Craftsman phase.",
|
||||
},
|
||||
{
|
||||
id: "luxuryCropTrader",
|
||||
name: "Luxury Crop Trader",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["coffee", "tobacco"],
|
||||
amount: 5,
|
||||
text: "Have at least 5 Crates of Coffee and Tobacco combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "luxuryGoodsProvider",
|
||||
name: "Luxury Goods Provider",
|
||||
vp: 5,
|
||||
goal: "productionSet",
|
||||
text: "Have at least 1 Sugar, 1 Tobacco, and 1 Coffee Production Building.",
|
||||
},
|
||||
{
|
||||
id: "majorInvestor",
|
||||
name: "Major Investor",
|
||||
vp: 7,
|
||||
goal: "expanded",
|
||||
text: "Have at least 2 expanded Buildings.",
|
||||
},
|
||||
{
|
||||
id: "majorLandowner",
|
||||
name: "Major Landowner",
|
||||
vp: 7,
|
||||
goal: "developed",
|
||||
text: "Have a maximum of 2 empty Countryside spaces and 2 empty Building spaces.",
|
||||
},
|
||||
{
|
||||
id: "masterAgronomist",
|
||||
name: "Master Agronomist",
|
||||
vp: 5,
|
||||
goal: "estates",
|
||||
text: "Have 12 Countryside tiles.",
|
||||
},
|
||||
{
|
||||
id: "masterArchitect",
|
||||
name: "Master Architect",
|
||||
vp: 3,
|
||||
goal: "cheapExpanded",
|
||||
text: "Build an expanded Building paying a maximum of 6 Coins.",
|
||||
},
|
||||
{
|
||||
id: "masterCollector",
|
||||
name: "Master Collector",
|
||||
vp: 7,
|
||||
goal: "goods",
|
||||
text: "Have at least 7 Crates of one Good.",
|
||||
},
|
||||
{
|
||||
id: "pastryMaker",
|
||||
name: "Pastry Maker",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["corn", "fruit"],
|
||||
amount: 9,
|
||||
text: "Have at least 9 Crates of Corn and Fruit combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "prudentMerchant",
|
||||
name: "Prudent Merchant",
|
||||
vp: 4,
|
||||
goal: "store",
|
||||
text: "Store at least 2 different Goods at the end of a Captain phase.",
|
||||
},
|
||||
{
|
||||
id: "seniorBureaucrat",
|
||||
name: "Senior Bureaucrat",
|
||||
vp: 7,
|
||||
goal: "commercial",
|
||||
text: "Have at least 7 regular Commercial Buildings.",
|
||||
},
|
||||
{
|
||||
id: "specialisedShipper",
|
||||
name: "Specialised Shipper",
|
||||
vp: 5,
|
||||
goal: "shipAmount",
|
||||
text: "Load at least 5 Crates of the same Good at once.",
|
||||
},
|
||||
{
|
||||
id: "sugarDispatcher",
|
||||
name: "Sugar Dispatcher",
|
||||
vp: 4,
|
||||
goal: "dispatch",
|
||||
good: "sugar",
|
||||
text: "Dispatch a Cargo Ship containing Sugar.",
|
||||
},
|
||||
{
|
||||
id: "tavernSupplier",
|
||||
name: "Tavern Supplier",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["coffee", "sugar"],
|
||||
amount: 6,
|
||||
text: "Have at least 6 Crates of Coffee and Sugar combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "tobaccoDispatcher",
|
||||
name: "Tobacco Dispatcher",
|
||||
vp: 5,
|
||||
goal: "dispatch",
|
||||
good: "tobacco",
|
||||
text: "Dispatch a Cargo Ship containing Tobacco.",
|
||||
},
|
||||
{
|
||||
id: "tobaccoFruitBroker",
|
||||
name: "Tobacco & Fruit Broker",
|
||||
vp: 4,
|
||||
goal: "goodsPair",
|
||||
goods: ["fruit", "tobacco"],
|
||||
amount: 6,
|
||||
text: "Have at least 6 Crates of Fruit and Tobacco combined, including at least one of each.",
|
||||
},
|
||||
{
|
||||
id: "tradeStrategist",
|
||||
name: "Trade Strategist",
|
||||
vp: 7,
|
||||
goal: "captainPoints",
|
||||
text: "Gain 7 or more VP during one Captain phase.",
|
||||
},
|
||||
{
|
||||
id: "tradeTycoon",
|
||||
name: "Trade Tycoon",
|
||||
vp: 4,
|
||||
goal: "tradeCoins",
|
||||
text: "Sell a Good to the Trading House for at least 6 Coins.",
|
||||
},
|
||||
{
|
||||
id: "tropicalProduceMagnate",
|
||||
name: "Tropical Produce Magnate",
|
||||
vp: 4,
|
||||
goal: "productionCount",
|
||||
text: "Have at least 3 Fruit and/or Sugar Production Buildings.",
|
||||
},
|
||||
];
|
||||
export const CARDS = Object.fromEntries(ACHIEVEMENTS.map((c) => [c.id, c]));
|
||||
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
|
||||
export function fulfilled(s, p, id, e = {}) {
|
||||
const a = s.players[p],
|
||||
c = CARDS[id];
|
||||
const size = sum(a.buildings.map((b) => B[b.id].size));
|
||||
const expanded = e.type === "build" && B[e.id]?.size === 2;
|
||||
const cargo = e.type === "ship" && Number.isInteger(e.ship);
|
||||
switch (c.goal) {
|
||||
case "spendAll":
|
||||
return expanded && e.paid === e.beforeCoins;
|
||||
case "goodsPair":
|
||||
return (
|
||||
c.goods.every((g) => a.goods[g] > 0) &&
|
||||
sum(c.goods.map((g) => a.goods[g])) >= c.amount
|
||||
);
|
||||
case "dispatch":
|
||||
return cargo && e.good === c.good && e.shipLoad === e.shipCapacity;
|
||||
case "closeTrade":
|
||||
return (
|
||||
e.type === "trade" &&
|
||||
!e.outpost &&
|
||||
s.owner === p &&
|
||||
s.trade.length === 4
|
||||
);
|
||||
case "shipTypes":
|
||||
return (
|
||||
s.role === "captain" &&
|
||||
GOODS.filter((g) => s.shipped?.[p]?.[g] > 0).length >= 3
|
||||
);
|
||||
case "buildingWorkers":
|
||||
return sum(a.buildings.map((b) => b.w + b.c)) >= 12;
|
||||
case "fillShip":
|
||||
return cargo && e.goods?.[e.good] === e.shipCapacity;
|
||||
case "estateWorkers":
|
||||
return sum(a.estates.map((t) => t.w + t.c)) >= 9;
|
||||
case "produce":
|
||||
return (
|
||||
s.role === "craftsman" &&
|
||||
sum(Object.values(s.production?.[p] ?? {})) >= 7
|
||||
);
|
||||
case "productionSet":
|
||||
return ["sugar", "tobacco", "coffee"].every((g) =>
|
||||
a.buildings.some((b) => B[b.id].good === g),
|
||||
);
|
||||
case "expanded":
|
||||
return a.buildings.filter((b) => B[b.id].size === 2).length >= 2;
|
||||
case "developed":
|
||||
return a.estates.length >= 10 && size >= 10;
|
||||
case "estates":
|
||||
return a.estates.length >= 12;
|
||||
case "cheapExpanded":
|
||||
return expanded && e.paid <= 6;
|
||||
case "goods":
|
||||
return GOODS.some((g) => a.goods[g] >= 7);
|
||||
case "store":
|
||||
return (
|
||||
e.type === "store" && GOODS.filter((g) => a.goods[g] > 0).length >= 2
|
||||
);
|
||||
case "commercial":
|
||||
return (
|
||||
a.buildings.filter((b) => !B[b.id].good && B[b.id].size === 1).length >=
|
||||
7
|
||||
);
|
||||
case "shipAmount":
|
||||
return (
|
||||
["ship", "smallWharf"].includes(e.type) &&
|
||||
Object.values(e.goods ?? {}).some((n) => n >= 5)
|
||||
);
|
||||
case "captainPoints":
|
||||
return s.role === "captain" && (s.phaseVP?.[p] ?? 0) >= 7;
|
||||
case "tradeCoins":
|
||||
return e.type === "trade" && !e.outpost && e.coins >= 6;
|
||||
case "productionCount":
|
||||
return (
|
||||
a.buildings.filter((b) => ["fruit", "sugar"].includes(B[b.id].good))
|
||||
.length >= 3
|
||||
);
|
||||
default:
|
||||
throw Error(`Unknown Achievement ${id}`);
|
||||
}
|
||||
}
|
||||
export function points(a) {
|
||||
return sum(
|
||||
(a.achievements ?? [])
|
||||
.filter((c) => c.completed)
|
||||
.map((c) => CARDS[c.id].vp),
|
||||
);
|
||||
}
|
||||
export function incompletePoints(s) {
|
||||
return sum(
|
||||
s.players
|
||||
.filter((a) => !a.puertoma)
|
||||
.flatMap((a) =>
|
||||
(a.achievements ?? [])
|
||||
.filter((c) => !c.completed)
|
||||
.map((c) => CARDS[c.id].vp),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -96,6 +96,7 @@ export const EXPANSIONS = [
|
|||
"smuggler",
|
||||
"festival",
|
||||
"festival-cards",
|
||||
"achievements",
|
||||
];
|
||||
export const FESTIVALS = [
|
||||
{
|
||||
|
|
|
|||
652
engine/index.js
652
engine/index.js
|
|
@ -1,3 +1,5 @@
|
|||
import * as P from "./puertoma.js";
|
||||
import * as A from "./achievements.js";
|
||||
import { sha256 } from "@noble/hashes/sha2.js";
|
||||
import {
|
||||
GOODS,
|
||||
|
|
@ -24,17 +26,25 @@ const order = (s, p = s.owner) =>
|
|||
const total = (tile) => tile.w + tile.c;
|
||||
const building = (p, id) => p.buildings.find((b) => b.id === id);
|
||||
export const active = (p, id) =>
|
||||
!!building(p, id) && total(building(p, id)) > 0;
|
||||
!p.puertoma && !!building(p, id) && total(building(p, id)) > 0;
|
||||
const citizen = (p, id) => (building(p, id)?.c ?? 0) > 0;
|
||||
export const citySize = (p) => sum(p.buildings.map((b) => B[b.id].size));
|
||||
const citizens = (p) =>
|
||||
p.reserve.c + sum([...p.estates, ...p.buildings].map((t) => t.c));
|
||||
p.reserve.c +
|
||||
(p.puertoma?.unused.c ?? 0) +
|
||||
sum([...p.estates, ...p.buildings].map((t) => t.c));
|
||||
const people = (p) =>
|
||||
p.reserve.w + p.reserve.c + sum([...p.estates, ...p.buildings].map(total));
|
||||
p.reserve.w +
|
||||
p.reserve.c +
|
||||
(p.puertoma ? total(p.puertoma.unused) : 0) +
|
||||
sum([...p.estates, ...p.buildings].map(total));
|
||||
const spaces = (p) =>
|
||||
p.estates.filter((t) => t.id !== "forest").length +
|
||||
sum(p.buildings.map((t) => B[t.id].workers));
|
||||
const freeSpaces = (p) => spaces(p) - (people(p) - total(p.reserve));
|
||||
const freeSpaces = (p) =>
|
||||
p.puertoma
|
||||
? P.emptyEstateSpaces(p)
|
||||
: spaces(p) - (people(p) - total(p.reserve));
|
||||
function rng(s) {
|
||||
// Hash-chain generator: state is server-only and fully deterministic.
|
||||
s.random = Array.from(sha256(new TextEncoder().encode(s.random)), (b) =>
|
||||
|
|
@ -68,6 +78,7 @@ function event(s, type, p, info = {}) {
|
|||
function vp(s, p, n) {
|
||||
if (n <= 0) return;
|
||||
s.players[p].vp += n;
|
||||
if (s.phaseVP) s.phaseVP[p] += n;
|
||||
s.vpSupply -= n;
|
||||
if (s.vpSupply <= 0) s.endReason ??= "points";
|
||||
}
|
||||
|
|
@ -90,7 +101,9 @@ function fillRegister(s) {
|
|||
s.players.length,
|
||||
sum(
|
||||
s.players.map((p) =>
|
||||
sum(p.buildings.map((b) => B[b.id].workers - total(b))),
|
||||
p.puertoma
|
||||
? P.registerDemand(p)
|
||||
: sum(p.buildings.map((b) => B[b.id].workers - total(b))),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
|
@ -123,7 +136,10 @@ function setupFestival(s) {
|
|||
)
|
||||
return;
|
||||
const cards = s.expansions.includes("festival-cards")
|
||||
? shuffle(s, clone(FESTIVALS)).slice(0, 3)
|
||||
? shuffle(
|
||||
s,
|
||||
clone(FESTIVALS.filter((f) => !s.puertoma || f.goal !== "ship")),
|
||||
).slice(0, 3)
|
||||
: ["connoisseur", "cocktail", "pioneer"].map((id) =>
|
||||
clone(FESTIVALS.find((f) => f.id === id)),
|
||||
);
|
||||
|
|
@ -147,7 +163,10 @@ function setupFestival(s) {
|
|||
}
|
||||
if (f.building) {
|
||||
const choices = Object.keys(s.market).filter(
|
||||
(id) => !B[id].good && B[id].vp === f.building && s.market[id] > 0,
|
||||
(id) =>
|
||||
!B[id].good &&
|
||||
(f.building === 4 ? B[id].size === 2 : B[id].vp === f.building) &&
|
||||
s.market[id] > 0,
|
||||
);
|
||||
const id = choices[Math.floor(rng(s) * choices.length)];
|
||||
f.targets.building = id;
|
||||
|
|
@ -168,7 +187,7 @@ export function init(n, expansions = [], options = {}, seed = "puerto-rico") {
|
|||
assert(
|
||||
Array.isArray(expansions) &&
|
||||
expansions.every((x) => EXPANSIONS.includes(x)),
|
||||
"Unsupported expansion; Achievements requires the verified 30-card deck",
|
||||
"Unsupported expansion",
|
||||
);
|
||||
const s = {
|
||||
version: 1,
|
||||
|
|
@ -246,17 +265,21 @@ export function init(n, expansions = [], options = {}, seed = "puerto-rico") {
|
|||
for (const b of Object.values(B))
|
||||
if (b.expansion === "base" && (!choose || b.good))
|
||||
s.market[b.id] = n === 2 ? (b.good ? 2 : 1) : b.copies;
|
||||
if (options.puertoma) setupPuertoma(s, options.puertoma);
|
||||
fillRegister(s);
|
||||
if (choose) s.tasks = [{ kind: "draft", p: 0 }];
|
||||
else {
|
||||
finishPuertomaSetup(s);
|
||||
setupFestival(s);
|
||||
refillEstates(s);
|
||||
s.tasks = [{ kind: "role", p: 0 }];
|
||||
}
|
||||
setupAchievements(s);
|
||||
event(s, "round", 0);
|
||||
return s;
|
||||
}
|
||||
export function production(p) {
|
||||
if (p.puertoma) return P.production(p);
|
||||
const out = counts();
|
||||
for (const g of GOODS) {
|
||||
const farms = sum(p.estates.filter((t) => t.id === g).map(total));
|
||||
|
|
@ -271,7 +294,8 @@ export function production(p) {
|
|||
if (out[g] && active(p, id)) out[g]++;
|
||||
return out;
|
||||
}
|
||||
export function cost(s, p, id) {
|
||||
export function cost(s, p, id, move = {}) {
|
||||
if (s.players[p].puertoma) return P.price(s, p, id);
|
||||
const a = s.players[p],
|
||||
b = B[id];
|
||||
let base = b.cost;
|
||||
|
|
@ -297,7 +321,46 @@ export function cost(s, p, id) {
|
|||
: b.size === 1
|
||||
? 1
|
||||
: 0;
|
||||
return Math.max(0, base - discount);
|
||||
return move.pay ?? Math.max(0, base - discount);
|
||||
}
|
||||
function buildingPayments(s, p, id) {
|
||||
const a = s.players[p],
|
||||
b = B[id];
|
||||
const base =
|
||||
s.options.costSwap && id === "factory"
|
||||
? 8
|
||||
: s.options.costSwap && id === "school"
|
||||
? 7
|
||||
: b.cost;
|
||||
const quarries = Math.min(
|
||||
sum(a.estates.filter((t) => t.id === "quarry").map(total)),
|
||||
b.size === 2 ? 4 : b.vp,
|
||||
);
|
||||
const privilege =
|
||||
s.owner === p && s.role === "builder"
|
||||
? active(a, "publishingHouse")
|
||||
? 2
|
||||
: 1
|
||||
: 0;
|
||||
const lumber = active(a, "lumberyard")
|
||||
? Math.floor(a.estates.filter((t) => t.id === "forest").length / 2)
|
||||
: 0;
|
||||
const notary = active(a, "notary")
|
||||
? citizen(a, "notary")
|
||||
? b.size === 2
|
||||
? 2
|
||||
: 0
|
||||
: b.size === 1
|
||||
? 1
|
||||
: 0
|
||||
: 0;
|
||||
let reductions = Array.from({ length: quarries + 1 }, (_, i) => i);
|
||||
for (const bonus of [privilege, lumber, notary])
|
||||
if (bonus)
|
||||
reductions = [...new Set(reductions.flatMap((n) => [n, n + bonus]))];
|
||||
return [...new Set(reductions.map((n) => Math.max(0, base - n)))].sort(
|
||||
(a, b) => a - b,
|
||||
);
|
||||
}
|
||||
function tileRef(a, key) {
|
||||
if (key === "reserve") return a.reserve;
|
||||
|
|
@ -316,6 +379,7 @@ function workerSources(a) {
|
|||
);
|
||||
}
|
||||
export function buildOptions(s, p) {
|
||||
if (s.players[p].puertoma) return P.buildings(s, p);
|
||||
const a = s.players[p],
|
||||
out = [];
|
||||
for (const [id, n] of Object.entries(s.market)) {
|
||||
|
|
@ -335,6 +399,11 @@ export function buildOptions(s, p) {
|
|||
const short = cost(s, p, id) - a.coins;
|
||||
if (short <= 0) {
|
||||
out.push({ type: "build", id });
|
||||
// Quarry reductions and role Advantages may be declined (rulebook pp. 9, 12).
|
||||
// Explicit higher Coin payments let Big Spender use this legal choice.
|
||||
for (const pay of buildingPayments(s, p, id))
|
||||
if (pay > cost(s, p, id) && pay <= a.coins)
|
||||
out.push({ type: "build", id, pay });
|
||||
continue;
|
||||
}
|
||||
if (short > 3 || !active(a, "hiddenMarket")) continue;
|
||||
|
|
@ -407,6 +476,9 @@ function startRole(s, id, p, captured = false) {
|
|||
if (s.captured?.id === id) s.captured = null;
|
||||
s.role = id.startsWith("adventurer") ? "adventurer" : id;
|
||||
s.owner = p;
|
||||
s.phaseVP = s.players.map(() => 0);
|
||||
if (s.role === "recruiter")
|
||||
for (const a of s.players) if (a.puertoma) a.puertoma.recruited = 0;
|
||||
s.production = s.players.map(() => counts());
|
||||
s.shipped = s.players.map(() => counts());
|
||||
s.planted = s.players.map(() => []);
|
||||
|
|
@ -449,6 +521,7 @@ function finishPhase(s) {
|
|||
s.offer = [];
|
||||
refillEstates(s);
|
||||
}
|
||||
finishPuertomaPhase(s);
|
||||
if (s.role === "recruiter") fillRegister(s);
|
||||
if (s.role === "trader" && s.trade.length === 4) {
|
||||
for (const g of s.trade) s.supply[g]++;
|
||||
|
|
@ -542,7 +615,10 @@ function checkFestival(s, p, e) {
|
|||
let nw = 0;
|
||||
for (let k = 0; k < (f.reward.workers ?? 0); k++)
|
||||
if (gainPerson(s, p)) nw++;
|
||||
if (nw) s.tasks.unshift({ kind: "bonusAssign", p, remaining: nw });
|
||||
if (nw) {
|
||||
if (a.puertoma) allocatePuertoma(s, p);
|
||||
else s.tasks.unshift({ kind: "bonusAssign", p, remaining: nw });
|
||||
}
|
||||
event(s, "festival", p, { id: f.id, reward: { ...f.reward, workers: nw } });
|
||||
}
|
||||
}
|
||||
|
|
@ -583,8 +659,12 @@ export function shipping(s, p) {
|
|||
function phaseLegal(s, t) {
|
||||
const p = t.p,
|
||||
a = s.players[p];
|
||||
if (a.puertoma) return [P.choice(s, t, puertomaAPI)];
|
||||
const pass = { type: "pass" };
|
||||
switch (t.kind) {
|
||||
case "achievementChoose":
|
||||
case "achievementDraft":
|
||||
return a.achievementOffer.map((id) => ({ type: t.kind, id }));
|
||||
case "role":
|
||||
return s.roles
|
||||
.filter(
|
||||
|
|
@ -755,7 +835,7 @@ function phaseLegal(s, t) {
|
|||
if (total(s.register) > s.players.length) out.push({ type: "poach" });
|
||||
out.push(
|
||||
...s.roles
|
||||
.filter((r) => r.taken === null && r.id !== "smuggler")
|
||||
.filter((r) => !s.puertoma && r.taken === null && r.id !== "smuggler")
|
||||
.map((r) => ({ type: "capture", id: r.id })),
|
||||
);
|
||||
return [...out, pass];
|
||||
|
|
@ -934,6 +1014,11 @@ function settle(s) {
|
|||
if (s.finished || !s.tasks.length) return;
|
||||
const t = s.tasks[0],
|
||||
a = s.players[t.p];
|
||||
if (t.kind === "bonusAssign" && a.puertoma) {
|
||||
allocatePuertoma(s, t.p);
|
||||
s.tasks.shift();
|
||||
continue;
|
||||
}
|
||||
if (t.kind === "phaseEnd") {
|
||||
s.tasks.shift();
|
||||
finishPhase(s);
|
||||
|
|
@ -999,6 +1084,7 @@ function endPoach(s, t) {
|
|||
s.tasks[0] = { kind: "poachDiscard", p: t.p };
|
||||
}
|
||||
export function autoAssignment(s, p) {
|
||||
if (s.players[p].puertoma) return P.allocation(s, p);
|
||||
const a = s.players[p],
|
||||
estates = a.estates.map(() => ({ w: 0, c: 0 })),
|
||||
buildings = a.buildings.map(() => ({ w: 0, c: 0 }));
|
||||
|
|
@ -1055,6 +1141,7 @@ export function autoAssignment(s, p) {
|
|||
return { estates, buildings };
|
||||
}
|
||||
export function autoStorage(s, p) {
|
||||
if (s.players[p].puertoma) return P.storage(s.players[p]);
|
||||
const a = s.players[p],
|
||||
slots =
|
||||
(active(a, "smallWarehouse") ? 1 : 0) +
|
||||
|
|
@ -1104,7 +1191,17 @@ export function move(state, m, p) {
|
|||
const s = clone(state),
|
||||
t = s.tasks[0],
|
||||
a = s.players[p],
|
||||
extra = { phase: t.kind };
|
||||
extra = { phase: t.kind, beforeCoins: s.players[p].coins };
|
||||
if (a.puertoma) {
|
||||
assert(sameMove(P.choice(s, t, puertomaAPI), m));
|
||||
for (let i = 0; i < (m.puertomaDraws ?? 0); i++) drawPuertoma(s);
|
||||
applyPuertoma(s, t, m);
|
||||
s.history.push({ p, move: clone(m) });
|
||||
checkAchievements(s, p, { ...m });
|
||||
settle(s);
|
||||
checkAllAchievements(s);
|
||||
return s;
|
||||
}
|
||||
const custom = {
|
||||
assign: "assign",
|
||||
produce: "produce",
|
||||
|
|
@ -1146,6 +1243,10 @@ export function move(state, m, p) {
|
|||
}
|
||||
const next = () => s.tasks.shift();
|
||||
switch (m.type) {
|
||||
case "achievementChoose":
|
||||
case "achievementDraft":
|
||||
selectAchievement(s, t, m);
|
||||
break;
|
||||
case "role":
|
||||
startRole(s, m.id, p);
|
||||
break;
|
||||
|
|
@ -1155,6 +1256,7 @@ export function move(state, m, p) {
|
|||
if (marketChoices(s).length)
|
||||
s.tasks.unshift({ kind: "draft", p: (p + 1) % s.players.length });
|
||||
else {
|
||||
finishPuertomaSetup(s);
|
||||
setupFestival(s);
|
||||
refillEstates(s);
|
||||
s.tasks = [{ kind: "role", p: s.governor }];
|
||||
|
|
@ -1296,7 +1398,7 @@ export function move(state, m, p) {
|
|||
next();
|
||||
break;
|
||||
case "build": {
|
||||
const price = cost(s, p, m.id),
|
||||
const price = cost(s, p, m.id, m),
|
||||
paid = Math.min(price, a.coins),
|
||||
school = active(a, "school"),
|
||||
church = active(a, "church");
|
||||
|
|
@ -1329,6 +1431,8 @@ export function move(state, m, p) {
|
|||
building: a.buildings.length - 1,
|
||||
});
|
||||
extra.coins = -paid;
|
||||
extra.paid = paid;
|
||||
updateReservations(s, m.id);
|
||||
checkFestival(s, p, { type: "build", id: m.id });
|
||||
break;
|
||||
}
|
||||
|
|
@ -1509,6 +1613,7 @@ export function move(state, m, p) {
|
|||
s.shipPasses++;
|
||||
if (s.shipPasses >= s.players.length) {
|
||||
next();
|
||||
beforePuertomaStorage(s);
|
||||
s.tasks.unshift(...order(s).map((p) => ({ kind: "store", p })));
|
||||
} else t.p = (p + 1) % s.players.length;
|
||||
} else if (t.kind === "poach") endPoach(s, t);
|
||||
|
|
@ -1518,9 +1623,12 @@ export function move(state, m, p) {
|
|||
assert(false);
|
||||
}
|
||||
if (!["role", "plant"].includes(m.type))
|
||||
event(s, m.type, p, { ...m, ...extra });
|
||||
if (!["achievementChoose", "achievementDraft"].includes(m.type))
|
||||
event(s, m.type, p, { ...m, ...extra });
|
||||
s.history.push({ p, move: clone(m) });
|
||||
checkAchievements(s, p, { ...m, ...extra });
|
||||
settle(s);
|
||||
checkAllAchievements(s);
|
||||
return s;
|
||||
}
|
||||
export function currentPlayer(s) {
|
||||
|
|
@ -1534,7 +1642,13 @@ export function ended(s) {
|
|||
}
|
||||
export function scoreBreakdown(s, p) {
|
||||
const a = s.players[p],
|
||||
bonus = {};
|
||||
bonus = a.puertoma ? P.score(a) : {};
|
||||
if (s.expansions.includes("achievements"))
|
||||
bonus.achievements = s.puertoma
|
||||
? a.puertoma
|
||||
? A.incompletePoints(s)
|
||||
: 0
|
||||
: A.points(a);
|
||||
if (active(a, "fireStation"))
|
||||
bonus.fireStation = sum(
|
||||
a.buildings
|
||||
|
|
@ -1587,8 +1701,27 @@ export function stripSecret(state, p) {
|
|||
s.bagCount = s.bag.length;
|
||||
delete s.bag;
|
||||
delete s.discard;
|
||||
if (s.puertoma) {
|
||||
delete s.puertoma.deck;
|
||||
delete s.puertoma.discard;
|
||||
for (const a of s.players)
|
||||
if (a.puertoma)
|
||||
a.puertoma.abilities = a.puertoma.abilities.map((x) =>
|
||||
s.finished || x.active ? x : { level: x.level, active: false },
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < s.players.length; i++)
|
||||
if (i !== p && !s.finished) s.players[i].vp = null;
|
||||
if (i !== p && !s.finished) {
|
||||
s.players[i].vp = null;
|
||||
if (s.players[i].achievements)
|
||||
s.players[i].achievements = s.players[i].achievements.map((c) =>
|
||||
c.completed ? { id: c.id, completed: true } : { hidden: true },
|
||||
);
|
||||
if (s.players[i].achievementOffer)
|
||||
s.players[i].achievementOffer = s.players[i].achievementOffer.map(
|
||||
() => null,
|
||||
);
|
||||
}
|
||||
// Logs contain only public moves; historical earned points are public even though totals are concealed.
|
||||
s.legal = Number.isInteger(p) ? legal(state, p) : [];
|
||||
s.roleWarnings = Number.isInteger(p) ? roleWarnings(state, p) : {};
|
||||
|
|
@ -1739,3 +1872,488 @@ export function chooseAI(s, p = currentPlayer(s)) {
|
|||
export function moveAI(s, p = currentPlayer(s)) {
|
||||
return move(s, chooseAI(s, p), p);
|
||||
}
|
||||
|
||||
function drawPuertoma(s) {
|
||||
if (!s.puertoma.deck.length) {
|
||||
s.puertoma.deck = shuffle(s, s.puertoma.discard);
|
||||
s.puertoma.discard = [];
|
||||
}
|
||||
const card = s.puertoma.deck.pop();
|
||||
s.puertoma.discard.push(card);
|
||||
s.puertoma.lastCard = card;
|
||||
return card;
|
||||
}
|
||||
const puertomaAPI = { draw: drawPuertoma, marketChoices, shipping };
|
||||
function setupPuertoma(s, config) {
|
||||
assert(
|
||||
config && typeof config === "object",
|
||||
"Puertoma configuration requires a human count and difficulty",
|
||||
);
|
||||
const humans = config.humans ?? 1,
|
||||
difficulty = config.difficulty ?? "normal";
|
||||
assert(
|
||||
integer(humans) &&
|
||||
humans >= 1 &&
|
||||
s.players.length - humans >= 1 &&
|
||||
s.players.length - humans <= 2,
|
||||
"Use one or two Puertomas after the human seats",
|
||||
);
|
||||
assert(
|
||||
["easy", "normal", "hard"].includes(difficulty),
|
||||
"Unsupported Puertoma difficulty",
|
||||
);
|
||||
s.puertoma = {
|
||||
humans,
|
||||
difficulty,
|
||||
tracker: "builder",
|
||||
deck: shuffle(s, [1, 2, 3, 4, 5, 6, 7, 8]),
|
||||
discard: [],
|
||||
lastCard: null,
|
||||
setup: false,
|
||||
};
|
||||
for (let p = humans; p < s.players.length; p++) {
|
||||
s.players[p].bot = true;
|
||||
s.players[p].puertoma = {
|
||||
unused: { w: 0, c: 0 },
|
||||
reserved: null,
|
||||
abilities: [1, 2, 3, 4].map((level) => ({
|
||||
level,
|
||||
id: P.ABILITIES[level][Math.floor(rng(s) * 3)],
|
||||
active: difficulty === "hard" && level === 1,
|
||||
})),
|
||||
recruited: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
function finishPuertomaSetup(s) {
|
||||
if (!s.puertoma || s.puertoma.setup) return;
|
||||
s.puertoma.setup = true;
|
||||
if (s.puertoma.difficulty !== "hard") return;
|
||||
for (let p = s.puertoma.humans; p < s.players.length; p++) {
|
||||
const a = s.players[p],
|
||||
n = p - s.puertoma.humans;
|
||||
const choices = Object.keys(s.market).filter(
|
||||
(id) => s.market[id] && !B[id].good && P.level(id) === (n === 0 ? 1 : 2),
|
||||
);
|
||||
assert(choices.length, "No commercial building for Hard Puertoma setup");
|
||||
choices.sort(P.buildingOrder);
|
||||
const id = choices[(drawPuertoma(s) - 1) % choices.length];
|
||||
s.market[id]--;
|
||||
a.buildings.push({ id, w: 0, c: 0, level: P.level(id) });
|
||||
reserveExpanded(s, p);
|
||||
if (n === 0) {
|
||||
gainPerson(s, p);
|
||||
allocatePuertoma(s, p);
|
||||
} else a.coins = 1;
|
||||
const good = n === 0 ? "corn" : "sugar";
|
||||
if (s.supply[good]) {
|
||||
s.supply[good]--;
|
||||
a.goods[good]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
function allocatePuertoma(s, p) {
|
||||
const a = s.players[p],
|
||||
assigned = P.allocation(s, p, () => drawPuertoma(s));
|
||||
a.estates.forEach((t, i) => Object.assign(t, assigned.estates[i]));
|
||||
a.puertoma.unused.w += assigned.unused.w;
|
||||
a.puertoma.unused.c += assigned.unused.c;
|
||||
a.reserve = { w: 0, c: 0 };
|
||||
}
|
||||
function reserveExpanded(s, p) {
|
||||
const a = s.players[p];
|
||||
const taken = s.players
|
||||
.filter((x) => x.puertoma)
|
||||
.map((x) => x.puertoma.reserved);
|
||||
const choices = Object.keys(s.market).filter(
|
||||
(id) =>
|
||||
s.market[id] &&
|
||||
B[id].size === 2 &&
|
||||
!taken.includes(id) &&
|
||||
!a.buildings.some((b) => b.id === id),
|
||||
);
|
||||
choices.sort(P.buildingOrder);
|
||||
a.puertoma.reserved = choices.length
|
||||
? choices[(drawPuertoma(s) - 1) % choices.length]
|
||||
: null;
|
||||
}
|
||||
function updateReservations(s, id) {
|
||||
if (!s.puertoma) return;
|
||||
for (let p = s.puertoma.humans; p < s.players.length; p++)
|
||||
if (s.players[p].puertoma.reserved === id) {
|
||||
s.players[p].puertoma.reserved = null;
|
||||
reserveExpanded(s, p);
|
||||
}
|
||||
}
|
||||
function trackPuertoma(s, role) {
|
||||
if (P.ADJACENCY[s.puertoma.tracker]?.includes(role))
|
||||
s.puertoma.tracker = role;
|
||||
}
|
||||
function gainPuertomaWorker(s, p) {
|
||||
if (gainPerson(s, p)) {
|
||||
s.players[p].puertoma.recruited++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function beforePuertomaStorage(s) {
|
||||
if (!s.puertoma) return;
|
||||
for (let p = s.puertoma.humans; p < s.players.length; p++) {
|
||||
const a = s.players[p];
|
||||
if (P.ability(a, "goodsPoints")) {
|
||||
const points = GOODS.filter((g) => a.goods[g]).length;
|
||||
vp(s, p, points);
|
||||
if (points)
|
||||
event(s, "puertomaBonus", p, { id: "goodsPoints", vp: points });
|
||||
}
|
||||
if (P.ability(a, "discardPoints")) {
|
||||
const good = GOODS.find((g) => a.goods[g]);
|
||||
if (good) {
|
||||
const n = Math.min(2, a.goods[good]);
|
||||
a.goods[good] -= n;
|
||||
s.supply[good] += n;
|
||||
vp(s, p, n);
|
||||
event(s, "puertomaBonus", p, {
|
||||
id: "discardPoints",
|
||||
vp: n,
|
||||
goods: { [good]: -n },
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function finishPuertomaPhase(s) {
|
||||
if (!s.puertoma) return;
|
||||
for (let p = s.puertoma.humans; p < s.players.length; p++) {
|
||||
const a = s.players[p];
|
||||
if (s.role === "craftsman") {
|
||||
if (P.ability(a, "produceCrate")) {
|
||||
const good = [...GOODS]
|
||||
.reverse()
|
||||
.find((g) => s.production[p][g] && s.supply[g]);
|
||||
if (good) {
|
||||
s.supply[good]--;
|
||||
a.goods[good]++;
|
||||
s.production[p][good]++;
|
||||
event(s, "puertomaBonus", p, {
|
||||
id: "produceCrate",
|
||||
goods: { [good]: 1 },
|
||||
});
|
||||
checkFestival(s, p, { type: "produce" });
|
||||
}
|
||||
}
|
||||
if (P.ability(a, "produceCoins")) {
|
||||
const coins = GOODS.filter((g) => s.production[p][g]).length;
|
||||
a.coins += coins;
|
||||
if (coins) event(s, "puertomaBonus", p, { id: "produceCoins", coins });
|
||||
}
|
||||
}
|
||||
if (s.role === "recruiter") {
|
||||
if (P.ability(a, "recruitWorker")) {
|
||||
if (gainPuertomaWorker(s, p))
|
||||
event(s, "puertomaBonus", p, { id: "recruitWorker", workers: 1 });
|
||||
allocatePuertoma(s, p);
|
||||
}
|
||||
if (P.ability(a, "recruitCoins")) {
|
||||
const coins = a.puertoma.recruited;
|
||||
a.coins += coins;
|
||||
if (coins) event(s, "puertomaBonus", p, { id: "recruitCoins", coins });
|
||||
}
|
||||
a.puertoma.recruited = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
function applyPuertoma(s, t, m) {
|
||||
const p = t.p,
|
||||
a = s.players[p],
|
||||
next = () => s.tasks.shift(),
|
||||
extra = { phase: t.kind };
|
||||
switch (m.type) {
|
||||
case "role":
|
||||
startRole(s, m.id, p);
|
||||
if (s.role === "adventurer") trackPuertoma(s, "adventurer");
|
||||
return;
|
||||
case "draft":
|
||||
s.market[m.id] = s.players.length === 2 ? 1 : B[m.id].copies;
|
||||
next();
|
||||
if (marketChoices(s).length)
|
||||
s.tasks.unshift({ kind: "draft", p: (p + 1) % s.players.length });
|
||||
else {
|
||||
finishPuertomaSetup(s);
|
||||
setupFestival(s);
|
||||
refillEstates(s);
|
||||
s.tasks = [{ kind: "role", p: s.governor }];
|
||||
}
|
||||
break;
|
||||
case "plant": {
|
||||
if (m.id === "quarry") s.quarries--;
|
||||
else s.offer.splice(s.offer.indexOf(m.id), 1);
|
||||
next();
|
||||
const vpArea =
|
||||
m.id !== "quarry" &&
|
||||
a.estates.filter((e) => e.id === m.id && !e.vpArea).length >= 2;
|
||||
a.estates.push({
|
||||
id: m.id,
|
||||
w: 0,
|
||||
c: 0,
|
||||
...(vpArea ? { vpArea: true } : {}),
|
||||
});
|
||||
s.planted[p].push(a.estates.length - 1);
|
||||
if (P.ability(a, "plantCrate") && s.supply[m.id]) {
|
||||
s.supply[m.id]--;
|
||||
a.goods[m.id]++;
|
||||
event(s, "puertomaBonus", p, {
|
||||
id: "plantCrate",
|
||||
goods: { [m.id]: 1 },
|
||||
});
|
||||
}
|
||||
event(s, "estate", p, { id: m.id });
|
||||
checkFestival(s, p, { type: "estates" });
|
||||
trackPuertoma(s, "planter");
|
||||
break;
|
||||
}
|
||||
case "build": {
|
||||
const buildWorker = P.ability(a, "buildWorker");
|
||||
const bonus = Number(P.ability(a, "buildCoin"));
|
||||
a.coins += bonus - P.price(s, p, m.id);
|
||||
s.market[m.id]--;
|
||||
a.buildings.push({ id: m.id, w: 0, c: 0, level: m.level });
|
||||
const count = a.buildings.filter((b) => b.level === m.level).length;
|
||||
const unlocked = a.puertoma.abilities.filter((x) => x.active).length;
|
||||
const target = a.puertoma.abilities.find((x) => x.level === m.level);
|
||||
if (
|
||||
target &&
|
||||
!target.active &&
|
||||
(m.level === 4 || count === 2) &&
|
||||
!(s.puertoma.difficulty === "easy" && unlocked >= 2)
|
||||
) {
|
||||
target.active = true;
|
||||
event(s, "puertomaAbility", p, { id: target.id, level: m.level });
|
||||
}
|
||||
if (
|
||||
[1, 2, 3, 4].every(
|
||||
(l) => a.buildings.filter((b) => b.level === l).length === 2,
|
||||
)
|
||||
)
|
||||
s.endReason ??= "city";
|
||||
next();
|
||||
if (buildWorker) {
|
||||
if (gainPuertomaWorker(s, p))
|
||||
event(s, "puertomaBonus", p, { id: "buildWorker", workers: 1 });
|
||||
allocatePuertoma(s, p);
|
||||
}
|
||||
updateReservations(s, m.id);
|
||||
if (
|
||||
!a.puertoma.reserved &&
|
||||
a.buildings.filter((b) => B[b.id].size === 2).length < 2
|
||||
)
|
||||
reserveExpanded(s, p);
|
||||
extra.coins = bonus - P.price(s, p, m.id);
|
||||
checkFestival(s, p, { type: "build", id: m.id });
|
||||
trackPuertoma(s, "builder");
|
||||
break;
|
||||
}
|
||||
case "recruitBonus":
|
||||
gainPuertomaWorker(s, p);
|
||||
if (--t.remaining === 0) next();
|
||||
trackPuertoma(s, "recruiter");
|
||||
break;
|
||||
case "recruit":
|
||||
s.register[m.kind]--;
|
||||
a.reserve[m.kind]++;
|
||||
a.puertoma.recruited++;
|
||||
t.p = (p + 1) % s.players.length;
|
||||
trackPuertoma(s, "recruiter");
|
||||
break;
|
||||
case "assign":
|
||||
a.estates.forEach((estate, i) => Object.assign(estate, m.estates[i]));
|
||||
a.puertoma.unused.w += m.unused.w;
|
||||
a.puertoma.unused.c += m.unused.c;
|
||||
a.reserve = { w: 0, c: 0 };
|
||||
next();
|
||||
break;
|
||||
case "produce":
|
||||
for (const g of GOODS) {
|
||||
a.goods[g] += m.goods[g];
|
||||
s.supply[g] -= m.goods[g];
|
||||
s.production[p][g] += m.goods[g];
|
||||
}
|
||||
next();
|
||||
checkFestival(s, p, { type: "produce" });
|
||||
if (sum(Object.values(m.goods))) trackPuertoma(s, "craftsman");
|
||||
break;
|
||||
case "produceBonus":
|
||||
a.goods[m.good]++;
|
||||
s.supply[m.good]--;
|
||||
s.production[p][m.good]++;
|
||||
if (--t.remaining === 0) next();
|
||||
checkFestival(s, p, { type: "produce" });
|
||||
break;
|
||||
case "trade": {
|
||||
a.goods[m.good]--;
|
||||
s.trade.push(m.good);
|
||||
const coins =
|
||||
GOODS.indexOf(m.good) +
|
||||
Number(s.owner === p) +
|
||||
Number(P.ability(a, "tradeCoin"));
|
||||
a.coins += coins;
|
||||
t.acted = true;
|
||||
extra.coins = coins;
|
||||
checkFestival(s, p, { type: "trade", good: m.good });
|
||||
trackPuertoma(s, "trader");
|
||||
break;
|
||||
}
|
||||
case "ship": {
|
||||
const ship = s.ships[m.ship],
|
||||
n = Math.min(a.goods[m.good], ship.capacity - ship.amount);
|
||||
a.goods[m.good] -= n;
|
||||
ship.good = m.good;
|
||||
ship.amount += n;
|
||||
s.shipped[p][m.good] += n;
|
||||
const advantage = p === s.owner && !s.captainBonus;
|
||||
if (advantage) s.captainBonus = true;
|
||||
vp(s, p, n + Number(advantage));
|
||||
extra.vp = n + Number(advantage);
|
||||
extra.goods = { ...counts(), [m.good]: n };
|
||||
extra.shipCapacity = ship.capacity;
|
||||
extra.shipLoad = ship.amount;
|
||||
t.p = (p + 1) % s.players.length;
|
||||
s.shipPasses = 0;
|
||||
checkFestival(s, p, {
|
||||
type: "ship",
|
||||
good: m.good,
|
||||
capacity: ship.capacity,
|
||||
full: ship.amount === ship.capacity,
|
||||
});
|
||||
trackPuertoma(s, "captain");
|
||||
break;
|
||||
}
|
||||
case "store":
|
||||
for (const g of GOODS) {
|
||||
s.supply[g] += a.goods[g] - m.goods[g];
|
||||
a.goods[g] = m.goods[g];
|
||||
}
|
||||
next();
|
||||
break;
|
||||
case "raid": {
|
||||
const ship = s.ships[m.ship];
|
||||
a.goods[ship.good] += m.amount;
|
||||
s.supply[ship.good] += ship.amount - m.amount;
|
||||
extra.good = ship.good;
|
||||
extra.shipCapacity = ship.capacity;
|
||||
ship.good = null;
|
||||
ship.amount = 0;
|
||||
next();
|
||||
trackPuertoma(s, "smuggler");
|
||||
break;
|
||||
}
|
||||
case "plunder":
|
||||
vp(s, p, s.trade.length);
|
||||
extra.vp = s.trade.length;
|
||||
s.trade.forEach((g) => s.supply[g]++);
|
||||
s.trade = [];
|
||||
next();
|
||||
trackPuertoma(s, "smuggler");
|
||||
break;
|
||||
case "poach":
|
||||
s.discardedPeople ??= { w: 0, c: 0 };
|
||||
s.tasks[0] = {
|
||||
kind: "poach",
|
||||
p,
|
||||
remaining: Math.min(3, total(s.register) - s.players.length),
|
||||
};
|
||||
trackPuertoma(s, "smuggler");
|
||||
break;
|
||||
case "poachWorker":
|
||||
s.register[m.kind]--;
|
||||
tileRef(a, m.target)[m.kind]++;
|
||||
t.remaining--;
|
||||
break;
|
||||
case "discardWorker":
|
||||
s.register[m.kind]--;
|
||||
s.discardedPeople[m.kind]++;
|
||||
break;
|
||||
case "pass":
|
||||
if (t.kind === "ship") {
|
||||
s.shipPasses++;
|
||||
if (s.shipPasses >= s.players.length) {
|
||||
next();
|
||||
beforePuertomaStorage(s);
|
||||
s.tasks.unshift(...order(s).map((p) => ({ kind: "store", p })));
|
||||
} else t.p = (p + 1) % s.players.length;
|
||||
} else if (t.kind === "poach") endPoach(s, t);
|
||||
else next();
|
||||
break;
|
||||
default:
|
||||
assert(false, "Unknown Puertoma action");
|
||||
}
|
||||
event(s, m.type, p, { ...m, ...extra });
|
||||
}
|
||||
|
||||
function setupAchievements(s) {
|
||||
if (!s.expansions.includes("achievements")) return;
|
||||
const cards = shuffle(
|
||||
s,
|
||||
A.ACHIEVEMENTS.map((c) => c.id),
|
||||
);
|
||||
for (const a of s.players) {
|
||||
if (a.puertoma) continue;
|
||||
a.achievements = [];
|
||||
if (s.puertoma) a.achievementOffer = cards.splice(0, 6);
|
||||
else if (s.options.achievementDraft)
|
||||
a.achievementOffer = cards.splice(0, 4);
|
||||
else
|
||||
a.achievements = cards
|
||||
.splice(0, 4)
|
||||
.map((id) => ({ id, completed: false }));
|
||||
}
|
||||
if (s.puertoma || s.options.achievementDraft) {
|
||||
s.setupAfterAchievements = s.tasks;
|
||||
s.tasks = [
|
||||
{ kind: s.puertoma ? "achievementChoose" : "achievementDraft", p: 0 },
|
||||
];
|
||||
}
|
||||
}
|
||||
function selectAchievement(s, t, m) {
|
||||
const a = s.players[t.p];
|
||||
a.achievementOffer.splice(a.achievementOffer.indexOf(m.id), 1);
|
||||
a.achievements.push({ id: m.id, completed: false });
|
||||
const humans = s.puertoma?.humans ?? s.players.length;
|
||||
if (t.kind === "achievementChoose") {
|
||||
if (a.achievements.length < 4) return;
|
||||
delete a.achievementOffer;
|
||||
if (t.p + 1 < humans) {
|
||||
t.p++;
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (t.p + 1 < humans) {
|
||||
t.p++;
|
||||
return;
|
||||
}
|
||||
const offers = s.players.map((a) => a.achievementOffer);
|
||||
if (a.achievements.length < 4) {
|
||||
for (let i = 0; i < humans; i++)
|
||||
s.players[i].achievementOffer = offers[(i - 1 + humans) % humans];
|
||||
t.p = 0;
|
||||
return;
|
||||
}
|
||||
s.players.forEach((a) => delete a.achievementOffer);
|
||||
}
|
||||
s.tasks = s.setupAfterAchievements;
|
||||
delete s.setupAfterAchievements;
|
||||
}
|
||||
function checkAchievements(s, p, e = {}) {
|
||||
const a = s.players[p];
|
||||
for (const c of a.achievements ?? []) {
|
||||
if (!c.completed && A.fulfilled(s, p, c.id, e)) {
|
||||
c.completed = true;
|
||||
c.round = s.round;
|
||||
// No VP tokens are withdrawn: card points are counted only at game end.
|
||||
event(s, "achievement", p, { id: c.id });
|
||||
}
|
||||
}
|
||||
}
|
||||
function checkAllAchievements(s) {
|
||||
s.players.forEach((_, p) => checkAchievements(s, p));
|
||||
}
|
||||
|
|
|
|||
575
engine/puertoma.js
Normal file
575
engine/puertoma.js
Normal file
|
|
@ -0,0 +1,575 @@
|
|||
import { BUILDINGS as B, GOODS } from "./catalog.js";
|
||||
|
||||
// Card orders transcribed from the eight physical tiebreaker cards; terminology
|
||||
// is mapped to the Special Edition (Mayor→Recruiter, Settler→Planter).
|
||||
export const TIEBREAKERS = [
|
||||
[
|
||||
"builder",
|
||||
"recruiter",
|
||||
"craftsman",
|
||||
"trader",
|
||||
"captain",
|
||||
"planter",
|
||||
"adventurer",
|
||||
],
|
||||
[
|
||||
"captain",
|
||||
"trader",
|
||||
"recruiter",
|
||||
"builder",
|
||||
"planter",
|
||||
"adventurer",
|
||||
"craftsman",
|
||||
],
|
||||
[
|
||||
"trader",
|
||||
"craftsman",
|
||||
"recruiter",
|
||||
"builder",
|
||||
"adventurer",
|
||||
"planter",
|
||||
"captain",
|
||||
],
|
||||
[
|
||||
"craftsman",
|
||||
"builder",
|
||||
"recruiter",
|
||||
"adventurer",
|
||||
"trader",
|
||||
"captain",
|
||||
"planter",
|
||||
],
|
||||
[
|
||||
"recruiter",
|
||||
"builder",
|
||||
"adventurer",
|
||||
"captain",
|
||||
"craftsman",
|
||||
"trader",
|
||||
"planter",
|
||||
],
|
||||
[
|
||||
"builder",
|
||||
"adventurer",
|
||||
"recruiter",
|
||||
"trader",
|
||||
"captain",
|
||||
"craftsman",
|
||||
"planter",
|
||||
],
|
||||
[
|
||||
"adventurer",
|
||||
"builder",
|
||||
"recruiter",
|
||||
"captain",
|
||||
"trader",
|
||||
"craftsman",
|
||||
"planter",
|
||||
],
|
||||
[
|
||||
"builder",
|
||||
"captain",
|
||||
"recruiter",
|
||||
"trader",
|
||||
"craftsman",
|
||||
"planter",
|
||||
"adventurer",
|
||||
],
|
||||
];
|
||||
export const ADJACENCY = {
|
||||
builder: ["adventurer", "planter", "trader", "recruiter"],
|
||||
planter: ["adventurer", "builder", "recruiter"],
|
||||
adventurer: ["builder", "planter"],
|
||||
trader: ["builder", "craftsman", "captain", "smuggler"],
|
||||
recruiter: ["trader", "craftsman"],
|
||||
craftsman: ["trader", "captain", "smuggler"],
|
||||
captain: ["trader", "craftsman", "builder", "planter", "smuggler"],
|
||||
smuggler: ["captain", "craftsman", "trader", "builder", "planter"],
|
||||
};
|
||||
export const ABILITIES = {
|
||||
1: ["tradeDuplicate", "tradeCoin", "buildWorker"],
|
||||
2: ["storage", "buildCoin", "produceCrate"],
|
||||
3: ["produceCoins", "recruitWorker", "plantCrate"],
|
||||
4: ["goodsPoints", "discardPoints", "recruitCoins"],
|
||||
};
|
||||
const total = (t) => t.w + t.c;
|
||||
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
|
||||
const counts = () => Object.fromEntries(GOODS.map((g) => [g, 0]));
|
||||
export const estateCapacity = (id) =>
|
||||
({ corn: 1, fruit: 2, sugar: 2, tobacco: 3, coffee: 3 })[id] ?? 0;
|
||||
export const level = (id) => (B[id].size === 2 ? 4 : B[id].vp);
|
||||
export const ability = (a, id) =>
|
||||
a.puertoma?.abilities.some((x) => x.id === id && x.active);
|
||||
export const estateActive = (t) =>
|
||||
!t.vpArea && estateCapacity(t.id) > 0 && total(t) === estateCapacity(t.id);
|
||||
export function production(a) {
|
||||
const out = counts();
|
||||
a.estates.forEach((t) => {
|
||||
if (estateActive(t)) out[t.id]++;
|
||||
});
|
||||
return out;
|
||||
}
|
||||
export function emptyEstateSpaces(a) {
|
||||
return sum(
|
||||
a.estates.map((t) =>
|
||||
Math.max(0, (t.vpArea ? 0 : estateCapacity(t.id)) - total(t)),
|
||||
),
|
||||
);
|
||||
}
|
||||
export function registerDemand(a) {
|
||||
return Math.max(
|
||||
0,
|
||||
...a.estates.map((t) => (t.vpArea ? 0 : estateCapacity(t.id)) - total(t)),
|
||||
);
|
||||
}
|
||||
export function price(s, p, id) {
|
||||
let base = B[id].cost;
|
||||
if (s.options.costSwap) {
|
||||
if (id === "factory") base = 8;
|
||||
if (id === "school") base = 7;
|
||||
}
|
||||
return Math.max(0, base - Number(s.role === "builder" && s.owner === p));
|
||||
}
|
||||
export const buildingOrder = (x, y) =>
|
||||
B[x].cost - B[y].cost || x.localeCompare(y);
|
||||
export function buildings(s, p) {
|
||||
const a = s.players[p];
|
||||
const bonus = Number(ability(a, "buildCoin"));
|
||||
const built = (l) =>
|
||||
a.buildings.filter((b) => (b.level ?? level(b.id)) === l).length;
|
||||
|
||||
const targets = s.festivals
|
||||
.filter((f) => f.claimed === undefined)
|
||||
.map((f) => f.targets.building);
|
||||
return Object.keys(s.market)
|
||||
.sort(buildingOrder)
|
||||
.flatMap((id) => {
|
||||
const b = B[id],
|
||||
natural = level(id);
|
||||
if (
|
||||
!s.market[id] ||
|
||||
b.good ||
|
||||
a.buildings.some((x) => x.id === id) ||
|
||||
price(s, p, id) > a.coins + bonus
|
||||
)
|
||||
return [];
|
||||
let slot = natural;
|
||||
if (targets.includes(id)) while (slot <= 4 && built(slot) >= 2) slot++;
|
||||
if (slot > 4 || built(slot) >= 2) return [];
|
||||
if (
|
||||
slot > natural &&
|
||||
!Object.keys(s.market).some(
|
||||
(other) =>
|
||||
s.market[other] &&
|
||||
!B[other].good &&
|
||||
level(other) === slot &&
|
||||
price(s, p, other) <= a.coins + bonus,
|
||||
)
|
||||
)
|
||||
return [];
|
||||
if (natural === 4 && (a.puertoma.reserved !== id || !a.buildings.length))
|
||||
return [];
|
||||
return [{ type: "build", id, level: slot }];
|
||||
});
|
||||
}
|
||||
function festivalEstates(s) {
|
||||
return [
|
||||
...new Set(
|
||||
s.festivals
|
||||
.filter((f) => f.claimed === undefined)
|
||||
.flatMap((f) => f.targets.estates),
|
||||
),
|
||||
];
|
||||
}
|
||||
function festivalGoods(s) {
|
||||
return [
|
||||
...new Set(
|
||||
s.festivals
|
||||
.filter((f) => f.claimed === undefined)
|
||||
.flatMap((f) => f.targets.goods),
|
||||
),
|
||||
];
|
||||
}
|
||||
export function allocation(s, p, draw) {
|
||||
const a = s.players[p];
|
||||
// Existing workers stay in their slots; unused workers already in the VP area
|
||||
// never return to production. Only newly gained workers are in reserve.
|
||||
const estates = a.estates.map((t) => ({ w: t.w, c: t.c }));
|
||||
let w = a.reserve.w,
|
||||
c = a.reserve.c;
|
||||
while (w + c) {
|
||||
const choices = a.estates
|
||||
.map((t, i) => ({
|
||||
i,
|
||||
id: t.id,
|
||||
empty: (t.vpArea ? 0 : estateCapacity(t.id)) - total(estates[i]),
|
||||
}))
|
||||
.filter((t) => t.empty > 0);
|
||||
if (!choices.length) break;
|
||||
const desired = festivalGoods(s);
|
||||
const matches = choices.filter((x) => desired.includes(x.id));
|
||||
let selected;
|
||||
if (matches.length)
|
||||
selected =
|
||||
matches.length === 1
|
||||
? matches[0]
|
||||
: matches[
|
||||
((draw?.() ?? s.puertoma.lastCard ?? 1) - 1) % matches.length
|
||||
];
|
||||
else
|
||||
selected = choices.sort(
|
||||
(x, y) =>
|
||||
x.empty - y.empty ||
|
||||
GOODS.indexOf(y.id) - GOODS.indexOf(x.id) ||
|
||||
x.i - y.i,
|
||||
)[0];
|
||||
const t = estates[selected.i];
|
||||
for (let n = 0; n < selected.empty && w + c; n++) {
|
||||
if (c) {
|
||||
t.c++;
|
||||
c--;
|
||||
} else {
|
||||
t.w++;
|
||||
w--;
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
estates,
|
||||
buildings: a.buildings.map(() => ({ w: 0, c: 0 })),
|
||||
unused: { w, c },
|
||||
};
|
||||
}
|
||||
export function storage(a) {
|
||||
const types = ability(a, "storage")
|
||||
? [...GOODS]
|
||||
.reverse()
|
||||
.filter((g) => a.goods[g])
|
||||
.slice(0, 1)
|
||||
: [];
|
||||
const goods = counts();
|
||||
types.forEach((g) => (goods[g] = a.goods[g]));
|
||||
const one = [...GOODS]
|
||||
.reverse()
|
||||
.find((g) => a.goods[g] && !types.includes(g));
|
||||
if (one) goods[one] = 1;
|
||||
return { types, goods };
|
||||
}
|
||||
function goodTrade(s, p) {
|
||||
const a = s.players[p];
|
||||
return GOODS.filter(
|
||||
(g) =>
|
||||
a.goods[g] &&
|
||||
s.trade.length < 4 &&
|
||||
(!s.trade.includes(g) || ability(a, "tradeDuplicate")) &&
|
||||
GOODS.indexOf(g) +
|
||||
Number(s.owner === p) +
|
||||
Number(ability(a, "tradeCoin")) >=
|
||||
1,
|
||||
);
|
||||
}
|
||||
function plantOptions(s, p) {
|
||||
const a = s.players[p],
|
||||
desired = festivalEstates(s);
|
||||
const ids = [...new Set(s.offer)].filter(
|
||||
(id) =>
|
||||
a.estates.filter((t) => t.id === id && !t.vpArea).length < 2 ||
|
||||
desired.includes(id),
|
||||
);
|
||||
return [
|
||||
...ids.map((id) => ({ type: "plant", id })),
|
||||
...(s.quarries ? [{ type: "plant", id: "quarry" }] : []),
|
||||
];
|
||||
}
|
||||
function profitable(s, p, id, api) {
|
||||
const preview = {
|
||||
...s,
|
||||
role: id,
|
||||
owner: p,
|
||||
players: s.players.map((a, i) =>
|
||||
i === p
|
||||
? { ...a, coins: a.coins + s.roles.find((r) => r.id === id).coins }
|
||||
: a,
|
||||
),
|
||||
};
|
||||
const a = preview.players[p];
|
||||
if (id === "builder") return buildings(preview, p).length > 0;
|
||||
if (id === "planter") return plantOptions(preview, p).length > 0;
|
||||
if (id === "recruiter") return emptyEstateSpaces(a) > 0;
|
||||
if (id === "craftsman")
|
||||
return GOODS.some((g) => production(a)[g] && !a.goods[g] && s.supply[g]);
|
||||
if (id === "trader") return goodTrade(preview, p).length > 0;
|
||||
if (id === "captain") return api.shipping(preview, p).length > 0;
|
||||
if (id === "smuggler") return smuggleOptions(preview, p).length > 0;
|
||||
return id.startsWith("adventurer");
|
||||
}
|
||||
function smuggleOptions(s, p) {
|
||||
const a = s.players[p],
|
||||
out = [];
|
||||
const surplus = total(s.register) - s.players.length;
|
||||
if (surplus > 0 && emptyEstateSpaces(a) > 0)
|
||||
out.push({
|
||||
type: "poach",
|
||||
gain: Math.min(3, surplus, emptyEstateSpaces(a)),
|
||||
priority: 3,
|
||||
});
|
||||
if (s.trade.length)
|
||||
out.push({ type: "plunder", gain: s.trade.length, priority: 2 });
|
||||
const raids = s.ships
|
||||
.map((sh, ship) => ({ sh, ship }))
|
||||
.filter((x) => x.sh.amount)
|
||||
.sort(
|
||||
(x, y) =>
|
||||
Number(!production(a)[y.sh.good]) - Number(!production(a)[x.sh.good]) ||
|
||||
y.sh.amount - x.sh.amount ||
|
||||
GOODS.indexOf(y.sh.good) - GOODS.indexOf(x.sh.good),
|
||||
);
|
||||
if (raids.length) {
|
||||
const { sh, ship } = raids[0];
|
||||
out.push({
|
||||
type: "raid",
|
||||
ship,
|
||||
amount: Math.min(3, sh.amount),
|
||||
gain: Math.min(3, sh.amount),
|
||||
priority: 1,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Select against a private clone so repeated legal/state queries never consume
|
||||
// randomness. The exact number of card draws is committed when the move executes.
|
||||
export function choice(state, t, api) {
|
||||
const s = structuredClone(state),
|
||||
p = t.p,
|
||||
a = s.players[p];
|
||||
let draws = 0;
|
||||
const card = () => {
|
||||
draws++;
|
||||
return api.draw(s);
|
||||
};
|
||||
const pick = (xs) => (xs.length === 1 ? xs[0] : xs[(card() - 1) % xs.length]);
|
||||
let m = { type: "pass" };
|
||||
switch (t.kind) {
|
||||
case "draft":
|
||||
m = {
|
||||
type: "draft",
|
||||
id: pick(
|
||||
api
|
||||
.marketChoices(s)
|
||||
.map((b) => b.id)
|
||||
.sort(buildingOrder),
|
||||
),
|
||||
};
|
||||
break;
|
||||
case "role": {
|
||||
let roles = s.roles.filter(
|
||||
(r) =>
|
||||
r.taken === null &&
|
||||
(r.id !== "smuggler" || s.smuggler !== p) &&
|
||||
profitable(s, p, r.id, api),
|
||||
);
|
||||
// If no action is profitable, still choose an available legal Role to keep
|
||||
// play progressing; profitability is advice, not an extra end condition.
|
||||
if (!roles.length)
|
||||
roles = s.roles.filter(
|
||||
(r) => r.taken === null && (r.id !== "smuggler" || s.smuggler !== p),
|
||||
);
|
||||
const adjacent = roles.filter((r) =>
|
||||
ADJACENCY[s.puertoma.tracker].includes(r.id.replace(/2$/, "")),
|
||||
);
|
||||
if (adjacent.length) roles = adjacent;
|
||||
const most = Math.max(
|
||||
...roles.map((r) => (r.id === "smuggler" ? 2 : r.coins)),
|
||||
);
|
||||
roles = roles.filter((r) => (r.id === "smuggler" ? 2 : r.coins) === most);
|
||||
let selected = roles.find((r) => r.id === "smuggler");
|
||||
if (!selected)
|
||||
selected =
|
||||
roles.length === 1
|
||||
? roles[0]
|
||||
: TIEBREAKERS[card() - 1].flatMap((id) =>
|
||||
roles.filter((r) => r.id.replace(/2$/, "") === id),
|
||||
)[0];
|
||||
m = { type: "role", id: selected.id };
|
||||
break;
|
||||
}
|
||||
case "plant": {
|
||||
const choices = plantOptions(s, p),
|
||||
desired = festivalEstates(s);
|
||||
let pool = choices.filter((m) => desired.includes(m.id));
|
||||
if (pool.length) m = pick(pool);
|
||||
else {
|
||||
pool = choices.filter(
|
||||
(m) =>
|
||||
festivalGoods(s).includes(m.id) &&
|
||||
!a.estates.some((e) => e.id === m.id),
|
||||
);
|
||||
if (pool.length) m = pick(pool);
|
||||
else
|
||||
m =
|
||||
choices
|
||||
.filter((m) => m.id !== "quarry")
|
||||
.sort(
|
||||
(x, y) =>
|
||||
Number(a.estates.some((e) => e.id === y.id)) -
|
||||
Number(a.estates.some((e) => e.id === x.id)) ||
|
||||
GOODS.indexOf(y.id) - GOODS.indexOf(x.id),
|
||||
)[0] ??
|
||||
choices[0] ??
|
||||
m;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "build": {
|
||||
const choices = buildings(s, p);
|
||||
const desired = s.festivals
|
||||
.filter((f) => f.claimed === undefined)
|
||||
.map((f) => f.targets.building);
|
||||
let pool = choices.filter((m) => desired.includes(m.id));
|
||||
if (pool.length) {
|
||||
const min = Math.min(...pool.map((m) => price(s, p, m.id)));
|
||||
pool = pool.filter((m) => price(s, p, m.id) === min);
|
||||
} else {
|
||||
const highest = Math.max(0, ...choices.map((m) => m.level));
|
||||
pool = choices.filter((m) => m.level === highest);
|
||||
}
|
||||
if (pool.length) m = pick(pool);
|
||||
break;
|
||||
}
|
||||
case "recruitBonus":
|
||||
if (s.workerSupply) m = { type: "recruitBonus" };
|
||||
break;
|
||||
case "recruit":
|
||||
m = { type: "recruit", kind: s.register.c ? "c" : "w" };
|
||||
break;
|
||||
case "assign":
|
||||
m = { type: "assign", ...allocation(s, p, card) };
|
||||
break;
|
||||
case "bonusAssign": {
|
||||
const next = allocation(s, p);
|
||||
const i = next.estates.findIndex((e, i) => e.w > a.estates[i].w);
|
||||
if (i >= 0) m = { type: "bonusAssign", target: `e${i}` };
|
||||
break;
|
||||
}
|
||||
case "produce":
|
||||
m = {
|
||||
type: "produce",
|
||||
goods: Object.fromEntries(
|
||||
GOODS.map((g) => [g, Math.min(production(a)[g], s.supply[g])]),
|
||||
),
|
||||
};
|
||||
break;
|
||||
case "produceBonus": {
|
||||
const good = [...GOODS]
|
||||
.reverse()
|
||||
.find((g) => s.production[p][g] && s.supply[g]);
|
||||
if (good) m = { type: "produceBonus", good };
|
||||
break;
|
||||
}
|
||||
case "trade": {
|
||||
const goods = t.acted ? [] : goodTrade(s, p);
|
||||
const festival = s.festivals.find(
|
||||
(f) =>
|
||||
f.claimed === undefined &&
|
||||
f.goal === "tradeFull" &&
|
||||
s.trade.length === 3 &&
|
||||
goods.includes(f.targets.goods[0]),
|
||||
);
|
||||
const good = festival?.targets.goods[0] ?? goods.at(-1);
|
||||
if (good) m = { type: "trade", good };
|
||||
break;
|
||||
}
|
||||
case "ship": {
|
||||
const moves = api.shipping(s, p).filter((m) => Number.isInteger(m.ship));
|
||||
const ceremony = moves.filter((m) =>
|
||||
s.festivals.some(
|
||||
(f) =>
|
||||
f.claimed === undefined &&
|
||||
["dispatchBig", "dispatchSmall"].includes(f.goal) &&
|
||||
f.targets.goods[0] === m.good &&
|
||||
s.ships[m.ship].capacity ===
|
||||
(f.goal === "dispatchBig"
|
||||
? Math.max(...s.ships.map((x) => x.capacity))
|
||||
: Math.min(...s.ships.map((x) => x.capacity))) &&
|
||||
a.goods[m.good] >=
|
||||
s.ships[m.ship].capacity - s.ships[m.ship].amount,
|
||||
),
|
||||
);
|
||||
const pool = ceremony.length ? ceremony : moves;
|
||||
m =
|
||||
pool.sort(
|
||||
(x, y) =>
|
||||
Math.min(
|
||||
a.goods[y.good],
|
||||
s.ships[y.ship].capacity - s.ships[y.ship].amount,
|
||||
) -
|
||||
Math.min(
|
||||
a.goods[x.good],
|
||||
s.ships[x.ship].capacity - s.ships[x.ship].amount,
|
||||
) ||
|
||||
GOODS.indexOf(x.good) - GOODS.indexOf(y.good) ||
|
||||
s.ships[x.ship].capacity - s.ships[y.ship].capacity,
|
||||
)[0] ?? m;
|
||||
break;
|
||||
}
|
||||
case "store":
|
||||
m = { type: "store", ...storage(a) };
|
||||
break;
|
||||
case "smuggle": {
|
||||
const options = smuggleOptions(s, p).sort(
|
||||
(x, y) =>
|
||||
y.gain - x.gain ||
|
||||
y.priority - x.priority ||
|
||||
Number(!production(a)[s.ships[y.ship]?.good]) -
|
||||
Number(!production(a)[s.ships[x.ship]?.good]) ||
|
||||
(s.ships[y.ship]?.amount ?? 0) - (s.ships[x.ship]?.amount ?? 0) ||
|
||||
GOODS.indexOf(s.ships[y.ship]?.good) -
|
||||
GOODS.indexOf(s.ships[x.ship]?.good),
|
||||
);
|
||||
const selected = options[0];
|
||||
if (selected) {
|
||||
const { gain, priority, ...move } = selected;
|
||||
m = move;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "poach": {
|
||||
const kind = s.register.c ? "c" : "w";
|
||||
const next = allocation(
|
||||
{
|
||||
...s,
|
||||
players: s.players.map((x, i) =>
|
||||
i === p
|
||||
? {
|
||||
...x,
|
||||
reserve: { w: Number(kind === "w"), c: Number(kind === "c") },
|
||||
}
|
||||
: x,
|
||||
),
|
||||
},
|
||||
p,
|
||||
card,
|
||||
);
|
||||
const i = next.estates.findIndex(
|
||||
(e, i) => total(e) > total(a.estates[i]),
|
||||
);
|
||||
if (i >= 0) m = { type: "poachWorker", kind, target: `e${i}` };
|
||||
break;
|
||||
}
|
||||
case "poachDiscard":
|
||||
m = { type: "discardWorker", kind: s.register.w ? "w" : "c" };
|
||||
break;
|
||||
}
|
||||
return draws ? { ...m, puertomaDraws: draws } : m;
|
||||
}
|
||||
export function score(a) {
|
||||
const out = production(a);
|
||||
const bonus = {
|
||||
expanded: a.buildings.filter((b) => B[b.id].size === 2).length * 6,
|
||||
unusedWorkers: total(a.puertoma.unused),
|
||||
quarries: a.estates.filter((t) => t.id === "quarry" || t.vpArea).length * 3,
|
||||
activePairs: GOODS.filter((g) => out[g] >= 2).length * 2,
|
||||
wealth: Math.ceil((a.coins + sum(Object.values(a.goods))) / 2),
|
||||
};
|
||||
return bonus;
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@boardgamers/puerto-rico",
|
||||
"version": "0.1.1",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",
|
||||
|
|
|
|||
|
|
@ -6,8 +6,7 @@ export const MODULES = {
|
|||
smuggler: true,
|
||||
festival: true,
|
||||
"festival-cards": true,
|
||||
// Reserved switch; enabling it is blocked until the complete official deck is verified.
|
||||
achievements: false,
|
||||
achievements: true,
|
||||
};
|
||||
export const RELEASE = {
|
||||
name: "Puerto Rico: Special Edition",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { resolve, join } from "node:path";
|
|||
import { tmpdir } from "node:os";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import assert from "node:assert/strict";
|
||||
import { RELEASE } from "../release-config.js";
|
||||
|
||||
export async function packageEngine() {
|
||||
const { name, version, description } = JSON.parse(
|
||||
|
|
@ -58,7 +59,7 @@ export async function packageEngine() {
|
|||
);
|
||||
for (const players of [2, 3, 4, 5]) {
|
||||
let state = engine.init(players, [], {}, `release-${players}`);
|
||||
assert.equal(state.expansions.length, 5);
|
||||
assert.deepEqual(state.expansions, RELEASE.expansions);
|
||||
let moves = 0;
|
||||
while (!engine.ended(state) && moves++ < 6000)
|
||||
state = engine.moveAI(state);
|
||||
|
|
|
|||
222
test/achievements.test.js
Normal file
222
test/achievements.test.js
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import * as A from "../engine/achievements.js";
|
||||
import { BUILDINGS as B, GOODS } from "../engine/catalog.js";
|
||||
const tile = (id, w = 0, c = 0) => ({ id, w, c });
|
||||
const fresh = () => E.init(3, ["achievements"], {}, "achievement-test");
|
||||
test("the deck has exactly 30 unique, sourced cards and each objective accepts its boundary", () => {
|
||||
assert.equal(A.ACHIEVEMENTS.length, 30);
|
||||
assert.equal(Object.keys(A.CARDS).length, 30);
|
||||
for (const card of A.ACHIEVEMENTS) {
|
||||
const s = fresh(),
|
||||
p = s.players[0];
|
||||
let e = {};
|
||||
assert.equal(A.fulfilled(s, 0, card.id, e), false, card.id + " initially");
|
||||
switch (card.goal) {
|
||||
case "spendAll":
|
||||
e = { type: "build", id: "fireStation", paid: 10, beforeCoins: 10 };
|
||||
break;
|
||||
case "goodsPair":
|
||||
p.goods[card.goods[0]] = card.amount - 1;
|
||||
p.goods[card.goods[1]] = 1;
|
||||
break;
|
||||
case "dispatch":
|
||||
e = {
|
||||
type: "ship",
|
||||
ship: 0,
|
||||
good: card.good,
|
||||
shipLoad: 4,
|
||||
shipCapacity: 4,
|
||||
};
|
||||
break;
|
||||
case "closeTrade":
|
||||
s.owner = 0;
|
||||
s.trade = ["corn", "fruit", "sugar", "coffee"];
|
||||
e = { type: "trade" };
|
||||
break;
|
||||
case "shipTypes":
|
||||
s.role = "captain";
|
||||
s.shipped = [{ corn: 1, fruit: 1, sugar: 1 }];
|
||||
break;
|
||||
case "buildingWorkers":
|
||||
p.buildings = [
|
||||
tile("largeFruit", 3),
|
||||
tile("largeSugar", 3),
|
||||
tile("tobaccoStorage", 3),
|
||||
tile("coffeeRoaster", 2, 1),
|
||||
];
|
||||
break;
|
||||
case "fillShip":
|
||||
e = {
|
||||
type: "ship",
|
||||
ship: 0,
|
||||
good: "corn",
|
||||
goods: { corn: 4 },
|
||||
shipCapacity: 4,
|
||||
};
|
||||
break;
|
||||
case "estateWorkers":
|
||||
p.estates = Array.from({ length: 9 }, () => tile("corn", 1));
|
||||
break;
|
||||
case "produce":
|
||||
s.role = "craftsman";
|
||||
s.production = [{ corn: 7 }];
|
||||
break;
|
||||
case "productionSet":
|
||||
p.buildings = ["smallSugar", "tobaccoStorage", "coffeeRoaster"].map(
|
||||
(id) => tile(id),
|
||||
);
|
||||
break;
|
||||
case "expanded":
|
||||
p.buildings = ["fireStation", "cityHall"].map((id) => tile(id));
|
||||
break;
|
||||
case "developed":
|
||||
p.estates = Array.from({ length: 10 }, () => tile("corn"));
|
||||
p.buildings = Array.from({ length: 5 }, () => tile("fireStation"));
|
||||
break;
|
||||
case "estates":
|
||||
p.estates = Array.from({ length: 12 }, () => tile("corn"));
|
||||
break;
|
||||
case "cheapExpanded":
|
||||
e = { type: "build", id: "fireStation", paid: 6 };
|
||||
break;
|
||||
case "goods":
|
||||
p.goods.corn = 7;
|
||||
break;
|
||||
case "store":
|
||||
p.goods.corn = 1;
|
||||
p.goods.fruit = 1;
|
||||
e = { type: "store" };
|
||||
break;
|
||||
case "commercial":
|
||||
p.buildings = Object.keys(B)
|
||||
.filter((id) => !B[id].good && B[id].size === 1)
|
||||
.slice(0, 7)
|
||||
.map((id) => tile(id));
|
||||
break;
|
||||
case "shipAmount":
|
||||
e = { type: "ship", ship: "wharf", goods: { corn: 5 } };
|
||||
break;
|
||||
case "captainPoints":
|
||||
s.role = "captain";
|
||||
s.phaseVP = [7];
|
||||
break;
|
||||
case "tradeCoins":
|
||||
e = { type: "trade", coins: 6 };
|
||||
break;
|
||||
case "productionCount":
|
||||
p.buildings = ["smallFruit", "largeFruit", "smallSugar"].map((id) =>
|
||||
tile(id),
|
||||
);
|
||||
break;
|
||||
default:
|
||||
assert.fail(card.goal);
|
||||
}
|
||||
assert.equal(A.fulfilled(s, 0, card.id, e), true, card.id + " at boundary");
|
||||
}
|
||||
});
|
||||
test("dispatch, empty-to-full loading, private ships and phase totals remain distinct", () => {
|
||||
const s = fresh();
|
||||
s.role = "captain";
|
||||
const e = {
|
||||
type: "ship",
|
||||
ship: 0,
|
||||
good: "coffee",
|
||||
goods: { coffee: 1 },
|
||||
shipCapacity: 4,
|
||||
shipLoad: 4,
|
||||
};
|
||||
assert.equal(A.fulfilled(s, 0, "coffeeDispatcher", e), true);
|
||||
assert.equal(A.fulfilled(s, 0, "independentShipper", e), false);
|
||||
assert.equal(
|
||||
A.fulfilled(s, 0, "coffeeDispatcher", { ...e, ship: "wharf" }),
|
||||
false,
|
||||
);
|
||||
s.shipped = [{ corn: 1, fruit: 1, sugar: 1 }];
|
||||
s.production = [{ corn: 7 }];
|
||||
s.phaseVP = [7];
|
||||
assert.equal(A.fulfilled(s, 0, "dockTycoon"), true);
|
||||
assert.equal(A.fulfilled(s, 0, "leadingProducer"), false);
|
||||
s.role = "trader";
|
||||
assert.equal(A.fulfilled(s, 0, "dockTycoon"), false);
|
||||
assert.equal(A.fulfilled(s, 0, "tradeStrategist"), false);
|
||||
assert.equal(
|
||||
A.fulfilled(s, 0, "dealCloser", { type: "trade", outpost: true }),
|
||||
false,
|
||||
);
|
||||
});
|
||||
test("dealing and drafting keep opponents objectives out of states, logs and events", () => {
|
||||
for (const options of [
|
||||
{},
|
||||
{ achievementDraft: true },
|
||||
{ puertoma: { humans: 1 } },
|
||||
]) {
|
||||
let s = E.init(3, ["achievements"], options, "secret-deck");
|
||||
const observer = E.stripSecret(s, 1);
|
||||
const initial =
|
||||
s.players[0].achievementOffer ??
|
||||
s.players[0].achievements.map((c) => c.id);
|
||||
for (const id of initial)
|
||||
assert.equal(JSON.stringify(observer).includes(id), false);
|
||||
while (["achievementChoose", "achievementDraft"].includes(s.tasks[0]?.kind))
|
||||
s = E.moveAI(s);
|
||||
for (const p of s.players.filter((p) => !p.puertoma))
|
||||
assert.equal(p.achievements.length, 4);
|
||||
assert.equal(
|
||||
s.events.some((e) =>
|
||||
["achievementChoose", "achievementDraft"].includes(e.type),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(E.replay(s), s);
|
||||
}
|
||||
});
|
||||
test("completing a card reveals it and scores only at game end without VP tokens", () => {
|
||||
let s = fresh();
|
||||
s.players[0].achievements = [{ id: "masterCollector", completed: false }];
|
||||
s.players[0].goods.corn = 7;
|
||||
const before = s.vpSupply;
|
||||
s = E.move(s, { type: "role", id: "planter" }, 0);
|
||||
assert.equal(s.players[0].achievements[0].completed, true);
|
||||
assert.equal(s.vpSupply, before);
|
||||
assert.equal(E.scoreBreakdown(s, 0).bonus.achievements, 7);
|
||||
assert.equal(
|
||||
E.stripSecret(s, 1).players[0].achievements[0].id,
|
||||
"masterCollector",
|
||||
);
|
||||
});
|
||||
test("Big Spender can decline discounts, while arbitrary overpayment is rejected", () => {
|
||||
let s = fresh();
|
||||
s.players[0].coins = 10;
|
||||
s.players[0].estates = Array.from({ length: 4 }, () => tile("quarry", 1));
|
||||
s.players[0].achievements = [
|
||||
{ id: "bigSpender", completed: false },
|
||||
{ id: "masterArchitect", completed: false },
|
||||
];
|
||||
s = E.move(s, { type: "role", id: "builder" }, 0);
|
||||
assert.equal(E.cost(s, 0, "fireStation"), 5);
|
||||
assert(E.legal(s, 0).some((m) => m.id === "fireStation" && m.pay === 10));
|
||||
assert.throws(() =>
|
||||
E.move(s, { type: "build", id: "fireStation", pay: 11 }, 0),
|
||||
);
|
||||
const r = E.move(s, { type: "build", id: "fireStation", pay: 10 }, 0);
|
||||
assert.equal(r.players[0].coins, 0);
|
||||
assert.equal(r.players[0].achievements[0].completed, true);
|
||||
assert.equal(r.players[0].achievements[1].completed, false);
|
||||
});
|
||||
test("Puertoma scores every humans incomplete cards, never the completed cards", () => {
|
||||
const s = E.init(
|
||||
3,
|
||||
["achievements"],
|
||||
{ puertoma: { humans: 1 } },
|
||||
"solo-achievements",
|
||||
);
|
||||
s.players[0].achievements = [
|
||||
{ id: "masterCollector", completed: true },
|
||||
{ id: "bigSpender", completed: false },
|
||||
];
|
||||
assert.equal(E.scoreBreakdown(s, 0).bonus.achievements, 0);
|
||||
assert.equal(E.scoreBreakdown(s, 1).bonus.achievements, 5);
|
||||
assert.equal(E.scoreBreakdown(s, 2).bonus.achievements, 5);
|
||||
});
|
||||
|
|
@ -202,6 +202,50 @@ try {
|
|||
const composer = await page.locator(".chat-composer").boundingBox();
|
||||
assert.ok(composer.y + composer.height <= 844);
|
||||
await page.keyboard.press("Escape");
|
||||
// Achievement selection sends a real legal move; opponents see card backs.
|
||||
let solo = E.init(
|
||||
3,
|
||||
RELEASE.expansions,
|
||||
{ puertoma: { humans: 1 } },
|
||||
"browser-solo",
|
||||
);
|
||||
await page.evaluate((s) => host.emit("state", s), E.stripSecret(solo, 0));
|
||||
assert.equal(await page.locator(".achievement-choices button").count(), 6);
|
||||
await page.locator(".achievement-choices button").first().click();
|
||||
const card = await page.evaluate(() => played.at(-1));
|
||||
assert.equal(card.type, "achievementChoose");
|
||||
solo = E.move(solo, card, 0);
|
||||
while (["achievementChoose", "draft"].includes(solo.tasks[0]?.kind))
|
||||
solo = E.moveAI(solo);
|
||||
await page.evaluate((s) => host.emit("state", s), E.stripSecret(solo, 0));
|
||||
assert.equal(await page.locator(".achievement-card").count(), 4);
|
||||
assert.equal(await overflow(), false, `Achievement layout at ${width}`);
|
||||
await page.locator('[data-player="1"]').click();
|
||||
assert.equal(await page.locator(".puertoma-board").count(), 1);
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".puertoma-board")
|
||||
.innerText()
|
||||
.then((x) => x.includes("Capacité cachée")),
|
||||
true,
|
||||
);
|
||||
assert.equal(await overflow(), false, `Puertoma layout at ${width}`);
|
||||
await page.screenshot({
|
||||
path: `.local/qa/${width}-puertoma.png`,
|
||||
fullPage: true,
|
||||
});
|
||||
await page.evaluate(
|
||||
(s) => host.emit("state", s),
|
||||
E.stripSecret(original, 0),
|
||||
);
|
||||
assert.equal(await page.locator(".achievement-card").count(), 4);
|
||||
assert.equal(
|
||||
await page
|
||||
.locator(".achievements")
|
||||
.innerText()
|
||||
.then((x) => x.includes("Objectif secret")),
|
||||
true,
|
||||
);
|
||||
assert.deepEqual(errors, [], `No browser errors at ${width}`);
|
||||
console.log(
|
||||
`Browser ${width}px: actions, allocation, layout, journal, chat and scrolling OK`,
|
||||
|
|
|
|||
232
test/puertoma.test.js
Normal file
232
test/puertoma.test.js
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import * as E from "../engine/index.js";
|
||||
import * as P from "../engine/puertoma.js";
|
||||
import { BUILDINGS as B, GOODS } from "../engine/catalog.js";
|
||||
import { RELEASE } from "../release-config.js";
|
||||
const fresh = (difficulty = "normal", expansions = []) =>
|
||||
E.init(
|
||||
3,
|
||||
expansions,
|
||||
{ puertoma: { humans: 1, difficulty } },
|
||||
"puertoma-test",
|
||||
);
|
||||
const tile = (id, w = 0, c = 0) => ({ id, w, c });
|
||||
test("physical card orders, directed role links and secret abilities are deterministic", () => {
|
||||
const s = fresh();
|
||||
assert.equal(P.TIEBREAKERS.length, 8);
|
||||
for (const c of P.TIEBREAKERS) assert.equal(new Set(c).size, 7);
|
||||
assert(P.ADJACENCY.builder.includes("recruiter"));
|
||||
assert(!P.ADJACENCY.recruiter.includes("builder"));
|
||||
assert(P.ADJACENCY.trader.includes("smuggler"));
|
||||
assert(!P.ADJACENCY.recruiter.includes("smuggler"));
|
||||
assert.deepEqual(s, fresh());
|
||||
const publicState = E.stripSecret(s, 0);
|
||||
assert.equal(publicState.puertoma.deck, undefined);
|
||||
assert(
|
||||
publicState.players[1].puertoma.abilities.every((x) => x.id === undefined),
|
||||
);
|
||||
const before = structuredClone(s);
|
||||
E.legal(s, 1);
|
||||
assert.deepEqual(s, before);
|
||||
});
|
||||
test("production uses complete estate slots, and workers never move from old estates or VP area", () => {
|
||||
const s = fresh(),
|
||||
a = s.players[1];
|
||||
a.estates = [
|
||||
tile("corn"),
|
||||
tile("fruit", 1),
|
||||
tile("coffee", 2),
|
||||
tile("quarry"),
|
||||
];
|
||||
a.reserve = { w: 2, c: 1 };
|
||||
a.puertoma.unused = { w: 3, c: 1 };
|
||||
const assigned = P.allocation(s, 1);
|
||||
assert.deepEqual(assigned.estates, [
|
||||
{ w: 1, c: 0 },
|
||||
{ w: 2, c: 0 },
|
||||
{ w: 2, c: 1 },
|
||||
{ w: 0, c: 0 },
|
||||
]);
|
||||
a.estates.forEach((t, i) => Object.assign(t, assigned.estates[i]));
|
||||
assert.deepEqual(P.production(a), {
|
||||
corn: 1,
|
||||
fruit: 1,
|
||||
sugar: 0,
|
||||
tobacco: 0,
|
||||
coffee: 1,
|
||||
});
|
||||
assert.equal(P.registerDemand(a), 0);
|
||||
assert.deepEqual(a.puertoma.unused, { w: 3, c: 1 });
|
||||
a.estates = [tile("corn", 1)];
|
||||
a.reserve = { w: 2, c: 0 };
|
||||
assert.deepEqual(P.allocation(s, 1).unused, { w: 2, c: 0 });
|
||||
});
|
||||
test("Puertoma buildings ignore commercial powers, quarry discounts and production buildings", () => {
|
||||
const s = fresh(),
|
||||
a = s.players[1];
|
||||
s.role = "builder";
|
||||
s.owner = 1;
|
||||
a.coins = 10;
|
||||
a.estates = [tile("quarry", 1), tile("quarry", 1)];
|
||||
a.buildings = [{ ...tile("smallMarket"), level: 1 }];
|
||||
assert.equal(P.price(s, 1, "fireStation"), 9);
|
||||
a.puertoma.reserved = "fireStation";
|
||||
assert(P.buildings(s, 1).some((m) => m.id === "fireStation"));
|
||||
assert(!P.buildings(s, 1).some((m) => B[m.id].good));
|
||||
a.buildings.push({ ...tile("hacienda"), level: 1 });
|
||||
assert(!P.buildings(s, 1).some((m) => m.level === 1));
|
||||
});
|
||||
test("hard setup, storage ability and scoring use Puertoma rules", () => {
|
||||
const s = fresh("hard"),
|
||||
a = s.players[1];
|
||||
assert.equal(a.buildings[0].level, 1);
|
||||
assert.equal(s.players[2].buildings[0].level, 2);
|
||||
assert.equal(s.players[2].coins, 1);
|
||||
assert.equal(a.goods.corn, 1);
|
||||
assert.equal(s.players[2].goods.sugar, 1);
|
||||
assert(a.puertoma.abilities.find((x) => x.level === 1).active);
|
||||
assert(a.puertoma.reserved);
|
||||
a.goods = { corn: 3, fruit: 0, sugar: 4, tobacco: 0, coffee: 2 };
|
||||
assert.deepEqual(P.storage(a).goods, {
|
||||
corn: 0,
|
||||
fruit: 0,
|
||||
sugar: 0,
|
||||
tobacco: 0,
|
||||
coffee: 1,
|
||||
});
|
||||
a.puertoma.abilities.push({ id: "storage", active: true });
|
||||
assert.deepEqual(P.storage(a).goods, {
|
||||
corn: 0,
|
||||
fruit: 0,
|
||||
sugar: 1,
|
||||
tobacco: 0,
|
||||
coffee: 2,
|
||||
});
|
||||
a.estates = [tile("coffee", 3), tile("coffee", 3), tile("quarry")];
|
||||
a.buildings = [{ ...tile("fireStation"), level: 4 }];
|
||||
a.puertoma.unused = { w: 2, c: 1 };
|
||||
a.coins = 2;
|
||||
assert.deepEqual(P.score(a), {
|
||||
expanded: 6,
|
||||
unusedWorkers: 3,
|
||||
quarries: 3,
|
||||
activePairs: 2,
|
||||
wealth: 6,
|
||||
});
|
||||
});
|
||||
for (const difficulty of ["easy", "normal", "hard"])
|
||||
test(`${difficulty}: complete Special Edition solo game conserves supplies and replays`, () => {
|
||||
let s = fresh(difficulty, RELEASE.expansions);
|
||||
const initial = structuredClone(s);
|
||||
const sum = (xs) => xs.reduce((a, b) => a + b, 0);
|
||||
const workers = (s, k) =>
|
||||
s[k === "w" ? "workerSupply" : "citizenSupply"] +
|
||||
s.register[k] +
|
||||
(s.discardedPeople?.[k] ?? 0) +
|
||||
sum(
|
||||
s.players.map(
|
||||
(a) =>
|
||||
a.reserve[k] +
|
||||
(a.puertoma?.unused[k] ?? 0) +
|
||||
sum([...a.estates, ...a.buildings].map((t) => t[k])),
|
||||
),
|
||||
);
|
||||
const goods = (s, g) =>
|
||||
s.supply[g] +
|
||||
sum(s.players.map((a) => a.goods[g])) +
|
||||
s.trade.filter((x) => x === g).length +
|
||||
sum(s.ships.map((x) => (x.good === g ? x.amount : 0))) +
|
||||
(s.privateCargo?.[g] ?? 0) +
|
||||
sum(
|
||||
s.festivals
|
||||
.filter((f) => f.claimed === undefined && !f.referenceGoods)
|
||||
.map((f) =>
|
||||
f.targets.goods.reduce((n, x, i) => n + (x === g ? 1 : 0), 0),
|
||||
),
|
||||
);
|
||||
const totals = Object.fromEntries(GOODS.map((g) => [g, goods(s, g)]));
|
||||
const people = { w: workers(s, "w"), c: workers(s, "c") };
|
||||
let turns = 0;
|
||||
while (!s.finished && turns++ < 1500) {
|
||||
const before = structuredClone(s);
|
||||
E.legal(s, E.currentPlayer(s));
|
||||
assert.deepEqual(s, before);
|
||||
s = E.moveAI(s);
|
||||
for (const g of GOODS) {
|
||||
assert(s.supply[g] >= 0);
|
||||
assert.equal(goods(s, g), totals[g], g);
|
||||
}
|
||||
for (const k of ["w", "c"]) assert.equal(workers(s, k), people[k], k);
|
||||
for (const a of s.players.filter((p) => p.puertoma)) {
|
||||
for (const t of a.estates)
|
||||
assert(t.w + t.c <= (t.vpArea ? 0 : P.estateCapacity(t.id)));
|
||||
for (const l of [1, 2, 3, 4])
|
||||
assert(a.buildings.filter((b) => b.level === l).length <= 2);
|
||||
}
|
||||
}
|
||||
assert(s.finished);
|
||||
assert.deepEqual(E.replay(s), s);
|
||||
assert.deepEqual(initial, fresh(difficulty, RELEASE.expansions));
|
||||
for (let p = 0; p < 3; p++)
|
||||
assert(Number.isFinite(E.scoreBreakdown(s, p).total));
|
||||
});
|
||||
test("production abilities run once at phase end and do not require production buildings", () => {
|
||||
let s = fresh(),
|
||||
a = s.players[1];
|
||||
a.estates = [tile("corn", 1), tile("coffee", 3)];
|
||||
a.puertoma.abilities = [
|
||||
{ id: "produceCrate", active: true },
|
||||
{ id: "produceCoins", active: true },
|
||||
];
|
||||
const coins = a.coins;
|
||||
s = E.move(s, { type: "role", id: "craftsman" }, 0);
|
||||
while (s.role === "craftsman") s = E.moveAI(s);
|
||||
assert.equal(s.players[1].goods.corn, 1);
|
||||
assert.equal(s.players[1].goods.coffee, 2);
|
||||
assert.equal(s.players[1].coins, coins + 2);
|
||||
assert.equal(
|
||||
s.events.filter(
|
||||
(e) => e.p === 1 && e.type === "puertomaBonus" && e.id === "produceCrate",
|
||||
).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
test("recruitment abilities count only workers from this Recruiter phase", () => {
|
||||
let s = fresh();
|
||||
s.players[1].puertoma.abilities = [
|
||||
{ id: "recruitWorker", active: true },
|
||||
{ id: "recruitCoins", active: true },
|
||||
];
|
||||
s.players[1].puertoma.recruited = 99;
|
||||
const coins = s.players[1].coins;
|
||||
s = E.move(s, { type: "role", id: "recruiter" }, 0);
|
||||
while (s.role === "recruiter") s = E.moveAI(s);
|
||||
assert.equal(s.players[1].coins, coins + 2);
|
||||
assert.equal(s.players[1].puertoma.recruited, 0);
|
||||
});
|
||||
test("goods scoring abilities resolve before storage and can trigger round-end VP depletion", () => {
|
||||
let s = fresh();
|
||||
s.players[1].goods.corn = 2;
|
||||
s.players[1].goods.coffee = 1;
|
||||
s.players[1].puertoma.abilities = [
|
||||
{ id: "goodsPoints", active: true },
|
||||
{ id: "discardPoints", active: true },
|
||||
];
|
||||
s.ships.forEach((sh) => {
|
||||
sh.good = "sugar";
|
||||
sh.amount = sh.capacity;
|
||||
});
|
||||
s.vpSupply = 1;
|
||||
s = E.move(s, { type: "role", id: "captain" }, 0);
|
||||
while (s.role === "captain" && !s.finished) s = E.moveAI(s);
|
||||
assert.equal(s.players[1].vp, 4);
|
||||
assert.equal(s.players[1].goods.corn, 0);
|
||||
assert.equal(s.players[1].goods.coffee, 1);
|
||||
assert.equal(s.endReason, "points");
|
||||
});
|
||||
test("Capture the Role is disabled for humans in a Puertoma game", () => {
|
||||
let s = fresh("normal", ["smuggler"]);
|
||||
s = E.move(s, { type: "role", id: "smuggler" }, 0);
|
||||
assert(!E.legal(s, 0).some((m) => m.type === "capture"));
|
||||
});
|
||||
120
viewer/achievement-text.js
Normal file
120
viewer/achievement-text.js
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { CARDS } from "../engine/achievements.js";
|
||||
const names = {
|
||||
bigSpender: "Grand dépensier",
|
||||
caramelPopcorn: "Inventeur du popcorn au caramel",
|
||||
coffeeDispatcher: "Expéditeur de café",
|
||||
confectionerySupplier: "Fournisseur de confiseries",
|
||||
cornDispatcher: "Expéditeur de maïs",
|
||||
dealCloser: "Négociateur",
|
||||
dockTycoon: "Magnat des quais",
|
||||
fruitDispatcher: "Expéditeur de fruits",
|
||||
headAdministrator: "Administrateur en chef",
|
||||
independentShipper: "Expéditeur indépendant",
|
||||
leadingEmployer: "Grand employeur",
|
||||
leadingProducer: "Grand producteur",
|
||||
luxuryCropTrader: "Marchand de cultures de luxe",
|
||||
luxuryGoodsProvider: "Fournisseur de produits de luxe",
|
||||
majorInvestor: "Grand investisseur",
|
||||
majorLandowner: "Grand propriétaire",
|
||||
masterAgronomist: "Maître agronome",
|
||||
masterArchitect: "Maître architecte",
|
||||
masterCollector: "Grand collectionneur",
|
||||
pastryMaker: "Pâtissier",
|
||||
prudentMerchant: "Marchand prudent",
|
||||
seniorBureaucrat: "Haut fonctionnaire",
|
||||
specialisedShipper: "Expéditeur spécialisé",
|
||||
sugarDispatcher: "Expéditeur de sucre",
|
||||
tavernSupplier: "Fournisseur de taverne",
|
||||
tobaccoDispatcher: "Expéditeur de tabac",
|
||||
tobaccoFruitBroker: "Courtier en tabac et fruits",
|
||||
tradeStrategist: "Stratège commercial",
|
||||
tradeTycoon: "Magnat du commerce",
|
||||
tropicalProduceMagnate: "Magnat des cultures tropicales",
|
||||
};
|
||||
export function achievementText(id, t) {
|
||||
const c = CARDS[id];
|
||||
if (!c)
|
||||
return { name: t.fr ? "Objectif secret" : "Secret Achievement", text: "" };
|
||||
if (!t.fr) return c;
|
||||
const objectives = {
|
||||
spendAll: "Construire un bâtiment étendu en dépensant toutes vos pièces.",
|
||||
goodsPair: `Posséder au moins ${c.amount} caisses de ${(c.goods ?? []).map(t).join(" et ")} au total, dont au moins une de chaque.`,
|
||||
dispatch: `Placer la dernière caisse de ${t(c.good)} sur un navire de charge et le remplir.`,
|
||||
closeTrade:
|
||||
"Vendre la quatrième marchandise au comptoir en ayant choisi le Marchand.",
|
||||
shipTypes:
|
||||
"Charger au moins 3 marchandises différentes durant une même phase de Capitaine.",
|
||||
buildingWorkers:
|
||||
"Avoir au moins 12 ouvriers ou citoyens sur vos bâtiments.",
|
||||
fillShip: "Remplir un navire de charge vide en une seule action.",
|
||||
estateWorkers:
|
||||
"Avoir au moins 9 ouvriers ou citoyens sur vos tuiles de campagne.",
|
||||
produce: "Produire au moins 7 caisses durant une même phase d’Artisan.",
|
||||
productionSet:
|
||||
"Posséder au moins un bâtiment de production de sucre, de tabac et de café.",
|
||||
expanded: "Posséder au moins 2 bâtiments étendus.",
|
||||
developed:
|
||||
"Avoir au maximum 2 espaces libres dans la campagne et 2 espaces libres dans la ville.",
|
||||
estates: "Posséder 12 tuiles de campagne.",
|
||||
cheapExpanded:
|
||||
"Construire un bâtiment étendu en payant au maximum 6 pièces.",
|
||||
goods: "Posséder au moins 7 caisses d’une même marchandise.",
|
||||
store:
|
||||
"Conserver au moins 2 marchandises différentes à la fin d’une phase de Capitaine.",
|
||||
commercial: "Posséder au moins 7 bâtiments commerciaux ordinaires.",
|
||||
shipAmount:
|
||||
"Charger au moins 5 caisses d’une même marchandise en une seule action.",
|
||||
captainPoints: "Gagner au moins 7 PV durant une même phase de Capitaine.",
|
||||
tradeCoins: "Vendre une marchandise au comptoir pour au moins 6 pièces.",
|
||||
productionCount:
|
||||
"Posséder au moins 3 bâtiments de production de fruits et/ou de sucre.",
|
||||
};
|
||||
return { ...c, name: names[id], text: objectives[c.goal] };
|
||||
}
|
||||
export const abilityTexts = {
|
||||
tradeDuplicate: [
|
||||
"May sell a duplicate Good.",
|
||||
"Peut vendre une marchandise déjà au comptoir.",
|
||||
],
|
||||
tradeCoin: ["+1 Coin per sale.", "+1 pièce par vente."],
|
||||
buildWorker: [
|
||||
"+1 Worker after building.",
|
||||
"+1 ouvrier après une construction.",
|
||||
],
|
||||
storage: [
|
||||
"Store all of the best Good and one other Crate.",
|
||||
"Conserver toutes les caisses de la meilleure marchandise et une autre caisse.",
|
||||
],
|
||||
buildCoin: [
|
||||
"+1 Coin when able to build.",
|
||||
"+1 pièce lorsqu’une construction est possible.",
|
||||
],
|
||||
produceCrate: [
|
||||
"+1 Crate of the best produced Good after production.",
|
||||
"+1 caisse de la meilleure marchandise produite après la production.",
|
||||
],
|
||||
produceCoins: [
|
||||
"+1 Coin per produced Goods type.",
|
||||
"+1 pièce par type de marchandise produit.",
|
||||
],
|
||||
recruitWorker: [
|
||||
"+1 Worker after recruitment.",
|
||||
"+1 ouvrier après le recrutement.",
|
||||
],
|
||||
plantCrate: [
|
||||
"+1 Crate matching a new Estate.",
|
||||
"+1 caisse correspondant à la plantation choisie.",
|
||||
],
|
||||
goodsPoints: [
|
||||
"+1 VP per Goods type before storage.",
|
||||
"+1 PV par type de marchandise avant le stockage.",
|
||||
],
|
||||
discardPoints: [
|
||||
"Discard up to 2 of the worst Good for 1 VP each before storage.",
|
||||
"Défausser jusqu’à 2 caisses de la moins bonne marchandise pour 1 PV chacune avant le stockage.",
|
||||
],
|
||||
recruitCoins: [
|
||||
"+1 Coin per Worker gained during recruitment.",
|
||||
"+1 pièce par ouvrier gagné durant le recrutement.",
|
||||
],
|
||||
};
|
||||
|
|
@ -718,6 +718,28 @@ const rolePrivileges = {
|
|||
"Un rôle capturé rapporte {coin:3} si un autre joueur le choisit ; sinon vous le jouez en fin de tour de table. Un autre joueur doit choisir le Contrebandier avant que vous puissiez le reprendre.",
|
||||
],
|
||||
};
|
||||
Object.assign(labels, {
|
||||
achievements: ["Achievements", "Objectifs"],
|
||||
achievementChoose: ["Choose 4 Achievements", "Choisissez 4 objectifs"],
|
||||
achievementDraft: ["Draft an Achievement", "Choisissez un objectif à passer"],
|
||||
expanded: ["Expanded Building bonuses", "Bonus des bâtiments étendus"],
|
||||
unusedWorkers: ["Unused Workers", "Ouvriers inutilisés"],
|
||||
quarries: ["Quarries", "Carrières"],
|
||||
activePairs: ["Active Estate pairs", "Paires de plantations actives"],
|
||||
wealth: ["Coins and Goods", "Pièces et marchandises"],
|
||||
puertoma: ["Puertoma", "Puertoma"],
|
||||
ability: ["Ability", "Capacité"],
|
||||
secretAbility: ["Hidden ability", "Capacité cachée"],
|
||||
reservedBuilding: ["Reserved Building", "Bâtiment réservé"],
|
||||
achievementHelp: [
|
||||
"Complete your four secret objectives at any point. Completed cards are revealed and score at game end without taking VP tokens.",
|
||||
"Accomplissez vos quatre objectifs secrets à tout moment. Les cartes accomplies sont révélées et rapportent leurs PV en fin de partie, sans prendre de jetons PV.",
|
||||
],
|
||||
puertomaHelp: [
|
||||
"Puertoma uses its own estate slots, permanent workers, building levels and unlocked abilities. Uncompleted human Achievements score for every Puertoma; completed ones score no points for humans.",
|
||||
"Puertoma utilise ses propres emplacements de plantations, ouvriers permanents, niveaux de bâtiments et capacités débloquées. Les objectifs humains non accomplis rapportent leurs PV à chaque Puertoma ; les objectifs accomplis ne rapportent aucun PV aux humains.",
|
||||
],
|
||||
});
|
||||
export function translator(locale = "en") {
|
||||
const fr = locale.toLowerCase().startsWith("fr");
|
||||
const pick = (pair) => pair?.[fr ? 1 : 0] ?? "";
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { achievementText, abilityTexts } from "./achievement-text.js";
|
||||
import { GOODS } from "../engine/catalog.js";
|
||||
import { icon, scoreToken } from "./icons.js";
|
||||
const esc = (value) =>
|
||||
|
|
@ -59,6 +60,15 @@ export function journalContent(state, t, { automatedSetup = false } = {}) {
|
|||
return `<li class="round-divider">${t("finished")} · ${t({ city: "journalEndCity", points: "journalEndPoints", workers: "journalEndWorkers" }[e.reason])}</li>`;
|
||||
let text = "";
|
||||
switch (e.type) {
|
||||
case "achievement":
|
||||
text = `${t("achievements")} · ${esc(achievementText(e.id, t).name)} ${icon("check", 20)}`;
|
||||
break;
|
||||
case "puertomaBonus":
|
||||
text = `${t("ability")} · ${esc(abilityTexts[e.id][t.fr ? 1 : 0])} ${goods(e.goods)} ${e.workers ? metric("worker", e.workers, true) : ""}`;
|
||||
break;
|
||||
case "puertomaAbility":
|
||||
text = `${t("ability")} ${e.level} · ${esc(abilityTexts[e.id][t.fr ? 1 : 0])}`;
|
||||
break;
|
||||
case "income":
|
||||
text = t("journalGains");
|
||||
break;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,14 @@
|
|||
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);
|
||||
const solo = params.get("mode") === "puertoma";
|
||||
const difficulty = ["easy", "normal", "hard"].includes(params.get("difficulty"))
|
||||
? params.get("difficulty")
|
||||
: "normal";
|
||||
const KEY = solo
|
||||
? `puerto-rico-preview-puertoma-${difficulty}-v1`
|
||||
: "puerto-rico-preview-v1";
|
||||
let state,
|
||||
undo = [],
|
||||
generation = 0,
|
||||
|
|
@ -11,10 +17,15 @@ function newGame() {
|
|||
let s = engine.init(
|
||||
3,
|
||||
RELEASE.expansions,
|
||||
RELEASE.options,
|
||||
{
|
||||
...RELEASE.options,
|
||||
...(solo ? { puertoma: { humans: 1, difficulty } } : {}),
|
||||
},
|
||||
`preview-${Date.now()}`,
|
||||
);
|
||||
s.players.forEach((p, i) => (p.name = ["Vous", "Isabel", "Rafael"][i]));
|
||||
if (solo)
|
||||
s.players.slice(1).forEach((p, i) => (p.name = `Puertoma ${i + 1}`));
|
||||
while (s.tasks[0]?.kind === "draft") s = engine.moveAI(s);
|
||||
return s;
|
||||
}
|
||||
|
|
@ -28,6 +39,7 @@ const ui = mountGame(document.getElementById("game"), {
|
|||
async onMove(move) {
|
||||
undo.push(structuredClone(state));
|
||||
state = engine.move(state, move, 0);
|
||||
while (state.tasks[0]?.kind === "draft") state = engine.moveAI(state);
|
||||
display();
|
||||
setTimeout(opponents, 180);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1557,3 +1557,46 @@
|
|||
vertical-align: -2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.achievements,
|
||||
.puertoma-board {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
.achievements p,
|
||||
.puertoma-board p {
|
||||
font-size: 0.85rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.achievements > div,
|
||||
.achievement-choices {
|
||||
display: grid;
|
||||
gap: 0.6rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 200px), 1fr));
|
||||
}
|
||||
.achievement-card {
|
||||
padding: 0.6rem;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 0.4rem;
|
||||
}
|
||||
.achievement-card strong,
|
||||
.achievement-card small,
|
||||
.achievement-choices strong,
|
||||
.achievement-choices small {
|
||||
display: block;
|
||||
}
|
||||
.achievement-card small,
|
||||
.achievement-choices small {
|
||||
white-space: normal;
|
||||
line-height: 1.4;
|
||||
margin-top: 0.4rem;
|
||||
}
|
||||
.achievement-card.completed {
|
||||
border-color: #477347;
|
||||
}
|
||||
.achievement-choices button {
|
||||
height: auto;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
.puertoma-board .metric {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
|
|
|||
42
viewer/ui.js
42
viewer/ui.js
|
|
@ -19,6 +19,8 @@ import { buildingSymbols } from "./building-symbols.js";
|
|||
import { richText } from "./rich-text.js";
|
||||
import { town } from "./town.js";
|
||||
import css from "./style.css";
|
||||
import { achievementText, abilityTexts } from "./achievement-text.js";
|
||||
import { estateCapacity } from "../engine/puertoma.js";
|
||||
|
||||
const esc = (x) =>
|
||||
String(x ?? "").replace(
|
||||
|
|
@ -174,6 +176,8 @@ export function mountGame(
|
|||
const task = state.tasks[0];
|
||||
return t(
|
||||
{
|
||||
achievementChoose: "achievementChoose",
|
||||
achievementDraft: "achievementDraft",
|
||||
role: "chooseRole",
|
||||
draft: "chooseDraft",
|
||||
plant: "choosePlant",
|
||||
|
|
@ -306,6 +310,17 @@ export function mountGame(
|
|||
moves = state.legal.filter(
|
||||
(m) => m.type !== "bohio" && (m.type !== "pass" || m.decline?.length),
|
||||
);
|
||||
if (["achievementChoose", "achievementDraft"].includes(task.kind))
|
||||
return `<p>${t(task.kind)} · ${state.players[seat].achievements.length}/4</p><div class="achievement-choices">${moves
|
||||
.map((m) => {
|
||||
const c = achievementText(m.id, t);
|
||||
return moveButton(
|
||||
m,
|
||||
`<strong>${esc(c.name)}</strong>${metric("vp", c.vp)}<small>${esc(c.text)}</small>`,
|
||||
"check",
|
||||
);
|
||||
})
|
||||
.join("")}</div>`;
|
||||
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}" aria-label="${esc(t(k === "erase" ? "erase" : k === "w" ? "workers" : "citizens"))}" title="${esc(t(k === "erase" ? "erase" : k === "w" ? "workers" : "citizens"))}">${icon(k === "w" ? "worker" : k === "c" ? "citizen" : "erase")}${k === "erase" ? "" : remaining()[k]}</button>`).join("")}<button class="icon-button" data-auto title="${esc(t("autoAssign"))}" aria-label="${esc(t("autoAssign"))}">${icon("autoAssign")}</button><span>${t("workerTool")}</span></div>`;
|
||||
if (task.kind === "store") return storageEditor();
|
||||
|
|
@ -376,7 +391,20 @@ export function mountGame(
|
|||
}
|
||||
function playerBoard() {
|
||||
const a = state.players[view];
|
||||
return `<section class="player-board panel" id="own-board"><header><h2>${playerMarker(view, true)}${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>${pointsBadge(B[x.id].vp)}</button>${peopleSlots(`b${i}`, x, B[x.id].workers)}</article>`).join("")}${a.buildings.length ? "" : `<div class="empty-city">${town}<span>${t("emptyCity")}</span></div>`}</div><button class="mobile-market-launch" data-market>${icon("building")} ${t("market")}</button></section>`;
|
||||
return `<section class="player-board panel" id="own-board"><header><h2>${playerMarker(view, true)}${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.filter((x) => (!x.vpArea && x.id !== "quarry") || !a.puertoma).length}/${a.puertoma ? 10 : 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, a.puertoma ? (x.vpArea ? 0 : estateCapacity(x.id)) : 1) : ""}</article>`).join("")}${Array.from({ length: Math.max(0, (a.puertoma ? 10 : 12) - a.estates.length) }, () => '<span class="estate empty-estate"></span>').join("")}</div><h3>${t("city")} <small>${a.puertoma ? a.buildings.length : citySize(a)}/${a.puertoma ? 8 : 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>${pointsBadge(B[x.id].vp)}</button>${a.puertoma ? `<small>${t.fr ? "Niveau" : "Level"} ${x.level}</small>` : peopleSlots(`b${i}`, x, B[x.id].workers)}</article>`).join("")}${a.buildings.length ? "" : `<div class="empty-city">${town}<span>${t("emptyCity")}</span></div>`}</div>${achievements(a)}${puertomaBoard(a)}<button class="mobile-market-launch" data-market>${icon("building")} ${t("market")}</button></section>`;
|
||||
}
|
||||
function achievements(a) {
|
||||
if (!a.achievements) return "";
|
||||
return `<section class="achievements"><h3>${t("achievements")}</h3><p>${t(state.puertoma ? "puertomaHelp" : "achievementHelp")}</p><div>${a.achievements
|
||||
.map((x) => {
|
||||
const c = achievementText(x.id, t);
|
||||
return `<article class="achievement-card ${x.completed ? "completed" : ""}"><strong>${x.completed ? icon("check", 18) : ""}${esc(c.name)}</strong>${c.vp === undefined ? "" : metric("vp", c.vp)}<small>${esc(c.text)}</small></article>`;
|
||||
})
|
||||
.join("")}</div></section>`;
|
||||
}
|
||||
function puertomaBoard(a) {
|
||||
if (!a.puertoma) return "";
|
||||
return `<section class="puertoma-board"><h3>Puertoma · ${t(state.puertoma.tracker)}</h3><p>${t("puertomaHelp")}</p><div>${metric("worker", a.puertoma.unused.w)}${metric("citizen", a.puertoma.unused.c)}<small>${t("unusedWorkers")}</small></div>${a.puertoma.reserved ? `<p>${t("reservedBuilding")}: ${t(a.puertoma.reserved)}</p>` : ""}${a.puertoma.abilities.map((x) => `<p>${t("ability")} ${x.level} · ${x.active ? icon("check", 18) : ""}${esc(x.id ? abilityTexts[x.id][t.fr ? 1 : 0] : t("secretAbility"))}</p>`).join("")}</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>`;
|
||||
|
|
@ -568,7 +596,7 @@ export function mountGame(
|
|||
);
|
||||
show(
|
||||
t(id),
|
||||
`<div class="building-detail">${icon(spriteFor(id), 56)}<div class="building-detail-stats"><span><small>${t("cost")}</small>${metric("coin", b.cost)}</span><span><small>${t("printedPoints")}</small>${metric("vp", b.vp)}</span><span><small>${t("workerSpaces")}</small>${buildingSlots(b)}</span></div></div><p>${buildingEffect(id, true)}</p>${b.size === 2 ? `<p>${t("twoCitySpaces")}</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>` : ""}`,
|
||||
`<div class="building-detail">${icon(spriteFor(id), 56)}<div class="building-detail-stats"><span><small>${t("cost")}</small>${metric("coin", b.cost)}</span><span><small>${t("printedPoints")}</small>${metric("vp", b.vp)}</span><span><small>${t("workerSpaces")}</small>${buildingSlots(b)}</span></div></div><p>${buildingEffect(id, true)}</p>${b.size === 2 ? `<p>${t("twoCitySpaces")}</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))}${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) {
|
||||
|
|
@ -637,6 +665,16 @@ export function mountGame(
|
|||
adventurer
|
||||
? section("adventurer", "adventurer", paragraph("ruleAdventurer"))
|
||||
: "",
|
||||
hasExpansion("achievements")
|
||||
? section(
|
||||
"vp",
|
||||
"achievements",
|
||||
paragraph(state.puertoma ? "puertomaHelp" : "achievementHelp"),
|
||||
)
|
||||
: "",
|
||||
state.puertoma
|
||||
? section("worker", "puertoma", paragraph("puertomaHelp"))
|
||||
: "",
|
||||
state.festivals.length
|
||||
? section("festival", "festival", paragraph("ruleFestival"))
|
||||
: "",
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue