Warn before choosing roles without an available personal action

This commit is contained in:
coyotte508 2026-10-01 14:25:40 +02:00
commit 228da41e25
9 changed files with 394 additions and 4 deletions

View file

@ -1,6 +1,6 @@
# Puerto Rico: Special Edition
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.0`; 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.1.1`; English and French are configured in the platform metadata.
```sh
pnpm install
@ -33,6 +33,7 @@ The engine accepts the optional `costSwap`, `alternativeStart`, `tailorLimit` an
- 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.
- 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.
- Deterministic ordinary bots for local testing and BGS bot seats.

View file

@ -836,6 +836,99 @@ export function legal(s, p = currentPlayer(s)) {
}
return moves;
}
// Advice is computed before secrets are stripped, using the same action checks
// as play. It never simulates a move, draws a tile, or changes the position.
export function roleWarnings(s, p) {
if (s.finished || s.tasks[0]?.kind !== "role" || s.tasks[0].p !== p)
return {};
const warnings = {};
for (const choice of phaseLegal(s, s.tasks[0])) {
const id = choice.id,
role = s.roles.find((r) => r.id === id);
const a = { ...s.players[p], coins: s.players[p].coins + role.coins };
const preview = {
...s,
role: id,
owner: p,
usedWharves: [],
players: s.players.map((other, i) => (i === p ? a : other)),
};
const can = (kind) =>
phaseLegal(preview, { kind, p, acted: false, zoneUsed: false }).some(
(m) => m.type !== "pass",
);
let reason;
const bonuses = [];
if (id === "craftsman") {
const potential = production(a);
if (!GOODS.some((g) => potential[g] > 0 && s.supply[g] > 0)) {
reason = GOODS.some((g) => potential[g] > 0)
? "warnProductionSupply"
: "warnProductionSetup";
if (active(a, "chapel"))
bonuses.push({
building: "chapel",
[citizen(a, "chapel") ? "vp" : "coins"]: 1,
});
if (active(a, "tailorShop") && citizens(a))
bonuses.push({
building: "tailorShop",
coins: Math.min(citizens(a), s.options.tailorLimit ? 3 : Infinity),
});
}
} else if (id === "builder" && !buildOptions(preview, p).length) {
const funded = {
...preview,
players: preview.players.map((other, i) =>
i === p ? { ...a, coins: Number.MAX_SAFE_INTEGER } : other,
),
};
reason = buildOptions(funded, p).length
? "warnBuildMoney"
: "warnBuildSpace";
} else if (id === "trader" && !can("trade")) {
reason = !GOODS.some((g) => a.goods[g])
? "warnTradeGoods"
: s.trade.length >= 4
? "warnTradeFull"
: "warnTradeTypes";
} else if (id === "captain" && !shipping(preview, p).length) {
// These buildings offer genuine actions before loading, so don't warn
// that the role has no available action when one of them can be used.
const bonusAction =
(active(a, "assemblyHall") && GOODS.some((g) => a.goods[g] >= 2)) ||
(active(a, "pensionOffice") &&
citizens(a) &&
GOODS.some((g) => a.goods[g]));
if (!bonusAction) {
reason = GOODS.some((g) => a.goods[g])
? "warnShipSpace"
: "warnShipGoods";
if (active(a, "lighthouse"))
bonuses.push({ building: "lighthouse", coins: 1 });
}
} else if (
id === "planter" &&
!can("plant") &&
!(active(a, "hacienda") && can("hacienda")) &&
!(active(a, "parkAuthority") && can("park"))
) {
reason = a.estates.length >= 12 ? "warnPlantSpace" : "warnPlantSupply";
} else if (
id === "recruiter" &&
!total(s.register) &&
!s.workerSupply &&
!(active(a, "villa") && s.citizenSupply) &&
!(people(a) && spaces(a))
) {
reason = "warnRecruitSupply";
} else if (id === "smuggler" && !can("smuggle")) {
reason = "warnSmugglerTargets";
}
if (reason) warnings[id] = { reason, coins: role.coins, bonuses };
}
return warnings;
}
function settle(s) {
for (let guard = 0; guard < 200; guard++) {
if (s.finished || !s.tasks.length) return;
@ -1498,6 +1591,7 @@ export function stripSecret(state, p) {
if (i !== p && !s.finished) s.players[i].vp = 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) : {};
s.historyLength = logLength(state);
if (s.finished) s.results = s.players.map((_, i) => scoreBreakdown(state, i));
return s;

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/puerto-rico",
"version": "0.1.0",
"version": "0.1.1",
"private": true,
"type": "module",
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",

View file

@ -51,6 +51,33 @@ try {
() => document.documentElement.scrollWidth > innerWidth + 1,
);
assert.equal(await overflow(), false, `No page overflow at ${width}`);
const craftsman = page.locator('[data-role-id="craftsman"]');
assert.equal(await craftsman.locator(".role-warning").count(), 1);
await craftsman.click();
assert.equal(await page.locator("[data-confirm-role]").count(), 1);
assert.deepEqual(await page.evaluate(() => played), []);
await page.locator(".modal-body [data-close]").click();
assert.deepEqual(await page.evaluate(() => played), []);
await craftsman.click();
// A newer game state invalidates an open warning; it must not send a stale choice.
await page.evaluate(
(s) => host.emit("state", s),
E.stripSecret(E.move(original, { type: "role", id: "planter" }, 0), 0),
);
assert.equal(await page.locator("dialog[open]").count(), 0);
await page.evaluate(
(s) => host.emit("state", s),
E.stripSecret(original, 0),
);
await craftsman.click();
await page.locator("[data-confirm-role]").click();
assert.deepEqual(await page.evaluate(() => played), [
{ type: "role", id: "craftsman" },
]);
await page.evaluate(
(s) => host.emit("state", s),
E.stripSecret(original, 0),
);
await page.locator('[data-panel="rules"]').click();
assert.equal(await page.locator("dialog[open]").count(), 1);
await page.keyboard.press("Escape");

125
test/role-warnings.test.js Normal file
View file

@ -0,0 +1,125 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as E from "../engine/index.js";
const fresh = () => E.init(3, [], {}, "role-warnings");
const tile = (id, w = 1, c = 0) => ({ id, w, c });
test("initial warnings are advisory, private to the chooser and do not mutate state", () => {
const s = fresh(),
before = structuredClone(s),
w = E.roleWarnings(s, 0);
assert.deepEqual(Object.keys(w).sort(), ["captain", "craftsman", "trader"]);
assert.equal(
E.move(s, { type: "role", id: "craftsman" }, 0).role,
"craftsman",
);
assert.deepEqual(s, before);
assert.deepEqual(E.stripSecret(s, 0).roleWarnings, w);
assert.deepEqual(E.stripSecret(s, 1).roleWarnings, {});
assert.deepEqual(E.stripSecret(s).roleWarnings, {});
});
test("production checks occupancy, the corn exception and depleted supply", () => {
const s = fresh(),
p = s.players[0];
p.estates = [tile("fruit")];
p.buildings = [tile("smallFruit", 0)];
assert.equal(E.roleWarnings(s, 0).craftsman.reason, "warnProductionSetup");
p.buildings[0].w = 1;
assert.equal(E.roleWarnings(s, 0).craftsman, undefined);
s.supply.fruit = 0;
assert.equal(E.roleWarnings(s, 0).craftsman.reason, "warnProductionSupply");
p.estates = [tile("corn")];
p.buildings = [];
assert.equal(E.roleWarnings(s, 0).craftsman, undefined);
});
test("production-independent rewards match the actual gains even when passing", () => {
const s = fresh(),
p = s.players[0];
s.roles.find((r) => r.id === "craftsman").coins = 3;
p.buildings = [tile("chapel", 0, 1), tile("tailorShop")];
const w = E.roleWarnings(s, 0).craftsman;
assert.equal(w.coins, 3);
assert.deepEqual(w.bonuses, [
{ building: "chapel", vp: 1 },
{ building: "tailorShop", coins: 1 },
]);
let next = E.move(s, { type: "role", id: "craftsman" }, 0);
next = E.move(next, { type: "pass" }, 0);
assert.equal(next.players[0].coins - p.coins, 4);
assert.equal(next.players[0].vp - p.vp, 1);
});
test("Builder includes incoming coins, privilege, and alternative payment methods", () => {
const s = fresh(),
p = s.players[0];
s.market = { largeSugar: 1 };
p.coins = 0;
assert.equal(E.roleWarnings(s, 0).builder.reason, "warnBuildMoney");
s.roles.find((r) => r.id === "builder").coins = 3;
assert.equal(E.roleWarnings(s, 0).builder, undefined);
s.roles.find((r) => r.id === "builder").coins = 0;
p.buildings = [tile("hiddenMarket")];
p.reserve.w = 1;
p.goods.corn = 1;
p.vp = 1;
assert.equal(E.roleWarnings(s, 0).builder, undefined);
p.buildings.push(tile("largeSugar"));
assert.equal(E.roleWarnings(s, 0).builder.reason, "warnBuildSpace");
});
test("Trader respects the Office, Outpost and Zoning Office", () => {
const s = fresh(),
p = s.players[0];
p.goods.corn = 1;
s.trade = ["corn"];
assert.equal(E.roleWarnings(s, 0).trader.reason, "warnTradeTypes");
p.buildings = [tile("office")];
assert.equal(E.roleWarnings(s, 0).trader, undefined);
s.trade = ["corn", "fruit", "sugar", "coffee"];
assert.equal(E.roleWarnings(s, 0).trader.reason, "warnTradeFull");
p.buildings = [tile("merchantOutpost")];
assert.equal(E.roleWarnings(s, 0).trader, undefined);
p.goods.corn = 0;
p.buildings = [tile("zoningOffice")];
assert.equal(E.roleWarnings(s, 0).trader, undefined);
});
test("Captain resets private ship use and respects alternate scoring actions", () => {
const s = fresh(),
p = s.players[0];
p.goods.corn = 2;
s.ships.forEach((sh, i) => {
sh.good = ["corn", "fruit", "sugar"][i];
sh.amount = sh.capacity;
});
assert.equal(E.roleWarnings(s, 0).captain.reason, "warnShipSpace");
p.buildings = [tile("wharf")];
s.usedWharves = ["0:wharf"];
assert.equal(E.roleWarnings(s, 0).captain, undefined);
p.buildings = [tile("assemblyHall")];
assert.equal(E.roleWarnings(s, 0).captain, undefined);
p.goods.corn = 1;
p.buildings = [tile("pensionOffice", 0, 1)];
assert.equal(E.roleWarnings(s, 0).captain, undefined);
p.goods.corn = 0;
p.buildings = [tile("lighthouse")];
assert.deepEqual(E.roleWarnings(s, 0).captain.bonuses, [
{ building: "lighthouse", coins: 1 },
]);
});
test("full countryside and empty recruitment supply allow building powers and reassignment", () => {
const s = fresh(),
p = s.players[0];
p.estates = Array.from({ length: 12 }, () => tile("fruit", 0));
assert.equal(E.roleWarnings(s, 0).planter.reason, "warnPlantSpace");
p.buildings = [tile("parkAuthority")];
assert.equal(E.roleWarnings(s, 0).planter, undefined);
p.buildings = [];
s.register = { w: 0, c: 0 };
s.workerSupply = 0;
assert.equal(E.roleWarnings(s, 0).recruiter.reason, "warnRecruitSupply");
p.reserve.w = 1;
assert.equal(E.roleWarnings(s, 0).recruiter, undefined);
});
test("Smuggler can capture roles on an empty board, Adventurer still earns money", () => {
const s = E.init(4, ["smuggler"], {}, "warnings");
assert.equal(E.roleWarnings(s, 0).smuggler, undefined);
assert.equal(E.roleWarnings(s, 0).adventurer, undefined);
});

View file

@ -107,6 +107,73 @@ const labels = {
waiting: ["Waiting for", "Au tour de"],
yourTurn: ["Your turn", "À vous"],
chooseRole: ["Choose a role", "Choisissez un rôle"],
roleWarningTitle: ["Before choosing this role", "Avant de choisir ce rôle"],
chooseRoleAnyway: ["Choose anyway", "Choisir quand même"],
chooseAnotherRole: ["Choose another role", "Choisir un autre rôle"],
roleCoinsStill: [
"Coins collected from the role",
"Pièces récupérées sur le rôle",
],
roleBonusesStill: [
"Building bonuses still apply",
"Bonus de bâtiments conservés",
],
roleWarningOthers: [
"Other players can still use this role if able.",
"Les autres joueurs pourront utiliser ce rôle s’ils le peuvent.",
],
warnProductionSetup: [
"You cannot produce any {crates} yet. Your estate and its matching production building must be occupied. {corn} only needs an occupied estate.",
"Vous ne pouvez produire aucune {crate}. Le domaine et son bâtiment de production doivent être occupés. Le {corn} n’a besoin que d’un domaine occupé.",
],
warnProductionSupply: [
"The supply has no {crates} of the types you can produce.",
"La réserve ne contient plus de {crates} des types que vous pouvez produire.",
],
warnBuildMoney: [
"You cannot afford a building, even with the role’s {coins}, your discounts and payment bonuses.",
"Vous ne pouvez financer aucun bâtiment, même avec les {coins} du rôle, vos réductions et vos bonus de paiement.",
],
warnBuildSpace: [
"No available building can be added to your city: check free spaces and buildings you already own.",
"Aucun bâtiment disponible ne peut être ajouté à votre ville : vérifiez les cases libres et les bâtiments déjà possédés.",
],
warnTradeGoods: [
"You have no {crates} to sell.",
"Vous n’avez aucune {crate} à vendre.",
],
warnTradeFull: [
"The trading house is full. You cannot sell any goods.",
"Le marché est plein. Vous ne pouvez vendre aucune marchandise.",
],
warnTradeTypes: [
"The trading house already contains every type you could sell.",
"Le marché contient déjà chacun des types que vous pourriez vendre.",
],
warnShipGoods: [
"You have no {crates} to load.",
"Vous n’avez aucune {crate} à charger.",
],
warnShipSpace: [
"No ship can accept your {crates} right now.",
"Aucun bateau ne peut accueillir vos {crates} actuellement.",
],
warnPlantSpace: [
"Your countryside already fills all 12 spaces. You cannot take another estate.",
"Vos 12 cases de campagne sont occupées. Vous ne pouvez prendre aucun domaine supplémentaire.",
],
warnPlantSupply: [
"No estate or {quarry} is available for you to take.",
"Aucun domaine ni aucune {quarry} ne sont disponibles pour vous.",
],
warnRecruitSupply: [
"Neither recruitment nor worker reassignment is possible for you.",
"Ni recrutement ni réaffectation d’ouvriers ne sont possibles pour vous.",
],
warnSmugglerTargets: [
"There is nothing to raid, plunder or poach, and no role left to capture.",
"Aucun pillage ni débauchage n’est possible, et il ne reste aucun rôle à capturer.",
],
chooseDraft: [
"Choose a building for the shared market",
"Choisissez un bâtiment pour le marché commun",

View file

@ -55,6 +55,8 @@ const paths = {
governor:
'<path fill="#d8ba65" d="m2 6 5 4 5-8 5 8 5-4-3 13H5Z"/><path d="M5 22h14"/>',
help: '<path d="M8 8a4 4 0 1 1 7 3c-2 1-3 2-3 5"/><circle cx="12" cy="21" r="1" fill="currentColor" stroke="none"/>',
warning:
'<path fill="#ddb568" stroke="#614625" d="M12 2 23 21H1Z"/><path stroke="#49351e" stroke-width="2" d="M12 8v6m0 3v.5"/>',
rules:
'<path d="M12 5C8 2 4 2 1 4v17c3-2 7-2 11 1 4-3 8-3 11-1V4c-3-2-7-2-11 1Zm0 0v17"/>',
journal: '<path d="M5 2h16v20H5ZM1 6h7M1 12h7M1 18h7m2-10h8m-8 5h8m-8 5h5"/>',

View file

@ -416,6 +416,35 @@
position: relative;
display: flex;
}
.pr-game .role-warning {
position: absolute;
top: 4px;
left: 4px;
line-height: 0;
}
.pr-game .role .role-warning .icon {
width: 15px;
height: 15px;
}
.pr-game .role-warning-heading,
.pr-game .role-warning-gain,
.pr-game .role-warning-bonuses > div {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.pr-game .role-warning-heading {
font-size: 18px;
}
.pr-game .role-warning-bonuses {
display: grid;
gap: 6px;
}
.pr-game .role-warning-note {
color: var(--muted);
font-size: 12px;
}
.pr-game .coin-badge {
position: absolute;
right: -12px;

View file

@ -63,6 +63,7 @@ export function mountGame(
tool = "w",
lastFocus,
modalMode = "",
roleConfirmation = null,
scrollLog = 0;
const metric = (id, n) =>
id === "vp"
@ -132,6 +133,7 @@ export function mountGame(
}
function hide(d) {
d.close();
if (d === modal) roleConfirmation = null;
if (d === chatDialog) chat?.setOpen(false);
lastFocus?.focus?.();
}
@ -366,8 +368,9 @@ export function mountGame(
return `<section class="shared-board"><div class="roles">${state.roles
.map((r) => {
const m = state.legal.find((m) => m.type === "role" && m.id === r.id),
selected = r.taken !== null;
return `<button data-role-id="${r.id}" class="role ${selected ? "taken" : ""} ${m ? "available" : ""}" ${selected ? `title="${esc(t(r.id))} · ${esc(state.players[r.taken].name)}"` : ""} ${m && acting ? `data-move="${encode(m)}"` : `data-role="${r.id}"`}><span class="role-icon">${icon(r.id === "adventurer2" ? "adventurer" : r.id, 32)}${r.coins ? `<span class="coin-badge">${r.coins}</span>` : ""}</span><b>${t(r.id)}</b>${selected ? playerMarker(r.taken) : ""}</button>`;
selected = r.taken !== null,
warning = m && acting ? state.roleWarnings?.[r.id] : null;
return `<button data-role-id="${r.id}" class="role ${selected ? "taken" : ""} ${m ? "available" : ""}" ${selected ? `title="${esc(t(r.id))} · ${esc(state.players[r.taken].name)}"` : warning ? `title="${esc(t(warning.reason))}" aria-label="${esc(t(r.id))} — ${esc(t(warning.reason))}"` : ""} ${m && acting ? `data-move="${encode(m)}"` : `data-role="${r.id}"`}>${warning ? `<span class="role-warning" aria-hidden="true">${icon("warning", 15)}</span>` : ""}<span class="role-icon">${icon(r.id === "adventurer2" ? "adventurer" : r.id, 32)}${r.coins ? `<span class="coin-badge">${r.coins}</span>` : ""}</span><b>${t(r.id)}</b>${selected ? playerMarker(r.taken) : ""}</button>`;
})
.join(
"",
@ -475,6 +478,16 @@ export function mountGame(
function render(s) {
if (s) state = s;
if (!state) return;
if (
roleConfirmation &&
(!enabled ||
seat !== roleConfirmation.seat ||
state.historyLength !== roleConfirmation.historyLength ||
!state.legal.some(
(m) => m.type === "role" && m.id === roleConfirmation.move.id,
))
)
hide(modal);
view = Math.min(view, state.players.length - 1);
draftInit();
shell.classList.toggle(
@ -499,6 +512,25 @@ export function mountGame(
const privilege = t.rolePrivilege(id);
return `<article class="role-reference"><h3>${icon(id.startsWith("adventurer") ? "adventurer" : id, 32)}${t(id)}</h3><div><small>${t(solo ? "chooserOnly" : "everyone")}</small><p>${t.roleActionHtml(id)}</p></div>${privilege ? `<div class="role-privilege"><small>${t(solo ? "roleNote" : "privilege")}</small><p>${t.rolePrivilegeHtml(id)}</p></div>` : ""}</article>`;
}
function confirmRole(m) {
const warning = state.roleWarnings?.[m.id];
if (!warning) return false;
show(
t("roleWarningTitle"),
`
<div class="role-warning-heading">${icon(m.id, 36)}<strong>${t(m.id)}</strong></div>
<p>${t.html(warning.reason)}</p>
${warning.coins ? `<p class="role-warning-gain">${t("roleCoinsStill")} ${metric("coin", warning.coins)}</p>` : ""}
${warning.bonuses.length ? `<div class="role-warning-bonuses"><small>${t("roleBonusesStill")}</small>${warning.bonuses.map((b) => `<div>${t(b.building)} ${b.coins ? metric("coin", b.coins) : ""}${b.vp ? metric("vp", b.vp) : ""}</div>`).join("")}</div>` : ""}
${m.id !== "smuggler" ? `<p class="role-warning-note">${t("roleWarningOthers")}</p>` : ""}
<div class="action-choices"><button type="button" class="primary" data-close>${t("chooseAnotherRole")}</button><button type="button" data-confirm-role>${t("chooseRoleAnyway")}</button></div>
`,
"role-warning",
);
roleConfirmation = { move: m, seat, historyLength: state.historyLength };
body.querySelector("[data-close]").focus();
return true;
}
function rolesHelp() {
const roles = [
...new Set(
@ -690,8 +722,21 @@ export function mountGame(
)
)
return;
if (el.hasAttribute("data-confirm-role")) {
const confirmation = roleConfirmation;
if (
!confirmation ||
confirmation.historyLength !== state.historyLength ||
confirmation.seat !== seat
)
return;
hide(modal);
send(confirmation.move);
return;
}
if (el.dataset.move) {
const m = JSON.parse(decodeURIComponent(el.dataset.move));
if (m.type === "role" && confirmRole(m)) return;
if (["smallWharf", "produce"].includes(m.type)) {
cargoDialog(m);
return;