Add final-state Clash of Cultures achievements and protocol hooks

This commit is contained in:
coyotte508 2026-11-14 00:46:25 +00:00
commit e7928f088e
10 changed files with 599 additions and 5 deletions

73
docs/achievements.md Normal file
View file

@ -0,0 +1,73 @@
# Clash of Cultures achievements
Review-only implementation; no release or BGS publication is implied.
The native Rust evaluator is the single source of truth. The WASM package exports
`achievementDefinitions()` and `achievements(serializedData)` directly, alongside
its existing engine hooks. The web-client tests check the generated API against
`@boardgamers/protocol` **0.11.0** types and runtime schemas; there is no separate
JavaScript scoring implementation.
## Revision 1 catalog
Each length has `complete-<length>` and `win-<length>` achievements:
| ID suffix | Explicit length | Rules |
| --- | --- | --- |
| `shorter` | Shorter | 4 ages, two starting settlers, two status-phase advances |
| `standard` | Standard (Normal) | 6 ages; also the legacy/default option |
| `roll-to-end` | Roll to End | 6–7 ages, end rolls from age 6 round 2 |
| `wonderful-ending` | Wonderful Ending | 6–7 ages, qualifying wonder ends after its round |
| `epic` | Epic | 8 ages |
Additional feats are evaluated independently of victory:
| ID | Final-state evidence |
| --- | --- |
| `score-30` | At least 30 victory points using engine scoring |
| `score-40` | At least 40 victory points using engine scoring |
| `four-cities` | At least four cities currently controlled |
| `twenty-advances` | At least 20 regular advances (not special advances) |
| `three-objectives` | At least three completed objective records |
| `two-wonders-built` | At least two recorded wonders built, not merely owned |
| `captured-leader` | At least one recorded captured leader |
Icons are omitted intentionally: the platform's generic fallback is sufficient.
IDs are permanent identities and must not be repurposed. This catalog is BGS
platform metadata, not text rendered by the game viewer, so the viewer localization
extractor excludes it. Protocol 0.11.0 also requires `openChat` and `undo` commands;
the isolated preview/tutorial adapters explicitly report those unsupported.
## Eligibility and outcome
Only `Finished` authoritative saves are evaluated. Secret-stripped snapshots,
ongoing games, barbarian/pirate players, and withdrawn seats earn nothing.
Original seat indexes are preserved. An all-withdrawn game returns no results.
The engine's score comparison includes withdrawal precedence and every existing
scoring tiebreaker. An unresolved shared first place is a draw, not a win; other
seats lose. Completion and other feats do not require a win. Withdrawal victories
follow the engine's terminal state rather than inventing an age minimum.
Clash has no serialized cancellation flag or `cancelled` hook. Platform-side
cancellation, practice/analysis eligibility, account identity, and bot-account
filtering remain BGS responsibilities; the evaluator cannot authenticate a save
or detect metadata absent from it. `is_human()` distinguishes playable civilization
seats from NPC factions, not account ownership. Do not run these hooks on arbitrary
client submissions or use their results as proof of platform eligibility.
Evaluation does not advance play, consume randomness, change saves, or expose
hands, hidden cards, seeds, history, or account identifiers. No inferred combat
history or civilization-specific claims are awarded.
## Verification
```sh
cargo test -p server --lib achievements
npm --prefix web-client ci --ignore-scripts
npm --prefix web-client run build:bridge
cd web-client
node --experimental-strip-types --test src/achievements.test.ts
npm run check
```
Generated WASM/JS build products remain ignored and are not committed.

388
server/src/achievements.rs Normal file
View file

@ -0,0 +1,388 @@
//! Read-only, revisioned achievements derived from authoritative final game state.
use crate::game::{Game, GameLength, GameState};
use crate::victory_points::compare_score;
use serde::Serialize;
use std::cmp::Ordering;
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct Manifest {
pub revision: u32,
pub achievements: Vec<Definition>,
}
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct Definition {
pub id: String,
pub name: String,
pub description: String,
}
#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct SeatAchievements {
pub seat: usize,
pub earned: Vec<String>,
pub outcome: String,
}
const LENGTHS: [(GameLength, &str, &str); 5] = [
(GameLength::Shorter, "shorter", "Shorter"),
(GameLength::Standard, "standard", "Standard (Normal)"),
(GameLength::RollToEnd, "roll-to-end", "Roll to End"),
(
GameLength::WonderfulEnding,
"wonderful-ending",
"Wonderful Ending",
),
(GameLength::Epic, "epic", "Epic"),
];
const FEATS: [(&str, &str, &str); 7] = [
(
"score-30",
"30 Points",
"Finish a game with at least 30 victory points in the final state.",
),
(
"score-40",
"40 Points",
"Finish a game with at least 40 victory points in the final state.",
),
(
"four-cities",
"Four Cities",
"Finish a game owning at least 4 cities in the final state.",
),
(
"twenty-advances",
"Twenty Advances",
"Finish a game with at least 20 regular advances in the final state; special advances do not count.",
),
(
"three-objectives",
"Three Objectives",
"Finish a game with at least 3 completed objectives in the final state.",
),
(
"two-wonders-built",
"Two Wonders Built",
"Finish a game having built at least 2 wonders, as recorded in the final state; merely owning wonders does not count.",
),
(
"captured-leader",
"Captured Leader",
"Finish a game with at least 1 captured leader in the final state.",
),
];
/// The stable achievement catalogue. Array order also defines award order.
#[must_use]
pub fn definitions() -> Manifest {
let mut definitions = Vec::with_capacity(17);
for (_, id, name) in LENGTHS {
definitions.push(Definition {
id: format!("complete-{id}"),
name: format!("Complete {name}"),
description: format!("Finish a {name} game without dropping out."),
});
definitions.push(Definition {
id: format!("win-{id}"),
name: format!("Win {name}"),
description: format!("Finish a {name} game as the sole highest-ranked non-dropped human seat, including score tiebreakers; tied games do not count as wins."),
});
}
definitions.extend(FEATS.map(|(id, name, description)| Definition {
id: id.into(),
name: name.into(),
description: description.into(),
}));
Manifest {
revision: 1,
achievements: definitions,
}
}
/// Evaluate only authoritative finished games, without modifying game state.
/// Dropped seats and non-human civilizations never receive awards or affect wins.
///
/// # Panics
/// Panics if a game length is added without a corresponding catalog entry.
#[must_use]
pub fn achievements(game: &Game) -> Vec<SeatAchievements> {
if !matches!(game.state, GameState::Finished) || game.secrets_stripped {
return vec![];
}
let players: Vec<_> = game
.players
.iter()
.filter(|p| p.is_human() && !game.dropped_players.contains(&p.index))
.collect();
let (_, length, _) = LENGTHS
.iter()
.find(|(length, _, _)| *length == game.options.length)
.expect("all game lengths have achievement IDs");
players
.iter()
.map(|p| {
let mut awards = vec![format!("complete-{length}")];
if players.iter().all(|other| {
p.index == other.index || compare_score(p, other, game) == Ordering::Greater
}) {
awards.push(format!("win-{length}"));
}
let score = p.victory_points(game);
let predicates = [
score >= 30.0,
score >= 40.0,
p.cities.len() >= 4,
p.advances.len() >= 20,
p.completed_objectives.len() >= 3,
p.wonders_built.len() >= 2,
!p.captured_leaders.is_empty(),
];
for ((id, _, _), met) in FEATS.iter().zip(predicates) {
if met {
awards.push((*id).into());
}
}
let outcome = if players
.iter()
.any(|other| compare_score(p, other, game) == Ordering::Less)
{
"loss"
} else if players.iter().any(|other| {
p.index != other.index && compare_score(p, other, game) == Ordering::Equal
}) {
"draw"
} else {
"win"
};
SeatAchievements {
seat: p.index,
earned: awards,
outcome: outcome.into(),
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::Action;
use crate::advance::Advance;
use crate::city::City;
use crate::events::EventOrigin;
use crate::game::{GameContext, GameOptions};
use crate::game_setup::{GameSetupBuilder, setup_game};
use crate::leader::Leader;
use crate::objective_card::CompletedObjective;
use crate::playing_actions::PlayingAction;
use crate::special_advance::SpecialAdvance;
use crate::victory_points::{SpecialVictoryPoints, VictoryPointAttribution};
use crate::wonder::Wonder;
use enumset::EnumSet;
use std::collections::HashSet;
fn setup(length: GameLength) -> Game {
let mut game = setup_game(
&GameSetupBuilder::new(2)
.seed("achievements-tests".into())
.assigned_civilizations(vec!["Rome".into(), "Greece".into()])
.options(GameOptions {
length,
..GameOptions::default()
})
.build(),
);
for p in &mut game.players {
p.objective_cards.clear();
}
game.starting_player_index = 0;
game.current_player_index = 1;
game.age = game.options.length.ages();
game.round = 3;
game
}
fn finish(game: Game) -> Game {
let game = crate::game_api::execute(game, Action::Playing(PlayingAction::EndTurn), 1);
assert_eq!(game.state, GameState::Finished);
game
}
fn has(game: &Game, seat: usize, id: &str) -> bool {
achievements(game)
.iter()
.any(|p| p.seat == seat && p.earned.iter().any(|a| a == id))
}
fn set_score(game: &mut Game, seat: usize, target: f32) {
let delta = target - game.player(seat).victory_points(game);
game.player_mut(seat)
.special_victory_points
.push(SpecialVictoryPoints::new(
delta,
EventOrigin::Ability("test score".into()),
VictoryPointAttribution::Events,
));
}
#[test]
fn manifest_and_real_end_turn_for_all_lengths() {
let manifest = definitions();
assert_eq!(manifest.revision, 1);
assert_eq!(manifest.achievements.len(), 17);
assert_eq!(
manifest
.achievements
.iter()
.map(|d| &d.id)
.collect::<HashSet<_>>()
.len(),
17
);
assert!(
manifest
.achievements
.iter()
.any(|d| d.name == "Complete Standard (Normal)")
);
for (length, id, _) in LENGTHS {
let mut game = setup(length);
set_score(&mut game, 0, 20.0);
let game = finish(game);
assert!(has(&game, 0, &format!("complete-{id}")));
assert!(has(&game, 1, &format!("complete-{id}")));
assert!(has(&game, 0, &format!("win-{id}")));
assert!(!has(&game, 1, &format!("win-{id}")));
assert_eq!(achievements(&game).len(), 2); // excludes barbarians/pirates
}
}
#[test]
fn ineligible_states_and_dropped_seats() {
let mut game = setup(GameLength::Standard);
assert!(achievements(&game).is_empty());
game.state = GameState::ChooseCivilization;
assert!(achievements(&game).is_empty());
game.state = GameState::Playing;
let mut game = finish(game);
game.secrets_stripped = true;
assert!(achievements(&game).is_empty());
game.secrets_stripped = false;
set_score(&mut game, 0, 100.0);
game.dropped_players.push(0);
assert_eq!(achievements(&game).len(), 1);
assert!(has(&game, 1, "win-standard"));
game.dropped_players.push(1);
assert!(achievements(&game).is_empty());
}
#[test]
fn exact_tie_is_a_draw_but_city_tiebreak_wins() {
let mut game = finish(setup(GameLength::Standard));
set_score(&mut game, 0, 20.0);
set_score(&mut game, 1, 20.0);
assert_eq!(
compare_score(game.player(0), game.player(1), &game),
Ordering::Equal
);
assert!(!has(&game, 0, "win-standard"));
assert!(!has(&game, 1, "win-standard"));
assert!(achievements(&game).iter().all(|p| p.outcome == "draw"));
let pos = game.player(0).cities[0].position;
game.player_mut(0).cities.push(City::new(0, pos));
let score = game.player(0).victory_points(&game);
set_score(&mut game, 1, score);
assert!(has(&game, 0, "win-standard"));
assert!(!has(&game, 1, "win-standard"));
assert_eq!(achievements(&game)[0].outcome, "win");
assert_eq!(achievements(&game)[1].outcome, "loss");
}
#[test]
fn score_thresholds_are_inclusive() {
for (score, thirty, forty) in [
(29.5, false, false),
(30.0, true, false),
(39.5, true, false),
(40.0, true, true),
(45.0, true, true),
] {
let mut game = finish(setup(GameLength::Standard));
set_score(&mut game, 0, score);
assert_eq!(has(&game, 0, "score-30"), thirty);
assert_eq!(has(&game, 0, "score-40"), forty);
}
}
#[test]
fn final_state_counts_not_special_advances_or_owned_wonders() {
let mut game = finish(setup(GameLength::Standard));
let pos = game.player(0).cities[0].position;
for count in [0, 1, 2] {
let p = game.player_mut(0);
p.cities = (0..3 + count).map(|_| City::new(0, pos)).collect();
p.advances = EnumSet::<Advance>::all().iter().take(19 + count).collect();
p.special_advances.insert(SpecialAdvance::Aqueduct);
p.completed_objectives = (0..2 + count)
.map(|i| CompletedObjective {
card: i as u8,
name: format!("test {i}"),
})
.collect();
p.wonders_owned = [Wonder::Colosseum, Wonder::Pyramids].into_iter().collect();
p.wonders_built =
[Wonder::Colosseum, Wonder::Pyramids, Wonder::GreatGardens][..1 + count].to_vec();
p.captured_leaders = [Leader::Alexander, Leader::Caesar][..count].to_vec();
for id in [
"four-cities",
"twenty-advances",
"three-objectives",
"two-wonders-built",
"captured-leader",
] {
assert_eq!(has(&game, 0, id), count >= 1, "{id}, offset {count}");
}
}
}
#[test]
fn saved_end_game_fixture_and_nonwinning_feats() {
let data: crate::game_data::GameData = serde_json::from_str(include_str!(
"../tests/test_games/status_phase/end_game.json"
))
.expect("valid fixture");
let cache = crate::cache::Cache::new(&data.options);
let game = Game::from_data(data, cache, GameContext::Play);
assert!(achievements(&game).is_empty());
let mut game = crate::game_api::execute(game, Action::Playing(PlayingAction::EndTurn), 0);
assert_eq!(game.state, GameState::Finished);
assert_eq!(achievements(&game).len(), 2);
set_score(&mut game, 0, 40.0);
set_score(&mut game, 1, 100.0);
let results = achievements(&game);
assert_eq!(results[0].outcome, "loss");
assert!(has(&game, 0, "score-30"));
assert!(has(&game, 0, "score-40"));
assert!(!has(&game, 0, "win-standard"));
}
#[test]
fn deterministic_read_only_and_save_load_stable() {
let mut game = finish(setup(GameLength::Standard));
set_score(&mut game, 0, 40.0);
let before = serde_json::to_value(game.cloned_data()).expect("serialize game");
let awards = achievements(&game);
assert_eq!(awards, achievements(&game));
assert_eq!(
before,
serde_json::to_value(game.cloned_data()).expect("serialize game")
);
let data = serde_json::from_value(before).expect("deserialize game");
let restored = Game::from_data(data, game.cache.clone(), GameContext::Play);
assert_eq!(awards, achievements(&restored));
let json = serde_json::to_value(&awards).expect("serialize awards");
assert_eq!(json[0]["seat"], 0);
assert!(json[0]["earned"].is_array());
}
}

View file

@ -153,6 +153,21 @@ pub fn ended(game: String) -> JsValue {
JsValue::from_bool(game_api::ended(&game))
}
/// Public catalog; contains no game or player data.
#[wasm_bindgen(js_name = "achievementDefinitions")]
pub fn achievement_definitions() -> JsValue {
serde_wasm_bindgen::to_value(&crate::achievements::definitions())
.expect("achievement definitions should be serializable")
}
/// Query only authoritative, completed saves; never infer feats from a viewer snapshot.
#[wasm_bindgen]
pub fn achievements(game: String) -> JsValue {
let game = get_game(game);
serde_wasm_bindgen::to_value(&crate::achievements::achievements(&game))
.expect("achievement results should be serializable")
}
#[wasm_bindgen]
pub fn scores(game: String) -> JsValue {
let game = get_game(game);

View file

@ -12,6 +12,7 @@
extern crate core;
pub mod ability_initializer;
pub mod achievements;
pub mod action;
pub mod action_card;
mod action_cost;

View file

@ -8,7 +8,7 @@
"name": "@boardgamers/clash-web-client",
"version": "0.1.217",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"@boardgamers/protocol": "0.11.0",
"lucide-svelte": "^0.577.0",
"svelte": "^5.0.0",
"three": "^0.186.0"
@ -27,9 +27,9 @@
}
},
"node_modules/@boardgamers/protocol": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@boardgamers/protocol/-/protocol-0.9.0.tgz",
"integrity": "sha512-xDQMui0xqqRF/ERIJ7Rm79JonMA2+6zn1CrgxpM6Oy3SpFKF6i0Wo6oAyYYqMveqiWJCkC0WvHlePclVfbH/IQ==",
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@boardgamers/protocol/-/protocol-0.11.0.tgz",
"integrity": "sha512-YQ54+aVOIZvxUJvFmUbZR7xSBEgQaemstPdmYKVGCUHCviRX2UXRLgqLSQl6PFhr++lUT+Nynbf+p7h19zN+/g==",
"license": "AGPL-3.0-only",
"dependencies": {
"zod": "^4.3.6"

View file

@ -16,7 +16,7 @@
"tutorial:fixtures": "node scripts/build-tutorial-fixtures.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"@boardgamers/protocol": "0.11.0",
"lucide-svelte": "^0.577.0",
"svelte": "^5.0.0",
"three": "^0.186.0"

View file

@ -51,6 +51,9 @@ javascript(
function rust(directory) {
for (const item of fs.readdirSync(directory, { withFileTypes: true })) {
const file = path.join(directory, item.name);
// BGS consumes this catalog as platform metadata, not viewer-localized prose.
// It has its own revisioned names/descriptions and is never rendered by this viewer.
if (item.name === 'achievements.rs') continue;
if (item.isDirectory()) rust(file);
else if (item.name.endsWith('.rs') && !/(?:^|_)tests?\.rs$/.test(item.name) && item.name !== 'timing.rs') {
const content = fs.readFileSync(file, 'utf8');

View file

@ -30,6 +30,7 @@
const localization=mountLocalization(document.body);
controller=new Controller({move(raw){void move(raw);return true;},fetchState(){void refresh();return true;},
updatePreference(name,value){controller!.setPreferences({mapView:'3d',[name]:value});return true;},
openChat(){return false;},undo(){return false;},
updateSetting(){return true;},openPlayer(){return true;},hoverPlayer(){return true;},leavePlayer(){return true;},openBoardgame(){return true;},fetchLog(){return true;},addLog(){return true;},replaceLog(){return true;},setReplayInfo(){return true;},
},new URL('/',location.href),{predict:false});
controller.setPreferences({mapView:'3d',locale:'en',sound:false});

View file

@ -0,0 +1,111 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import type { Engine, AchievementManifest, SeatAchievements } from '@boardgamers/protocol/engine';
import { achievementManifestSchema, achievementResultsSchema } from '@boardgamers/protocol/achievements';
const require = createRequire(import.meta.url);
// Check the generated WASM API, not a parallel JS achievement implementation.
const engine: typeof import('../.bridge/server.js') = require('../.engine/server.js');
const hooks = {
achievementDefinitions: (): AchievementManifest => engine.achievementDefinitions(),
achievements: (data: string): SeatAchievements[] => engine.achievements(data),
} satisfies Pick<Engine<string>, 'achievementDefinitions' | 'achievements'>;
const fixture = readFileSync(
new URL('../../server/tests/test_games/status_phase/end_game.json', import.meta.url),
'utf8',
);
const finish = () => engine.tryMove(fixture, JSON.stringify({ Playing: 'EndTurn' }), 0);
test('WASM achievement catalog follows official protocol 0.11.0', () => {
const manifest = achievementManifestSchema.parse(hooks.achievementDefinitions());
assert.equal(manifest.revision, 1);
assert.equal(manifest.achievements.length, 17);
assert.deepEqual(hooks.achievementDefinitions(), manifest);
for (const length of ['shorter', 'standard', 'roll-to-end', 'wonderful-ending', 'epic']) {
for (const verb of ['complete', 'win'])
assert.ok(manifest.achievements.some((a) => a.id === `${verb}-${length}`));
}
});
test('actual completed fixture produces valid, deterministic, immutable seat achievements', () => {
assert.deepEqual(hooks.achievements(fixture), []);
const finished = finish();
assert.equal(engine.ended(finished), true);
const before = JSON.parse(finished);
const manifest = hooks.achievementDefinitions();
const results = achievementResultsSchema(manifest, 2).parse(hooks.achievements(finished));
assert.deepEqual(
results.map((r) => r.seat),
[0, 1],
);
const ranks = engine.rankings(finished) as number[];
for (const result of results) {
assert.ok(result.earned.includes('complete-standard'));
const outcome =
ranks[result.seat] === 1 ? (ranks.filter((r) => r === 1).length > 1 ? 'draw' : 'win') : 'loss';
assert.equal(result.outcome, outcome);
assert.equal(result.earned.includes('win-standard'), outcome === 'win');
}
assert.deepEqual(hooks.achievements(finished), results);
assert.deepEqual(hooks.achievements(JSON.stringify(before)), results);
assert.deepEqual(JSON.parse(finished), before);
});
test('WASM preserves inclusive score boundaries and awards feats to losing seats', () => {
for (const [score, thirty, forty] of [
[29.5, false, false],
[30, true, false],
[39.5, true, false],
[40, true, true],
] as const) {
const finished = finish();
const data = JSON.parse(finished);
const scores = engine.scores(finished) as number[];
for (const seat of [0, 1]) {
data.players[seat].special_victory_points ??= [];
data.players[seat].special_victory_points.push({
points: (seat === 0 ? score : 100) - scores[seat],
origin: { Ability: 'achievement boundary test' },
attribution: 'Events',
});
}
const result = hooks.achievements(JSON.stringify(data)).find((r) => r.seat === 0)!;
assert.equal(result.outcome, 'loss');
assert.equal(result.earned.includes('score-30'), thirty);
assert.equal(result.earned.includes('score-40'), forty);
assert.ok(result.earned.includes('complete-standard'));
}
});
test('all length options survive the serialized WASM boundary', () => {
for (const [option, suffix] of [
['Shorter', 'shorter'],
['Standard', 'standard'],
['RollToEnd', 'roll-to-end'],
['WonderfulEnding', 'wonderful-ending'],
['Epic', 'epic'],
]) {
const data = JSON.parse(finish());
data.options = { ...data.options, length: option };
const results = hooks.achievements(JSON.stringify(data));
assert.equal(results.length, 2);
for (const result of results) {
assert.deepEqual(
result.earned.filter((id) => id.startsWith('complete-')),
[`complete-${suffix}`],
);
}
}
});
test('filtered snapshots and all-withdrawn completions cannot award achievements', () => {
const finished = finish();
for (const seat of [undefined, 0, 1]) {
assert.deepEqual(hooks.achievements(engine.stripSecret(finished, seat)), []);
}
const dropped = JSON.parse(finished);
dropped.dropped_players = [0, 1];
assert.deepEqual(hooks.achievements(JSON.stringify(dropped)), []);
});

View file

@ -72,6 +72,8 @@ export const mountTutorial: TutorialMount = async (target, options) => {
void send({ step: lesson.steps[latest.step].id, kind: 'move', move: JSON.parse(move) });
return true;
},
openChat: noop,
undo: noop,
openPlayer: noop,
hoverPlayer: noop,
leavePlayer: noop,