Add curated Puerto Rico platform achievement hooks

This commit is contained in:
coyotte508 2026-11-14 01:18:54 +00:00
commit 95ffaa42e8
8 changed files with 474 additions and 9 deletions

177
bgs/achievements.js Normal file
View file

@ -0,0 +1,177 @@
// Platform badges, deliberately separate from the physical Achievement cards.
import { scoreBreakdown } from "../engine/index.js";
import { BUILDINGS, GOODS, ROLES } from "../engine/catalog.js";
/** @type {import('@boardgamers/protocol/engine').AchievementManifest} */
const manifest = {
revision: 1,
achievements: [
["island-victory", "Island victory", "Win a multiplayer game outright."],
...["easy", "normal", "hard"].map((level) => [
`puertoma-${level}`,
`Puertoma: ${level}`,
`Win outright against both Puertomas on ${level} difficulty.`,
]),
[
"all-festival-objectives",
"Festival sweep",
"Finish having personally claimed every active Festival objective (at least one).",
],
[
"all-personal-achievements",
"Personal perfection",
"Finish with every card in your active personal Achievement set completed (at least one).",
],
[
"festival-claim",
"Festival participant",
"Finish having claimed at least one Festival objective.",
],
[
"personal-achievement",
"Personal milestone",
"Finish with at least one completed personal Achievement card.",
],
["fifty-points", "Fifty points", "Finish with at least 50 total points."],
[
"seventy-points",
"Seventy points",
"Finish with at least 70 total points.",
],
["full-city", "Full city", "Finish with all 12 city spaces built."],
[
"full-island",
"Full island",
"Finish with all 12 island spaces occupied.",
],
[
"expanded-city",
"Expanded city",
"Finish with at least two expanded (two-space) buildings.",
],
[
"five-crop-estates",
"Five-crop estates",
"Finish owning an estate for each of the five crops.",
],
["twenty-coins", "Treasury", "Finish with at least 20 coins."],
[
"six-core-roles",
"Versatile governor",
"Choose each of the six core roles at least once in a completed game.",
],
].map(([id, name, description]) => ({ id, name, description })),
};
/** @returns {import('@boardgamers/protocol/engine').AchievementManifest} */
export function achievementDefinitions() {
return structuredClone(manifest);
}
/** @returns {import('@boardgamers/protocol/engine').SeatAchievements[]} */
export function achievements(s) {
// Cancellation/practice eligibility also belongs to the platform: its metadata
// is not passed to this hook. Tutorial and analysis are engine-owned markers.
if (
!s ||
s.finished !== true ||
s.tutorial ||
s.analysis ||
s.practice ||
s.cancelled ||
s.canceled ||
!["points", "workers", "city"].includes(s.endReason) ||
!Array.isArray(s.tasks) ||
s.tasks.length ||
!Array.isArray(s.players) ||
s.players.length < 2 ||
!Array.isArray(s.expansions)
)
return [];
const totals = s.players.map((_, seat) => scoreBreakdown(s, seat));
if (totals.some((v) => !Number.isFinite(v.total) || !Number.isFinite(v.tie)))
return [];
const solo = s.options?.hostedSolo === true;
if (
solo &&
(!s.puertoma ||
s.players.length !== 3 ||
s.players[0].puertoma ||
!s.players.slice(1).every((p) => p.puertoma))
)
return [];
const festival = s.expansions.some((x) =>
["festival", "festival-cards"].includes(x),
);
return s.players.flatMap((a, seat) => {
if (solo && seat !== 0) return [];
const value = totals[seat];
const better = totals.some(
(v) =>
v.total > value.total || (v.total === value.total && v.tie > value.tie),
);
const tied = totals.some(
(v, i) => i !== seat && v.total === value.total && v.tie === value.tie,
);
const outcome = better ? "loss" : tied ? "draw" : "win";
const earned = [];
const award = (id, condition) => {
if (condition) earned.push(id);
};
award("island-victory", !s.puertoma && outcome === "win");
for (const level of ["easy", "normal", "hard"])
award(
`puertoma-${level}`,
solo && s.puertoma.difficulty === level && outcome === "win",
);
const festivals = festival ? (s.festivals ?? []) : [];
const cards = s.expansions.includes("achievements")
? (a.achievements ?? [])
: [];
award(
"all-festival-objectives",
festivals.length > 0 && festivals.every((f) => f.claimed === seat),
);
award(
"all-personal-achievements",
cards.length > 0 && cards.every((c) => c.completed === true),
);
award(
"festival-claim",
festivals.some((f) => f.claimed === seat),
);
award(
"personal-achievement",
cards.some((c) => c.completed === true),
);
award("fifty-points", value.total >= 50);
award("seventy-points", value.total >= 70);
award(
"full-city",
a.buildings.reduce((n, b) => n + BUILDINGS[b.id].size, 0) === 12,
);
award("full-island", a.estates.length === 12);
award(
"expanded-city",
a.buildings.filter((b) => BUILDINGS[b.id].size === 2).length >= 2,
);
award(
"five-crop-estates",
GOODS.every((g) => a.estates.some((e) => e.id === g)),
);
award("twenty-coins", a.coins >= 20);
const roles = new Set(
(s.history ?? [])
.filter((h) => h.p === seat && h.move.type === "role")
.map((h) => h.move.id),
);
award(
"six-core-roles",
ROLES.every((r) => roles.has(r)),
);
return [{ seat, earned, outcome }];
});
}
/** @type {Pick<import('@boardgamers/protocol/engine').Engine, 'achievementDefinitions' | 'achievements'>} */
export const achievementHooks = { achievementDefinitions, achievements };

View file

@ -1,4 +1,5 @@
export * from "../engine/index.js";
export { achievementDefinitions, achievements } from "./achievements.js";
import * as game from "../engine/index.js";
import en from "../viewer/locales/en.json" with { type: "json" };
import { RELEASE } from "../release-config.js";

View file

@ -0,0 +1,82 @@
# Platform badges (manifest revision 1)
`bgs/achievements.js` exports the optional protocol 0.11.0 hooks through
`bgs/engine.js`. These are account badges, **not** additions to the physical
Achievement deck in `engine/achievements.js`. Stable hyphenated IDs must not be
repurposed. Default platform artwork is used: no durable uploaded asset keys
have been verified, and no production upload is part of this change.
## Objective semantics
See `docs/sources.md` for the edition, June 2026 errata, deck transcription and
Festival reservation caveat. No game rules or objective requirements change.
- **Festival sweep** requires every objective in the nonempty active global
`s.festivals` array to have `claimed === seat`. Festival objectives are
first-claim-only: collectively clearing the table is not a personal sweep.
Either `festival` or `festival-cards` must be enabled. Seat zero is valid.
- **Personal perfection** requires every card in the player's nonempty active
`achievements` array to have `completed === true`, with `achievements` enabled.
This means the dealt/chosen set (normally four), not all 30 physical cards.
Completion is latched; final inventory need not still satisfy the card.
- Partial-completion badges use those same sets and variant guards.
Authoritative implementation: `setupFestival`, `completedFestivals`,
`checkFestival`, `setupAchievements`, `selectAchievement`, and
`checkAchievements` in `engine/index.js`; card predicates in
`engine/achievements.js`. No historical event requirement is reconstructed from
final inventories.
## Curated manifest
| ID | Requirement at a completed game |
| --- | --- |
| island-victory | Outright multiplayer win |
| puertoma-easy | Outright hosted solo win on easy |
| puertoma-normal | Outright hosted solo win on normal |
| puertoma-hard | Outright hosted solo win on hard |
| all-festival-objectives | Personally claim all active Festival objectives |
| all-personal-achievements | Complete all owned personal cards |
| festival-claim | Claim at least one Festival |
| personal-achievement | Complete at least one owned card |
| fifty-points | Final total at least 50 |
| seventy-points | Final total at least 70 |
| full-city | Exactly 12 built city spaces |
| full-island | Exactly 12 countryside tiles |
| expanded-city | At least two two-space buildings, occupancy not required |
| five-crop-estates | Own an estate of each of the five crops |
| twenty-coins | At least 20 coins remaining |
| six-core-roles | Choose Planter, Recruiter, Builder, Craftsman, Trader, Captain |
All non-victory feats are independent of outcome. Roles are read from committed
move history (not the bounded journal). City space sizes and crops come from the
catalog. Scores use `scoreBreakdown`, including personal-card/Puertoma bonuses.
## Outcomes, eligibility and purity
Require `finished === true`, no pending tasks, and a natural `points`, `workers`
or `city` end reason. Triggering the end condition before the round finishes is
not enough. Tutorials, analysis, and explicit practice/cancellation markers are
excluded. `createAnalysis` now marks its fork, and `replay` preserves that marker.
Live replay remains eligible; querying either hook never mutates state or RNG.
Older unmarked analysis saves cannot be distinguished from real games. Only the
engine-owned analysis marker is newly preserved by replay; ad hoc practice or
cancellation flags are defensive direct-state guards, not persisted platform
eligibility records. The platform must enforce those restrictions on replays too.
BGS owns account eligibility, cancellations, practice metadata and bot/drop
filtering not represented in engine state; no invented account-service lookup
is made here. `dropPlayer` only marks a replacement bot. Multiplayer bot seats
use normal human rules, not Puertoma rules.
Outcomes compare all players' final total, then coins plus crates. Shared best
results are draws, not outright-win badges. Hosted solo returns **only seat 0**,
but explicitly compares against both virtual Puertomas. Hosted creation currently
fixes **normal** difficulty. Easy/hard badges are reserved for genuine supported
engine configurations; they are not selectable in the released host, and no
picker has been added. Ordinary multiplayer never earns a solo badge.
Tests: `test/platform-achievements.test.js` plays real completed multiplayer and
hosted solo games, validates official runtime schemas, checks deterministic
replay/purity, and uses cloned final fixtures for all-vs-missing-one, empty and
disabled sets, finality/analysis, solo win/loss/draw, and numeric/role boundaries.

View file

@ -2274,6 +2274,7 @@ export function replay(s, options = {}) {
p.bot = s.players[i].bot;
if (s.players[i].settings) p.settings = clone(s.players[i].settings);
});
if (s.analysis) r.analysis = true;
return r;
}
export function logSlice(
@ -2317,6 +2318,7 @@ export function canLaunchAnalysisMode(s) {
}
export function createAnalysis(s, { to = logLength(s) } = {}) {
const n = replay(s, to);
n.analysis = true;
n.players.forEach((p) => {
p.bot = false;
p.settings = { autoForcedActions: false };

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/puerto-rico",
"version": "0.3.18",
"version": "0.3.19",
"private": true,
"type": "module",
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",
@ -16,7 +16,7 @@
"publish:gallery": "node scripts/publish-gallery.mjs"
},
"dependencies": {
"@boardgamers/protocol": "file:vendor/boardgamers-protocol-0.11.0.tgz",
"@boardgamers/protocol": "0.11.0",
"@noble/hashes": "2.0.1",
"morphdom": "2.7.8"
},

11
pnpm-lock.yaml generated
View file

@ -9,8 +9,8 @@ importers:
.:
dependencies:
'@boardgamers/protocol':
specifier: file:vendor/boardgamers-protocol-0.11.0.tgz
version: file:vendor/boardgamers-protocol-0.11.0.tgz
specifier: 0.11.0
version: 0.11.0
'@noble/hashes':
specifier: 2.0.1
version: 2.0.1
@ -30,9 +30,8 @@ importers:
packages:
'@boardgamers/protocol@file:vendor/boardgamers-protocol-0.11.0.tgz':
resolution: {integrity: sha512-WmLTORnjHONvGjx24DzDylB1EQV9EO53rHKlouVX+Y59fIYAVkR1TZ9YbUo1es+jS7YYb0iFSHB3c8aOGxAgKQ==, tarball: file:vendor/boardgamers-protocol-0.11.0.tgz}
version: 0.11.0
'@boardgamers/protocol@0.11.0':
resolution: {integrity: sha512-YQ54+aVOIZvxUJvFmUbZR7xSBEgQaemstPdmYKVGCUHCviRX2UXRLgqLSQl6PFhr++lUT+Nynbf+p7h19zN+/g==}
'@esbuild/aix-ppc64@0.28.2':
resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}
@ -227,7 +226,7 @@ packages:
snapshots:
'@boardgamers/protocol@file:vendor/boardgamers-protocol-0.11.0.tgz':
'@boardgamers/protocol@0.11.0':
dependencies:
zod: 4.6.5

View file

@ -2,4 +2,4 @@ allowBuilds:
esbuild: true
minimumReleaseAgeExclude:
- "@boardgamers/protocol@0.8.1"
- "@boardgamers/protocol@0.8.1 || 0.11.0"

View file

@ -0,0 +1,204 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as host from "../bgs/engine.js";
import * as game from "../engine/index.js";
import { BUILDINGS, GOODS, ROLES } from "../engine/catalog.js";
import {
achievementManifestSchema,
achievementResultsSchema,
} from "@boardgamers/protocol/achievements";
function finish(s, move = game.moveAI) {
for (let n = 0; !s.finished && n < 3000; n++) s = move(s);
assert.equal(s.finished, true);
return s;
}
// Actual legal games, not a fabricated finished flag. Boundary tests clone these.
const completed = finish(host.init(3, [], {}, "badge-fixture"));
const solo = finish(host.init(1, [], {}, "badge-solo"), host.moveAI);
const has = (s, id, seat = 0) =>
host
.achievements(s)
.find((r) => r.seat === seat)
?.earned.includes(id) ?? false;
test("official schemas, stable manifest, real completed fixtures, replay and purity", () => {
const manifest = host.achievementDefinitions();
achievementManifestSchema.parse(manifest);
assert.equal(manifest.revision, 1);
assert.equal(manifest.achievements.length, 16);
for (const s of [completed, solo]) {
const before = structuredClone(s);
const results = host.achievements(s);
achievementResultsSchema(manifest, s === solo ? 1 : 3).parse(results);
assert.deepEqual(host.achievements(s), results);
assert.deepEqual(host.achievements(game.replay(s)), results);
assert.deepEqual(s, before);
}
manifest.achievements.length = 0;
assert.equal(host.achievementDefinitions().achievements.length, 16);
});
test("all means this seat's entire nonempty active set, not the table or the deck", () => {
const s = structuredClone(completed);
s.festivals.forEach((f) => (f.claimed = 0));
s.players[0].achievements.forEach((c) => (c.completed = true));
assert(has(s, "all-festival-objectives"));
assert(has(s, "all-personal-achievements"));
assert(!has(s, "all-festival-objectives", 1));
s.festivals[0].claimed = 1;
s.players[0].achievements[0].completed = false;
assert(!has(s, "all-festival-objectives"));
assert(!has(s, "all-personal-achievements"));
assert(has(s, "festival-claim"));
assert(has(s, "personal-achievement"));
delete s.festivals[0].claimed;
assert(!has(s, "all-festival-objectives"));
s.festivals = [];
s.players[0].achievements = [];
assert(!has(s, "all-festival-objectives"));
assert(!has(s, "all-personal-achievements"));
});
test("disabled variants never award objective badges, even with stale completed data", () => {
const s = structuredClone(completed);
s.festivals.forEach((f) => (f.claimed = 0));
s.players[0].achievements.forEach((c) => (c.completed = true));
s.expansions = [];
for (const id of [
"all-festival-objectives",
"all-personal-achievements",
"festival-claim",
"personal-achievement",
])
assert(!has(s, id));
for (const expansion of ["festival", "festival-cards"]) {
s.expansions = [expansion];
assert(has(s, "all-festival-objectives"));
}
});
test("only naturally finished games; analysis marker survives moves and replay", () => {
assert.deepEqual(host.achievements(host.init(3, [], {}, "live")), []);
for (const patch of [
{ finished: false },
{ endReason: "cancelled" },
{ tasks: [{ kind: "role" }] },
{ tutorial: {} },
{ practice: true },
{ cancelled: true },
{ canceled: true },
{ analysis: true },
])
assert.deepEqual(host.achievements({ ...completed, ...patch }), []);
const analysis = host.createAnalysis(completed);
assert.deepEqual(host.achievements(analysis), []);
assert.deepEqual(host.achievements(game.replay(analysis)), []);
const branch = game.createAnalysis(completed, { to: 1 });
const advanced = game.moveAI(branch);
assert.equal(advanced.analysis, true);
assert.equal(game.replay(advanced).analysis, true);
});
test("solo outcomes explicitly compare both virtual opponents including tie breakers", () => {
for (const difficulty of ["easy", "normal", "hard"]) {
const s = structuredClone(solo);
s.puertoma.difficulty = difficulty;
s.players[0].vp = 1000;
assert.equal(host.achievements(s).length, 1);
assert.equal(host.achievements(s)[0].outcome, "win");
assert(has(s, `puertoma-${difficulty}`));
assert(!has(s, "island-victory"));
s.players[1].vp = 2000;
assert.equal(host.achievements(s)[0].outcome, "loss");
assert(!has(s, `puertoma-${difficulty}`));
assert(has(s, "seventy-points")); // Nonwin feats remain independent.
}
const s = structuredClone(solo);
s.players.forEach((p) => {
p.vp = 0;
p.buildings = []; // Remove VP-dependent Customs House bonus before fixing a tie.
p.coins = 0;
p.goods = {};
});
const values = game.scores(s);
s.players.forEach((p, i) => (p.vp = 100 - values[i]));
assert.deepEqual(game.scores(s), [100, 100, 100]);
assert.deepEqual(
s.players.map((_, seat) => game.scoreBreakdown(s, seat).tie),
[0, 0, 0],
);
assert.equal(host.achievements(s)[0].outcome, "draw");
assert(!has(s, "puertoma-normal"));
s.players[0].coins = 1;
assert.equal(host.achievements(s)[0].outcome, "win");
});
test("multiplayer outcomes and nonwinning badges are seat-local", () => {
const s = structuredClone(completed);
s.players.forEach((p) => {
p.buildings = [];
p.estates = [];
p.reserve = { w: 0, c: 0 };
p.achievements = [];
p.vp = 70;
p.coins = 0;
p.goods = {};
});
assert.deepEqual(
host.achievements(s).map((r) => r.outcome),
["draw", "draw", "draw"],
);
assert(!has(s, "island-victory"));
s.players[1].coins = 1;
assert.deepEqual(
host.achievements(s).map((r) => r.outcome),
["loss", "win", "loss"],
);
assert(has(s, "island-victory", 1));
assert(has(s, "seventy-points", 0));
assert(!has(s, "puertoma-normal", 1));
});
test("score, city, island, building, crop, treasury and role boundaries", () => {
const s = structuredClone(completed),
a = s.players[0];
a.buildings = [];
a.estates = [];
a.reserve = { w: 0, c: 0 };
a.achievements = [];
for (const [points, expected] of [
[49, []],
[50, ["fifty-points"]],
[69, ["fifty-points"]],
[70, ["fifty-points", "seventy-points"]],
]) {
a.vp = points;
for (const id of ["fifty-points", "seventy-points"])
assert.equal(has(s, id), expected.includes(id));
}
a.coins = 19;
assert(!has(s, "twenty-coins"));
a.coins = 20;
assert(has(s, "twenty-coins"));
const large = Object.values(BUILDINGS).filter((b) => b.size === 2);
a.buildings = large.slice(0, 1).map((b) => ({ id: b.id, w: 0, c: 0 }));
assert(!has(s, "expanded-city"));
a.buildings = large.slice(0, 6).map((b) => ({ id: b.id, w: 0, c: 0 }));
assert(has(s, "expanded-city"));
assert(has(s, "full-city"));
a.buildings.pop();
assert(!has(s, "full-city"));
a.estates = GOODS.map((id) => ({ id, w: 0, c: 0 }));
assert(has(s, "five-crop-estates"));
a.estates.pop();
assert(!has(s, "five-crop-estates"));
a.estates = Array.from({ length: 11 }, () => ({ id: "corn", w: 0, c: 0 }));
assert(!has(s, "full-island"));
a.estates.push({ id: "corn", w: 0, c: 0 });
assert(has(s, "full-island"));
s.history = ROLES.map((id) => ({ p: 0, move: { type: "role", id } }));
assert(has(s, "six-core-roles"));
s.history.pop();
assert(!has(s, "six-core-roles"));
});