From a36a4aca77ea3c7913405c924580da491c818f9a Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Fri, 13 Nov 2026 17:00:45 +0000 Subject: [PATCH] feat(engine): add per-game achievement hooks and catalog --- docs/achievements.md | 149 +++++++++++++++++++ engine/README.md | 5 + engine/achievements.spec.ts | 277 ++++++++++++++++++++++++++++++++++++ engine/src/achievements.ts | 180 +++++++++++++++++++++++ engine/wrapper.ts | 2 + 5 files changed, 613 insertions(+) create mode 100644 docs/achievements.md create mode 100644 engine/achievements.spec.ts create mode 100644 engine/src/achievements.ts diff --git a/docs/achievements.md b/docs/achievements.md new file mode 100644 index 00000000..e1bc46cc --- /dev/null +++ b/docs/achievements.md @@ -0,0 +1,149 @@ +# Achievements + +The engine implements optional Boardgamers.space (BGS) achievement hooks in +[`engine/src/achievements.ts`](../engine/src/achievements.ts), re-exported as named +exports by `engine/wrapper.ts`. This is engine-side support, not a BGS publication +or a claim that achievements have been enabled on the hosted service. + +## Hook contract + +- `achievementDefinitions()` returns `{ revision: 1, achievements }`. Each definition + has string `id`, `name`, and `description` fields. The complete 36-entry catalog is + returned regardless of the current game's ruleset or selected factions. +- `achievements(data)` accepts an `Engine` or serialized engine state and returns + `{ seat, earned, outcome? }[]`. `earned` contains catalog IDs. The structural + outcome type allows `"win" | "loss" | "draw"`; this implementation emits only + `"win"` and `"loss"` for eligible humans, because shared first place is a win. +- These optional exports use local structural TypeScript interfaces. They add no + runtime protocol dependency and require no protocol-package upgrade to expose + the hooks. Consuming and publishing awards remains a host integration concern. + +### Authoritative completion only + +The caller must supply authoritative completed game state, not a client view or +an arbitrary analysis position. Evaluation requires all three of: + +1. `phase === Phase.EndGame`; +2. `round === Round.LastRound`; +3. an `advancedLog` entry whose phase is `Phase.EndGame`, emitted by final scoring. + +Otherwise the hook returns `[]`. Merely ending or terminating a game is not enough. +The hook does not advance play, replay moves, or recompute final scoring. It reads +stored final victory points, including auction deductions already applied. The +completion marker is a state predicate, not proof that untrusted input is genuine; +a host must not accept fabricated client state as authoritative. + +Seats are zero-based indices in the engine's **human-player list**, in original +player order after removing Automa players; they are not raw engine player numbers. +Automa never receives a result. Dropped humans retain their human seat index and +return `{ seat, earned: [] }`, with no outcome, rather than shifting later seats. + +## Revision 1 catalog (36 IDs) + +### Faction victories (18) + +Each requires a win as the named faction; either ruleset qualifies where that +faction is available. + +| ID | Faction | +| --------------------------- | ------------- | +| `win.faction.terrans` | Terrans | +| `win.faction.lantids` | Lantids | +| `win.faction.hadsch-hallas` | Hadsch Hallas | +| `win.faction.ivits` | Ivits | +| `win.faction.geodens` | Geodens | +| `win.faction.baltaks` | Bal T'aks | +| `win.faction.xenos` | Xenos | +| `win.faction.gleens` | Gleens | +| `win.faction.taklons` | Taklons | +| `win.faction.ambas` | Ambas | +| `win.faction.firaks` | Firaks | +| `win.faction.bescods` | Bescods | +| `win.faction.nevlas` | Nevlas | +| `win.faction.itars` | Itars | +| `win.faction.tinkeroids` | Tinkeroids | +| `win.faction.darkanians` | Darkanians | +| `win.faction.moweyds` | Moweyds | +| `win.faction.space-giants` | Space Giants | + +### Ruleset victories and scores (6) + +| ID | Requirement | +| ---------------------- | --------------------------------------------------- | +| `win.mode.base` | Win a base game | +| `win.mode.lost-fleet` | Win a Lost Fleet game | +| `score.base.150` | Finish a base game with at least 150 final VP | +| `score.base.200` | Finish a base game with at least 200 final VP | +| `score.lost-fleet.150` | Finish a Lost Fleet game with at least 150 final VP | +| `score.lost-fleet.200` | Finish a Lost Fleet game with at least 200 final VP | + +`options.lostFleet` selects the ruleset; a Lost Fleet game does not also award base +mode IDs. Score achievements require **no win**, and 200 VP earns both thresholds +for the selected mode. + +### Automa victories (5) + +| ID | Exact difficulty | +| ------------------------- | ---------------- | +| `win.automa.automalein` | `automalein` | +| `win.automa.automa` | `automa` | +| `win.automa.automaechtig` | `automaechtig` | +| `win.automa.ultoma` | `ultoma` | +| `win.automa.alptrauma` | `alptrauma` | + +Only the configured difficulty's ID is earned, not all lower difficulties. +In both multiplayer and solo Automa games, a human at the highest final score +wins: ties for first count as wins, including a human tied with Automa. Winners +also earn their faction and mode victory IDs. The comparison uses the maximum +stored VP across engine players, including Automa. + +### General and faction feats (7) + +None of these feats requires a win. They still require an eligible, non-dropped +human in an authoritatively completed game. + +| ID | Requirement | +| ------------------------------------- | ---------------------------------------------------------------------------- | +| `build.all-standard` | All 18 standard building pieces simultaneously deployed at game end | +| `federation.form.3` | At least three federation formations in one game | +| `explore.all-types.base` | Main-owned colonies on all 9 required physical types in a base game | +| `explore.all-types.lost-fleet` | Main-owned colonies on all 11 required physical types in a Lost Fleet game | +| `faction.ivits.growing-federation` | As Ivits, at least three federation formation milestones | +| `faction.lantids.shared-civilization` | As Lantids, at least six additional mines on opponents' colonies at game end | +| `faction.bescods.balanced-research` | As Bescods, finish at level 3 or higher on all six research tracks | + +**Full deployment:** the standard supply is 8 mines, 4 trading stations, 3 research +labs, 1 planetary institute, and both academies (18 pieces). The predicate checks +each standard building counter against its faction-board maximum. Lost Planet, +artifacts, Gaiaformers, and space stations do not count. Upgrading returns lower-tier +pieces to supply, so building new colonies and refilling those tiers makes all 18 +simultaneously deployed structurally possible; upgrades do not impose a permanent +shortfall. Difficulty and practical attainability within a legal game's economy +remain uncalibrated. That is not an implementation blocker, nor is structural +possibility a claim of a demonstrated legal all-18 game. + +**Federations:** use `federationCount`, not federation-token inventory. Rewards and +rescores do not count as formations. Ivits' growing-federation extensions count as +formation milestones; qualifying Ivits earn both the general and faction feat. + +**Physical colony types:** the base set is Terra, Desert, Swamp, Oxide, Volcanic, +Titanium, Ice, Gaia, and Lost Planet (9). Lost Fleet adds Asteroid and Protoplanet +(11). Transdimensional (`m`) and empty space (`e`) are not required colony types. +The evaluator reads physical planets from `ownedPlanets`, not the broader scoring +condition that includes virtual artifact planet types. Artifact bonuses cannot +substitute for a physical colony. Gaiaformers and Lantids' shared/additional mines +do not satisfy this main-ownership requirement. Lantids' additional mines instead +count toward their separate shared-civilization feat. + +## Verification and scope + +Predicate tests may construct or modify final-state counters, scores, ownership, +and completion markers to isolate thresholds, exclusions, and seat mapping. Such +synthetic states test the evaluator contract; they do **not** prove that every feat +can be reached through legal play. A legal completed-game fixture exercises the +real completion/scoring path and serialization, but proves attainability only for +feats actually demonstrated by that fixture. In particular, do not interpret a +synthetic all-18 assertion as a legal all-18 playthrough or difficulty calibration. + +These hooks do not publish a BGS catalog, persist account awards, or deploy the +engine to BGS. Those host-side operations are outside this implementation. diff --git a/engine/README.md b/engine/README.md index db590bea..b0c8345d 100644 --- a/engine/README.md +++ b/engine/README.md @@ -2,6 +2,11 @@ Javascript engine for Gaia Project. +## Achievements + +See the [achievement hooks and revision 1 catalog](../docs/achievements.md) for the +optional BGS contract, completion requirements, award semantics, and verification scope. + ## Play online at Check out [boardgamers.space](https://boardgamers.space/boardgame/gaia-project)! Reach out to us if you want to contribute. diff --git a/engine/achievements.spec.ts b/engine/achievements.spec.ts new file mode 100644 index 00000000..15dca3f1 --- /dev/null +++ b/engine/achievements.spec.ts @@ -0,0 +1,277 @@ +import { expect } from "chai"; +import Beta2 from "./fixtures/Beta-2.json"; +import { automaDifficulties } from "./src/automa"; +import Engine from "./src/engine"; +import { Building, Expansion, Faction, Phase, Planet, ResearchField, Round } from "./src/enums"; +import { achievementDefinitions, achievements, factions, rankings, scores } from "./wrapper"; + +// Existing completed-game fixture for integration; mutations below are predicate boundary tests, +// not claims that the difficult feats have been demonstrated in a six-round resource budget. +function state(): Record { + return JSON.parse(JSON.stringify(Beta2)); +} + +function earned(data: Record, seat = 0): string[] { + return achievements(data).find((result) => result.seat === seat).earned; +} + +const baseTypes = [ + Planet.Terra, + Planet.Desert, + Planet.Swamp, + Planet.Oxide, + Planet.Volcanic, + Planet.Titanium, + Planet.Ice, + Planet.Gaia, + Planet.Lost, +]; + +function colonies(data: Record, types: Planet[]) { + for (const hex of data.map) { + delete hex.data.player; + delete hex.data.building; + delete hex.data.additionalMine; + } + types.forEach((planet, index) => { + Object.assign(data.map[index].data, { planet, player: 0, building: Building.Mine }); + }); +} + +function solo(difficulty = "automa"): Record { + const data = state(); + data.players = data.players.slice(0, 2); + data.players[1].isAutoma = true; + data.automa = { difficulty, round: 6, remaining: 0, discard: [], boosters: [], lastActions: [] }; + // Keep a valid map after removing the other two fixture seats. + for (const hex of data.map) { + if (hex.data.player > 1) { + delete hex.data.player; + delete hex.data.building; + } + } + return data; +} + +describe("BGS achievement hooks", () => { + it("exports a complete, unique, isolated revision-1 catalog", () => { + const manifest = achievementDefinitions(); + const ids = manifest.achievements.map((definition) => definition.id); + expect(manifest.revision).to.equal(1); + expect(ids).to.have.length(36); + expect(new Set(ids).size).to.equal(ids.length); + for (const faction of Faction.values(Expansion.All)) expect(ids).to.include(`win.faction.${faction}`); + for (const difficulty of automaDifficulties) expect(ids).to.include(`win.automa.${difficulty}`); + expect(manifest.achievements.every((definition) => definition.name && definition.description)).to.equal(true); + manifest.achievements[0].name = "mutated"; + expect(achievementDefinitions().achievements[0].name).not.to.equal("mutated"); + }); + + it("hydrates the existing completed fixture, agrees with wrapper outcomes, and is deterministic", () => { + const data = state(); + const engine = Engine.fromData(state()); + const result = achievements(data); + expect(result.map((entry) => entry.seat)).to.deep.equal([0, 1, 2, 3]); + expect(scores(engine)).to.deep.equal([151, 135, 213, 138]); + expect(factions(engine)[2]).to.equal(Faction.HadschHallas); + expect(result[2].outcome).to.equal("win"); + expect(result[2].earned).to.include.members([ + "win.faction.hadsch-hallas", + "win.mode.base", + "score.base.150", + "score.base.200", + ]); + expect(result[0].outcome).to.equal("loss"); + expect(result[0].earned).to.include("score.base.150"); + expect(result[0].earned.some((id) => id.startsWith("win."))).to.equal(false); + expect(achievements(engine)).to.deep.equal(result); + expect(achievements(data)).to.deep.equal(result); + const ids = new Set(achievementDefinitions().achievements.map((definition) => definition.id)); + expect(result.every((entry) => entry.earned.every((id) => ids.has(id)))).to.equal(true); + }); + + it("does not mutate serialized legacy options or federation caches during hydration", () => { + const data = state(); + const engine = Engine.fromData(state()); + data.players[0].federationCache = { + federations: [{ hexes: [engine.players[0].data.occupied[0].toString()] }], + }; + const before = JSON.stringify(data); + achievements(data); + expect(JSON.stringify(data)).to.equal(before); + achievements(data); + expect(JSON.stringify(data)).to.equal(before); + }); + + it("awards nothing before authoritative final scoring or after early cancellation", () => { + for (const phase of [Phase.RoundMove, Phase.RoundGaia]) { + const data = state(); + data.phase = phase; + expect(achievements(data)).to.deep.equal([]); + } + const cancelled = state(); + cancelled.round = 0; + expect(achievements(cancelled)).to.deep.equal([]); + const stopped = state(); + stopped.advancedLog = stopped.advancedLog.filter((entry) => entry.phase !== Phase.EndGame); + expect(achievements(stopped)).to.deep.equal([]); + }); + + it("retains human-seat indexing without awarding dropped players", () => { + const data = state(); + data.players[0].dropped = true; + const result = achievements(data); + expect(result[0]).to.deep.equal({ seat: 0, earned: [] }); + expect(result[2].seat).to.equal(2); + expect(result[2].earned).to.include("win.faction.hadsch-hallas"); + }); + + it("treats multiplayer tied first place as wins, not draws", () => { + const data = state(); + data.players[0].data.victoryPoints = 213; + expect(achievements(data).map((entry) => entry.outcome)).to.deep.equal(["win", "loss", "win", "loss"]); + }); + + it("uses exact resolved Automa difficulty and excludes the bot seat, including ties and losses", () => { + for (const difficulty of automaDifficulties) { + const data = solo(difficulty); + data.players[0].data.victoryPoints = 200; + for (const botScore of [199, 200, 201]) { + data.players[1].data.victoryPoints = botScore; + const result = achievements(data); + expect(result).to.have.length(1); + expect(result[0].seat).to.equal(0); + const won = rankings(Engine.fromData(data))[0] === 1; + expect(result[0].outcome).to.equal(won ? "win" : "loss"); + expect(result[0].earned.filter((id) => id.startsWith("win.automa."))).to.deep.equal( + won ? [`win.automa.${difficulty}`] : [] + ); + expect(result[0].earned).to.include("score.base.200"); + } + } + }); + + it("separates rulesets, not faction origin, and checks final-score thresholds inclusively", () => { + for (const lostFleet of [false, true]) { + const data = state(); + data.options.lostFleet = lostFleet; + const mode = lostFleet ? "lost-fleet" : "base"; + for (const score of [149, 150, 199, 200]) { + data.players[0].data.victoryPoints = score; + const ids = earned(data); + expect(ids.includes(`score.${mode}.150`)).to.equal(score >= 150); + expect(ids.includes(`score.${mode}.200`)).to.equal(score >= 200); + expect(ids.some((id) => id.startsWith(`score.${lostFleet ? "base" : "lost-fleet"}.`))).to.equal(false); + } + expect(earned(data, 2)).to.include(`win.mode.${mode}`); + } + }); + + it("supports every faction win, including the four expansion factions", () => { + for (const faction of Faction.values(Expansion.All)) { + const data = state(); + data.options.lostFleet = true; + data.players[2].faction = faction; + delete data.players[2].variant; + expect(earned(data, 2)).to.include(`win.faction.${faction}`); + } + }); + + it("requires every standard piece currently deployed, not virtual or returned mines", () => { + const data = state(); + const buildings = { + [Building.Mine]: 8, + [Building.TradingStation]: 4, + [Building.ResearchLab]: 3, + [Building.PlanetaryInstitute]: 1, + [Building.Academy1]: 1, + [Building.Academy2]: 1, + }; + Object.assign(data.players[0].data.buildings, buildings); + expect(earned(data)).to.include("build.all-standard"); + for (const building of Object.keys(buildings)) { + data.players[0].data.buildings[building]--; + data.players[0].data.lostPlanet = 1; + data.players[0].data.artifactPlanetTypes = [Planet.Asteroid, Planet.Protoplanet]; + expect(earned(data)).not.to.include("build.all-standard"); + data.players[0].data.buildings[building]++; + } + }); + + it("counts formations, not token inventory, and applies Ivits' growing-federation feat only to Ivits", () => { + const data = state(); + data.players[0].data.federationCount = 2; + data.players[0].data.tiles.federations = Array(5).fill({ tile: "fed1", green: true }); + data.players[0].data.spaceshipFederations = [{ tile: "unused", green: true }]; + expect(earned(data)).not.to.include("federation.form.3"); + data.players[0].data.federationCount = 3; + data.players[0].data.tiles.federations = []; + data.players[0].data.spaceshipFederations = []; + expect(earned(data)).to.include("federation.form.3"); + expect(earned(data)).not.to.include("faction.ivits.growing-federation"); + data.players[0].faction = Faction.Ivits; + delete data.players[0].variant; + expect(earned(data)).to.include("faction.ivits.growing-federation"); + }); + + it("requires all nine physical base types including Lost, but never Transdim", () => { + const data = state(); + colonies(data, baseTypes); + expect(earned(data)).to.include("explore.all-types.base"); + for (let index = 0; index < baseTypes.length; index++) { + const hex = data.map[index]; + hex.data.planet = Planet.Transdim; + expect(earned(data)).not.to.include("explore.all-types.base"); + hex.data.planet = baseTypes[index]; + } + data.map[7].data.building = Building.GaiaFormer; + expect(earned(data)).not.to.include("explore.all-types.base"); + }); + + it("requires physical asteroid and protoplanet colonies in Lost Fleet, not artifact types", () => { + const data = state(); + data.options.lostFleet = true; + colonies(data, baseTypes); + data.players[0].data.artifactPlanetTypes = [Planet.Asteroid, Planet.Protoplanet]; + expect(earned(data)).not.to.include("explore.all-types.lost-fleet"); + colonies(data, [...baseTypes, Planet.Asteroid, Planet.Protoplanet]); + expect(earned(data)).to.include("explore.all-types.lost-fleet"); + expect(earned(data)).not.to.include("explore.all-types.base"); + }); + + it("counts Lantids shared mines separately from main-owned planet types", () => { + const data = state(); + data.players[0].faction = Faction.Lantids; + delete data.players[0].variant; + colonies(data, baseTypes); + for (let index = 0; index < 6; index++) { + Object.assign(data.map[index].data, { player: 1, additionalMine: 0 }); + } + expect(earned(data)).to.include("faction.lantids.shared-civilization"); + expect(earned(data)).not.to.include("explore.all-types.base"); + delete data.map[5].data.additionalMine; + expect(earned(data)).not.to.include("faction.lantids.shared-civilization"); + }); + + it("requires Bescods and all six research tracks at level three or above", () => { + const data = state(); + for (const field of ResearchField.values(Expansion.All)) data.players[0].data.research[field] = 3; + expect(earned(data)).not.to.include("faction.bescods.balanced-research"); + data.players[0].faction = Faction.Bescods; + delete data.players[0].variant; + expect(earned(data)).to.include("faction.bescods.balanced-research"); + for (const field of ResearchField.values(Expansion.All)) { + data.players[0].data.research[field] = 2; + expect(earned(data)).not.to.include("faction.bescods.balanced-research"); + data.players[0].data.research[field] = 4; + } + }); + + it("can evaluate the fixture replay after the actual final-scoring transition", () => { + const engine = Engine.fromData(state()).replayedTo(); + expect(engine.phase).to.equal(Phase.EndGame); + expect(engine.round).to.equal(Round.LastRound); + expect(achievements(engine)).to.deep.equal(achievements(JSON.parse(JSON.stringify(engine)))); + expect(achievements(engine).filter((result) => result.outcome === "win")).to.have.length.greaterThan(0); + }); +}); diff --git a/engine/src/achievements.ts b/engine/src/achievements.ts new file mode 100644 index 00000000..434405a1 --- /dev/null +++ b/engine/src/achievements.ts @@ -0,0 +1,180 @@ +import { automaDifficulties } from "./automa"; +import Engine from "./engine"; +import { Building, Expansion, Faction, Phase, Planet, ResearchField, Round } from "./enums"; + +// Structural BGS protocol types: optional named exports need no runtime protocol dependency. +export interface AchievementDefinition { + id: string; + name: string; + description: string; +} + +export interface AchievementManifest { + revision: number; + achievements: AchievementDefinition[]; +} + +export interface SeatAchievements { + seat: number; + earned: string[]; + outcome?: "win" | "loss" | "draw"; +} + +const standardBuildings = [ + Building.Mine, + Building.TradingStation, + Building.ResearchLab, + Building.PlanetaryInstitute, + Building.Academy1, + Building.Academy2, +]; + +const baseColonyTypes = [ + Planet.Terra, + Planet.Desert, + Planet.Swamp, + Planet.Oxide, + Planet.Volcanic, + Planet.Titanium, + Planet.Ice, + Planet.Gaia, + Planet.Lost, +]; + +function displayName(id: string): string { + return id + .split("-") + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(" "); +} + +/** The complete catalog, independent of the current game's mode or faction selection. */ +export function achievementDefinitions(): AchievementManifest { + const definitions: AchievementDefinition[] = Faction.values(Expansion.All).map((faction) => ({ + id: `win.faction.${faction}`, + name: `${displayName(faction)} Victory`, + description: `Win as ${displayName(faction)}. Shared first place counts; either ruleset qualifies.`, + })); + for (const mode of ["base", "lost-fleet"]) { + const name = mode === "base" ? "Base Game" : "Lost Fleet"; + definitions.push({ + id: `win.mode.${mode}`, + name: `${name} Victory`, + description: `Win a ${name} game, including shared first place.`, + }); + for (const threshold of [150, 200]) { + definitions.push({ + id: `score.${mode}.${threshold}`, + name: `${name}: ${threshold} Points`, + description: `Finish a ${name} game with at least ${threshold} final victory points, after auction deductions. No win required.`, + }); + } + } + for (const difficulty of automaDifficulties) { + definitions.push({ + id: `win.automa.${difficulty}`, + name: `Defeat ${displayName(difficulty)}`, + description: `Win against Automa at exactly ${difficulty} difficulty. A tied score counts as a human win.`, + }); + } + definitions.push( + { + id: "build.all-standard", + name: "Full Deployment", + description: + "Finish with all 18 standard building pieces simultaneously deployed: 8 mines, 4 trading stations, 3 research labs, the institute and both academies. Excludes Lost Planet, artifacts, Gaiaformers and space stations. No win required.", + }, + { + id: "federation.form.3", + name: "Federation Builder", + description: + "Complete at least three federation formations in one game (extensions of the growing federation for Ivits). Token rewards and rescores do not count. No win required.", + }, + { + id: "explore.all-types.base", + name: "Every World: Base Game", + description: + "Finish a base game with main-owned colonies on all seven ordinary planet types, Gaia and the Lost Planet. Gaiaformers and Lantids shared mines do not count. No win required.", + }, + { + id: "explore.all-types.lost-fleet", + name: "Every World: Lost Fleet", + description: + "Finish a Lost Fleet game with main-owned colonies on all seven ordinary types, Gaia, Lost Planet, Asteroid and Protoplanet. Artifacts, Gaiaformers and Lantids shared mines do not count. No win required.", + }, + { + id: "faction.ivits.growing-federation", + name: "Growing Federation", + description: "As Ivits, complete three federation formation milestones in one game. No win required.", + }, + { + id: "faction.lantids.shared-civilization", + name: "Shared Civilization", + description: "As Lantids, finish with at least six additional mines on opponents' colonies. No win required.", + }, + { + id: "faction.bescods.balanced-research", + name: "Balanced Research", + description: "As Bescods, finish at level 3 or higher on all six research tracks. No win required.", + } + ); + return { revision: 1, achievements: definitions }; +} + +/** Evaluate authoritative completed state only; never advance play or recompute final scoring. */ +export function achievements(data: Engine | Record): SeatAchievements[] { + // The EndGame log marker is emitted by finalScoringPhase, unlike early termination. + if ( + data.phase !== Phase.EndGame || + data.round !== Round.LastRound || + !data.advancedLog?.some((entry) => entry.phase === Phase.EndGame) + ) { + return []; + } + // Hydration normalizes legacy options and federation caches in place. Never change the + // caller's authoritative serialized state just to evaluate an optional reporting hook. + const engine = data instanceof Engine ? data : Engine.fromData(JSON.parse(JSON.stringify(data))); + const humans = engine.players.filter((player) => !player.isAutoma); + const bestScore = Math.max(...engine.players.map((player) => player.data.victoryPoints)); + const mode = engine.options.lostFleet ? "lost-fleet" : "base"; + const requiredTypes = engine.options.lostFleet + ? [...baseColonyTypes, Planet.Protoplanet, Planet.Asteroid] + : baseColonyTypes; + + return humans.map((player, seat) => { + // Preserve wrapper human-seat indexing even when a participant dropped. + if (player.dropped) return { seat, earned: [] }; + const earned: string[] = []; + const won = player.data.victoryPoints >= bestScore; + if (won) { + earned.push(`win.faction.${player.faction}`, `win.mode.${mode}`); + if (engine.automa) earned.push(`win.automa.${engine.automa.difficulty}`); + } + for (const threshold of [150, 200]) { + if (player.data.victoryPoints >= threshold) earned.push(`score.${mode}.${threshold}`); + } + if (standardBuildings.every((building) => player.data.buildings[building] === player.maxBuildings(building))) { + earned.push("build.all-standard"); + } + if (player.data.federationCount >= 3) { + earned.push("federation.form.3"); + if (player.faction === Faction.Ivits) earned.push("faction.ivits.growing-federation"); + } + // Unlike Condition.PlanetType, ownedPlanets excludes virtual artifact types and shared mines. + const physicalTypes = new Set(player.ownedPlanets.map((hex) => hex.data.planet)); + if (requiredTypes.every((type) => physicalTypes.has(type))) earned.push(`explore.all-types.${mode}`); + if ( + player.faction === Faction.Lantids && + [...engine.map.grid.values()].filter((hex) => hex.data.additionalMine === player.player).length >= 6 + ) { + earned.push("faction.lantids.shared-civilization"); + } + if ( + player.faction === Faction.Bescods && + ResearchField.values(engine.expansions).every((field) => player.data.research[field] >= 3) + ) { + earned.push("faction.bescods.balanced-research"); + } + return { seat, earned, outcome: won ? "win" : "loss" }; + }); +} diff --git a/engine/wrapper.ts b/engine/wrapper.ts index c6c4a5e7..ac81b75f 100644 --- a/engine/wrapper.ts +++ b/engine/wrapper.ts @@ -23,6 +23,8 @@ import { } from "./src/premoves"; import assert from "./src/utils/assert"; +export { achievementDefinitions, achievements } from "./src/achievements"; + export async function init( nbPlayers: number, expansions: string[],