Correct Aggressor and Great Architect with historical boundaries; prepare viewer 0.1.240 and engine 0.4.171

This commit is contained in:
coyotte508 2026-11-24 01:32:10 +00:00
commit a61cfc54e0
30 changed files with 4797 additions and 16 deletions

View file

@ -1,7 +1,7 @@
name: Web viewer
on:
pull_request:
paths: ['web-client/**', 'server/**', 'scripts/status-phase-battle.test.cjs', 'scripts/postcombat-queue*.cjs', 'scripts/tributes.test.cjs', 'scripts/withdrawal.test.cjs', 'scripts/viking-cargo.test.cjs', 'Cargo.*', '.github/workflows/web-viewer.yml']
paths: ['web-client/**', 'server/**', 'scripts/status-phase-battle.test.cjs', 'scripts/postcombat-queue*.cjs', 'scripts/tributes.test.cjs', 'scripts/withdrawal.test.cjs', 'scripts/viking-cargo.test.cjs', 'scripts/aggressor.test.cjs', 'scripts/great-architect.test.cjs', 'Cargo.*', '.github/workflows/web-viewer.yml']
push:
branches: [main, feat/3d-web-viewer]
jobs:
@ -24,7 +24,7 @@ jobs:
working-directory: web-client
- run: npx playwright install --with-deps chromium
working-directory: web-client
- run: node scripts/resource-journal-smoke.mjs && node scripts/famine-journal-smoke.mjs && node scripts/construction-smoke.mjs && node scripts/research-card-smoke.mjs
- run: node scripts/resource-journal-smoke.mjs && node scripts/famine-journal-smoke.mjs && node scripts/construction-smoke.mjs && node scripts/great-architect-smoke.mjs && node scripts/research-card-smoke.mjs
working-directory: web-client
- run: npm run test:boarding && node scripts/embark-smoke.mjs && node scripts/ship-landing-smoke.mjs
working-directory: web-client

View file

@ -0,0 +1,66 @@
# Aggressor eligibility (O23 / O25)
The independently visually checked primary English O23 and O25 faces in the
[Monumental Edition objective deck scan](https://cdn.steamusercontent.com/ugc/1781731512046605829/43DEFEAC6C24E28AFBE67BD5DB2E44AA9B5BD073/)
(Steam Workshop 2651868219, as catalogued in `card-text-audit.json`) both say:
> Immediately: After eliminating at least two Army units in a battle you started against another player.
The local inspection crops were `/tmp/clash-O23-primary.jpg` and
`/tmp/clash-O25-primary.jpg`; these are not repository assets. O23's other half
is Seafarer, and O25's is Government.
The combat-end listener now requires the objective owner to be the attacker,
a human opponent, and at least two opposing army casualties. Winning is **not**
a prerequisite: an attacker can qualify after a loss or draw. The existing
land-battle guard is retained (normal sea battles lose ships, not army units).
The `requires_player_combat` metadata removes only the Aggressor half in Builder;
it is not a substitute for the runtime human-opponent check.
Synthetic native tests exercise the real combat-end offer/claim flow for both
cards and all three results, negative defender/barbarian/one-army/settler/sea
cases, Builder filtering, save/reload before and after claiming, and actual
movement battles with deterministic combat dice. No private production fixture
is used. `scripts/aggressor.test.cjs` also initializes fresh synthetic games
through the public WASM engine, plays actual movement battles, and checks both
cards' offer/claim/save flow after wins, losses and draws, plus defender,
barbarian and one-casualty negatives.
Checks: `cargo test -p server --lib aggressor` and, after
`bash web-client/scripts/build-bridge.sh`, `node --test scripts/aggressor.test.cjs`.
## Existing saves
Loading an already completed award does not re-evaluate its historical combat
and does not remove points. A pending objective prompt already persisted by an
older engine likewise retains its offered choice through reload and claim.
The tests explicitly cover both forms of preservation. The predicate correction
applies when new combat-end eligibility is evaluated, not as a save repair.
`aggressor_eligibility_from` persists the first action using corrected eligibility.
Fresh games use zero. Old histories without the field replay with the historical
winner / land / two-army-loss predicate (including defenders and barbarians),
then adopt the corrected rule for new actions. Partial replay clamps the boundary
to the retained prefix plus one; undo does not erase it, and branching clamps it
to the new action. New histories retain the corrected predicate during replay:
this is not a blanket replay-mode exception. The comparison uses the action
resolving combat-end, not the action that started the battle. Already pending
objective claims remain valid.
Native regressions cover both predicates at the boundary and synthetic saved
battle action/claim replays, undo/redo, and live-save branching for old defender
and barbarian awards. These synthetic battle tests are not from-initialization
historical fixtures. The separate frozen published-engine Architect history
exercises full and partial replay boundary serialization. Builder retains all
38 objective card IDs in order: O23 keeps Seafarers and O25 keeps Government,
so removing Aggressor halves does not alter the shuffled deck or RNG consumption.
An exact seeded setup comparison additionally checks the entire serialized deal
and RNG. Old Builder caches retain the Aggressor halves for historical barbarian
awards and pending claims; new Builder games filter them. The runtime boundary
still prevents new barbarian awards in upgraded old games.
Client-side undo prediction also retains all four independent rules boundaries,
matching native undo patches; otherwise the first undo in an upgraded save could
cause prediction mismatches and drop queued moves. This is covered by both the
existing real-engine prediction suite and an explicit boundary regression.
No production save or historical award was edited.

View file

@ -0,0 +1,98 @@
# Great Architect: construction costs an action
Prepared for viewer 0.1.240 / engine 0.4.171, following 0.1.239 / 0.4.170.
No production save edits or retrospective action deductions.
## Primary rule source
The original **E55 Great Architect** image was opened and visually read:
<https://cdn.steamusercontent.com/ugc/1781731512046920408/E10408D4482864585C2C9FF7B972D4E0FDA0A223>.
The local inspected image was `/tmp/clash-E55-primary.jpg`.
The incident lets the recipient keep the card for 1 culture, otherwise passing
it left for another player to keep for 2 culture. “Immediately when bought”
applies to placing the card in front of its owner with three culture from the
supply, **not** immediately constructing a wonder. It permits disregarding the
prerequisite advance when constructing a wonder, spending the culture on the
card towards that wonder, and then discarding the card. It grants no free
construction action.
## Implementation scope
Public card 155 remains a free modifier. Its wonder cost retains the existing
three-culture reduction and prerequisite waiver (Engineering remains required).
It no longer unconditionally sets `ignore_action_cost` for new construction.
Actual construction therefore pays exactly one action through the existing
wonder payment handler. Preview and execution share that eligibility check:
zero actions cannot consume/strand the card, nor can missing Engineering or an
ineligible city. Selection prompts spend nothing before the construction step.
There is no optional decline added to this mandatory selection flow.
Existing city-specific leader exemptions are unchanged: Nebuchadnezzar and Qin
can still construct a wonder for free in their own city, but not elsewhere.
Japan's Shogunate does not turn this public modifier into an action-cost card or
waive its construction action. Great Engineer 126 is unchanged: its card costs
an action, its accepted construction grants a temporary action offset, and that
building does not activate its city. Other activation timing (including Great
Lighthouse), token storage semantics, and unrelated card effects are untouched.
## Persisted history boundary
`great_architect_action_cost_from` is a 1-based linear-log action boundary,
with `Some(0)` for newly initialized games. A live old save without a boundary
records one when it next starts Architect. Reconstruction of an absent-field
history sets the boundary **after its entire recorded prefix**, so old free
wonders and all subsequent recorded actions remain legal. Returned historical
positions clamp the boundary to the first future action; replacing an undone
future does likewise. Undo patches cannot remove/restore the boundary.
A pending old wonder payment already stores its old `CostInfo` and remains
free. A pending old *wonder-card selection* is evaluated against its originating
Architect play's log index, not its new response index, so it also stays legacy.
Newly played Architect after that pending operation uses the correction. Merely
loading a save does not retroactively charge anything. This deliberately
preserves already-started operations rather than changing their contract mid-prompt.
An independent `aggressor_eligibility_from` is carried by the same shared history
plumbing; the predicates are independent. Legacy golden test games pin missing
Aggressor boundaries to the existing `usize::MAX` compatibility convention.
## Frozen old-engine evidence and checks
`server/tests/fixtures/legacy_architect_170.json` was generated through the
published **0.4.170** engine, using only legal `init`/`tryMove` operations, no
synthetic state edits or private production data. Seed: `architect-history-35`;
ChooseCivilization setup, E55 as the first incident. Research, gathering, status
phase choices, the incident purchase, and a second city are all recorded.
Its cursors are:
- 73: before Architect, three actions available;
- 74: pending old wonder payment;
- 75: Great Wall constructed with three actions still available;
- 78: after Math, Collect, and Irrigation, zero actions remaining.
Native and WASM tests replay this actual history, including all three following
actions. A branch before the card pays one action, and replaying that newly saved
branch also pays once. A branch at pending old payment stays free. Unit tests
also cover saved multi-wonder selection, ordinary 3→2 construction, prerequisites,
zero-action eligibility, Japan, and both free-wonder leaders. WASM checks cover
these public API paths and unchanged Great Engineer action/activation behavior.
Commands used:
```sh
cargo test -p server --lib architect_tests
cargo test -p server --test architect_replay_tests --test great_person_tests
bash web-client/scripts/build-bridge.sh
node --test scripts/great-architect.test.cjs
```
The normal-viewer `web-client/scripts/great-architect-smoke.mjs` clicks the
Architect control and confirms actual payment at desktop/mobile widths, comparing
new one-action construction with a resumed old free payment. Web viewer CI runs
this alongside the unchanged Great Engineer construction smoke.
Additional native and WASM regressions compare old/new undo-redo with replacing
the same future: old redo stays free, new redo and replacement cost one action.
Redo already skips live availability and reconstructs the card event before
evaluating construction cost, so no special redo-mode exception is needed.

View file

@ -0,0 +1,49 @@
// Synthetic public-engine setup, real movement/combat, and serialized WASM claims.
// Build with: bash web-client/scripts/build-bridge.sh
const assert = require('node:assert/strict');
const { test } = require('node:test');
const engine = require(process.env.CLASH_WASM || '../web-client/.engine/server.js');
const move = (game, action, player = 0) => JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify(action), player));
async function battle(card, attackers, defenders, owner = 0, barbarian = false) {
const game = JSON.parse(await engine.init(2, [], {}, 'aggressor-printed-rule', null));
game.current_player_index = 0;
game.starting_player_index = 0;
game.map = { tiles: [['C2', 'Fertile'], ['C1', 'Fertile']], unexplored_blocks: [] };
game.players.forEach((p, i) => {
p.civilization = ['Rome', 'Greece', 'Barbarians', 'Pirates'][i];
p.objective_cards = i === owner ? [card] : [];
p.action_cards = [];
p.cities = [];
p.units = [];
p.advances = ['Farming', 'Mining', 'Tactics'];
});
const opponent = barbarian ? 2 : 1;
for (const [index, count, position] of [[0, attackers, 'C2'], [opponent, defenders, 'C1']]) {
game.players[index].units = Array.from({ length: count }, (_, id) => ({ id, position, unit_type: 'Infantry' }));
game.players[index].next_unit_id = count;
}
game.dice_roll_outcomes = Array(10).fill(11);
return move(game, { Movement: { Move: { units: Array.from({ length: attackers }, (_, i) => i), destination: 'C1', payment: {} } } });
}
const offered = g => (g.events || []).some(e => e.event_type.SelectObjectives?.shown_objective === 'Aggressor');
for (const card of [23, 25]) {
for (const [attackers, defenders, result] of [[3, 2, 'win'], [2, 3, 'loss'], [2, 2, 'draw']]) {
test(`O${card} attacker ${result}: two army casualties offer and claim through WASM`, async () => {
let game = await battle(card, attackers, defenders);
assert.ok(offered(game));
game = move(game, { Response: { SelectHandCards: [{ ObjectiveCard: card }] } });
assert.deepEqual(game.players[0].completed_objectives, [{ card, name: 'Aggressor' }]);
assert.ok(!(game.players[0].objective_cards || []).includes(card));
// stripSecret deserializes the completed save without removing its award.
const reloaded = JSON.parse(engine.stripSecret(JSON.stringify(game), 0));
assert.deepEqual(reloaded.players[0].completed_objectives, game.players[0].completed_objectives);
});
}
test(`O${card} defender win, barbarian opponent, and one casualty never offer`, async () => {
assert.ok(!offered(await battle(card, 2, 3, 1)));
assert.ok(!offered(await battle(card, 3, 2, 0, true)));
assert.ok(!offered(await battle(card, 2, 1)));
});
}

View file

@ -0,0 +1,107 @@
// Public WASM API regressions. Build with bash web-client/scripts/build-bridge.sh.
const assert = require('node:assert/strict');
const { test } = require('node:test');
const fs = require('node:fs');
const path = require('node:path');
const engine = require(process.env.CLASH_WASM || '../web-client/.engine/server.js');
const read = name => JSON.parse(fs.readFileSync(path.join(__dirname, '../server/tests/', name)));
const move = (g, action, player = 0) => JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify(action), player));
const view = (g, player = 0) => JSON.parse(engine.webView(engine.stripSecret(JSON.stringify(g), player), player));
const payment = { Response: { Payment: [{ food: 2, wood: 3, ore: 6, gold: 1, culture_tokens: 2 }] } };
function game() {
const g = read('test_games/incidents/great_persons/great_architect.json');
g.players[0].action_cards = [155];
g.actions_left = 3;
for (const civilization of ["Barbarians", "Pirates"]) {
g.players.push({ id: g.players.length, civilization, resources: {}, cities: [], units: [], advances: [], next_unit_id: 0 });
}
return g;
}
function build(g) {
g = move(g, { Playing: { ActionCard: 155 } });
assert.equal(g.actions_left, 3);
g = move(g, { Response: { SelectPositions: ['A1'] } });
assert.equal(g.actions_left, 2);
g = move(g, payment);
assert.equal(g.actions_left, 2);
assert.ok(g.players[0].wonders_built.includes('Pyramids'));
return g;
}
test('normal and Japan public Architect cost precisely one construction action', () => {
build(game());
const japan = game();
japan.players[0].civilization = 'Japan';
japan.players[0].special_advances = ['Shogunate'];
const g = build(japan);
assert.ok(!g.players[0].event_info?.['Shogunate card']);
});
test('zero actions, missing Engineering, and no happy cities never expose playable Architect', () => {
for (const change of [g => g.actions_left = 0, g => g.players[0].advances = ['Farming', 'Mining'], g => g.players[0].cities.forEach(c => c.mood_state = 'Angry')]) {
const g = game(); change(g);
assert.equal(view(g).actionCards.find(c => c.id === 155).action, null);
assert.throws(() => move(g, { Playing: { ActionCard: 155 } }));
assert.ok(g.players[0].action_cards.includes(155));
}
});
test('frozen published-engine 0.4.170 full replay preserves free wonder and all three following actions', () => {
const f = read('fixtures/legacy_architect_170.json');
const full = JSON.parse(engine.replay(JSON.stringify(f.history), {}));
assert.equal(full.actions_left, 0);
assert.ok(full.players[1].wonders_built.includes('GreatWall'));
const before = JSON.parse(engine.replay(JSON.stringify(f.history), { to: f.before }));
const newPlay = move(before, { Playing: { ActionCard: 155 } }, 1);
assert.equal(newPlay.actions_left, 2);
const pending = JSON.parse(engine.replay(JSON.stringify(f.history), { to: f.pending }));
const resumed = move(pending, { Response: { Payment: [{ food: 3, wood: 2, ore: 7, culture_tokens: 2 }] } }, 1);
assert.equal(resumed.actions_left, 3);
});
test('Nebuchadnezzar and Qin keep free wonders only in their own city', () => {
for (const [civilization, leader] of [['Babylonia', 'Nebuchadnezzar'], ['China', 'Qin']]) {
const g = game();
g.players[0].civilization = civilization;
g.players[0].units[0] = { id: 0, position: 'A1', unit_type: { Leader: leader } };
g.players[0].recruited_leaders = [leader];
g.actions_left = 0;
assert.ok(view(g).actionCards.find(c => c.id === 155).action);
let next = move(g, { Playing: { ActionCard: 155 } });
// Only the leader's city is eligible, so no city-choice prompt remains.
assert.equal(next.events.at(-1).event_type.WonderCard.selected_position, 'A1');
next = move(next, payment);
assert.equal(next.actions_left, 0);
assert.ok(next.players[0].wonders_built.includes('Pyramids'));
}
});
test('Great Engineer still pays for the card, offsets construction and does not activate city', () => {
let g = read('test_games/incidents/great_persons/great_engineer.json');
g.players[0].action_cards = [126];
g.actions_left = 3;
const cityBefore = structuredClone(g.players[0].cities.find(c => c.position === 'C2'));
g = move(g, { Playing: { ActionCard: 126 } });
assert.equal(g.actions_left, 2);
g = move(g, { Response: { SelectAdvance: 'Engineering' } });
g = move(g, { Response: { Bool: true } });
assert.equal(g.actions_left, 3);
g = move(g, { Playing: { Construct: { city_position: 'C2', city_piece: 'Fortress', payment: { food: 1, wood: 1, ore: 1 } } } });
assert.equal(g.actions_left, 2);
const cityAfter = g.players[0].cities.find(c => c.position === 'C2');
assert.equal(cityAfter.mood_state, cityBefore.mood_state);
assert.equal(cityAfter.activations, cityBefore.activations);
assert.equal(cityAfter.angry_activation, cityBefore.angry_activation);
});
test('Architect undo/redo retains old free play while replacing its future charges once', () => {
const f = read('fixtures/legacy_architect_170.json');
for (const legacy of [false, true]) {
let pending = JSON.parse(engine.replay(JSON.stringify(f.history), { to: f[legacy ? 'pending' : 'before'] }));
if (!legacy) pending = move(pending, { Playing: { ActionCard: 155 } }, 1);
const boundary = pending.great_architect_action_cost_from;
const undone = move(pending, 'Undo', 1);
assert.equal(undone.actions_left, 3);
assert.equal(undone.great_architect_action_cost_from, boundary);
const redone = move(undone, 'Redo', 1);
assert.equal(redone.actions_left, legacy ? 3 : 2);
assert.equal(redone.great_architect_action_cost_from, boundary);
const branch = move(undone, { Playing: { ActionCard: 155 } }, 1);
assert.equal(branch.actions_left, 2);
assert.equal(branch.great_architect_action_cost_from, f.pending);
}
});

View file

@ -55,6 +55,31 @@ pub struct Cache {
}
impl Cache {
// Old Builder games could earn Aggressor against barbarians. Keep that
// half available to historical listeners and already-persisted claims;
// the persisted runtime boundary still blocks new barbarian awards.
pub(crate) fn retain_legacy_builder_aggressor(&mut self) {
let objective = objectives::combat_objectives::aggressor();
for id in [23, 25] {
for card in self.all_objective_cards.iter_mut().filter(|c| c.id == id) {
if !card.has_objective("Aggressor") {
card.objectives.push(objective.clone());
}
}
if let Some(card) = self.objective_cards_by_id.get_mut(&id)
&& !card.has_objective("Aggressor")
{
card.objectives.push(objective.clone());
}
}
if !self.objectives_by_name.contains_key("Aggressor") {
self.all_objectives.push(objective.clone());
self.all_objectives.sort_by(|a, b| a.name.cmp(&b.name));
self.objectives_by_name
.insert("Aggressor".into(), objective);
}
}
#[must_use]
pub fn new(options: &GameOptions) -> Self {
Cache {

View file

@ -184,6 +184,255 @@ fn architect_wonder_cost(game: &Game, player: &Player, w: Wonder) -> CostInfo {
let mut info = wonder_cost(game, player, w);
info.cost.default.culture_tokens -= 3;
info.ignore_required_advances = true;
info.ignore_action_cost = true; // we already paid for the action with the architect card
// The public card is a modifier, not payment for Construct Wonder. Only
// recorded legacy plays retain the former action waiver. City-specific
// exemptions (wonder experts) still apply in can_construct_wonder.
if legacy_architect_play(game) {
info.ignore_action_cost = true;
}
info
}
// A saved card-selection prompt belongs to its original play, even when its
// response is the first action executed by the updated engine. Later wonder
// prompts already persist their CostInfo, including the legacy waiver.
fn legacy_architect_play(game: &Game) -> bool {
use crate::action::Action;
use crate::content::persistent_events::PersistentEventType;
use crate::playing_actions::PlayingAction;
let pending = game.events.iter().any(|event| {
matches!(&event.event_type, PersistentEventType::ActionCard(card) if card.id == 155)
});
let index = if pending {
crate::log::linear_action_entries(game)
.iter()
.rposition(|entry| {
matches!(
entry.action,
Action::Playing(PlayingAction::ActionCard(155))
)
})
.map_or(0, |index| index + 1)
} else if game.context == crate::game::GameContext::Replay {
crate::game_api::log_length(game)
} else {
// A live eligibility preview always describes a new branch, even if
// an undone legacy future still exists beyond the current cursor.
return false;
};
game.great_architect_action_cost_from
.is_some_and(|from| index < from)
|| (pending && game.great_architect_action_cost_from.is_none())
}
#[cfg(test)]
mod architect_tests {
use super::*;
use crate::action::{Action, try_execute_action};
use crate::cache::Cache;
use crate::content::persistent_events::EventResponse;
use crate::game::GameContext;
use crate::game_data::GameData;
use crate::playing_actions::PlayingAction;
use crate::position::Position;
fn game() -> Game {
let data: GameData = serde_json::from_str(include_str!(
"../../../tests/test_games/incidents/great_persons/great_architect.json"
))
.expect("valid Architect test fixture");
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
game.players[0].action_cards = vec![155];
game.actions_left = 3;
game
}
fn play(game: Game) -> Game {
crate::game_api::execute(game, Action::Playing(PlayingAction::ActionCard(155)), 0)
}
fn select(game: Game) -> Game {
crate::game_api::execute(
game,
Action::Response(EventResponse::SelectPositions(vec![Position::from_offset(
"A1",
)])),
0,
)
}
#[test]
fn architect_charges_construction_once_and_keeps_discounts() {
let game = game();
let base = wonder_cost(&game, game.player(0), Wonder::Pyramids);
let cost = architect_wonder_cost(&game, game.player(0), Wonder::Pyramids);
assert_eq!(
cost.cost.default.culture_tokens + 3,
base.cost.default.culture_tokens
);
assert!(cost.ignore_required_advances);
assert!(!cost.ignore_action_cost);
let game = play(game);
assert_eq!(game.actions_left, 3); // choosing the public modifier is free
let game = select(game);
assert_eq!(game.actions_left, 2);
let game = crate::game_api::execute(
game,
Action::Response(EventResponse::Payment(vec![ResourcePile::new(
2, 3, 6, 0, 1, 0, 2,
)])),
0,
);
assert_eq!(game.actions_left, 2);
assert!(game.players[0].wonders_built.contains(&Wonder::Pyramids));
assert!(!game.players[0].action_cards.contains(&155));
}
#[test]
fn architect_unavailable_without_action_engineering_or_city() {
for condition in 0..3 {
let mut game = game();
match condition {
0 => game.actions_left = 0,
1 => {
game.players[0]
.advances
.remove(crate::advance::Advance::Engineering);
}
_ => {
for city in &mut game.players[0].cities {
city.mood_state = crate::city::MoodState::Angry;
}
}
}
assert!(
PlayingActionType::ActionCard(155)
.is_available(&game, 0)
.is_err()
);
assert!(
try_execute_action(
game.clone(),
Action::Playing(PlayingAction::ActionCard(155)),
0
)
.is_err()
);
assert!(game.players[0].action_cards.contains(&155));
}
}
#[test]
fn japan_cannot_use_shogunate_to_make_public_architect_free() {
let mut game = game();
game.players[0].civilization = game.cache.get_civilization("Japan");
game.players[0]
.special_advances
.insert(crate::special_advance::SpecialAdvance::Shogunate);
let mut game = game.clone();
game.actions_left = 0;
assert!(
PlayingActionType::ActionCard(155)
.is_available(&game, 0)
.is_err()
);
game.actions_left = 3;
let game = select(play(game));
assert_eq!(game.actions_left, 2);
}
#[test]
fn expert_city_retains_its_own_free_wonder_exemption() {
for (civilization, leader) in [
("Babylonia", crate::leader::Leader::Nebuchadnezzar),
("China", crate::leader::Leader::Qin),
] {
let mut game = game();
game.players[0].civilization = game.cache.get_civilization(civilization);
game.players[0].units[0].unit_type = crate::unit::UnitType::Leader(leader);
game.players[0].units[0].position = Position::from_offset("A1");
game.players[0].recruited_leaders = vec![leader];
let mut game = game.clone();
game.actions_left = 0;
let cities = cities_for_wonder(
Wonder::Pyramids,
&game,
game.player(0),
architect_wonder_cost(&game, game.player(0), Wonder::Pyramids),
);
assert_eq!(cities, vec![Position::from_offset("A1")]);
assert!(
PlayingActionType::ActionCard(155)
.is_available(&game, 0)
.is_ok()
);
let game = play(game); // single city is selected automatically
assert_eq!(game.actions_left, 0);
}
}
#[test]
fn saved_multiple_wonder_choices_keep_original_cost_policy() {
for legacy in [false, true] {
let mut game = game();
game.players[0].wonder_cards.push(Wonder::GreatWall);
game.players[0].resources = ResourcePile::new(7, 7, 7, 7, 7, 7, 7);
if legacy {
game.great_architect_action_cost_from = Some(usize::MAX);
}
let game = play(game);
assert_eq!(game.actions_left, 3);
let mut value =
serde_json::to_value(game.cloned_data()).expect("valid Architect test fixture");
if legacy {
value
.as_object_mut()
.expect("valid Architect test fixture")
.remove("great_architect_action_cost_from");
}
let game = Game::from_data(
serde_json::from_value(value).expect("valid Architect test fixture"),
game.cache.clone(),
GameContext::Play,
);
let game = crate::game_api::execute(
game,
Action::Response(EventResponse::SelectHandCards(vec![HandCard::Wonder(
Wonder::Pyramids,
)])),
0,
);
assert_eq!(game.actions_left, 3);
let game = select(game);
assert_eq!(game.actions_left, if legacy { 3 } else { 2 });
}
}
#[test]
fn legacy_pending_wonder_keeps_waiver_but_new_branch_uses_action() {
let mut game = game();
game.great_architect_action_cost_from = Some(usize::MAX);
let game = play(game);
let mut value =
serde_json::to_value(game.cloned_data()).expect("valid Architect test fixture");
value
.as_object_mut()
.expect("valid Architect test fixture")
.remove("great_architect_action_cost_from");
let data = serde_json::from_value(value).expect("valid Architect test fixture");
let game = Game::from_data(data, game.cache.clone(), GameContext::Play);
let game = select(game);
assert_eq!(game.actions_left, 3);
let mut game = self::game();
game.great_architect_action_cost_from = Some(crate::game_api::log_length(&game) + 1);
game.actions_left = 0;
assert!(
PlayingActionType::ActionCard(155)
.is_available(&game, 0)
.is_err()
);
}
}

View file

@ -0,0 +1,456 @@
use crate::action::Action;
use crate::card::HandCard;
use crate::combat_listeners::{CombatResult, on_end_combat};
use crate::combat_stats::{Battleground, CombatPlayerStats, CombatStats};
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest, PersistentEventType,
};
use crate::game::{Game, GameContext, GameOptions, GameVariant};
use crate::game_setup::{GameSetupBuilder, setup_game};
use crate::log::{ActionLogAction, current_turn_log_mut};
use crate::objective_card::present_objective_cards;
use crate::playing_actions::PlayingAction;
use crate::position::Position;
use crate::unit::Units;
const CARDS: [u8; 2] = [23, 25];
fn game(card: u8) -> Game {
let mut game = setup_game(
&GameSetupBuilder::new(2)
.seed("aggressor-printed-rule".into())
.assigned_civilizations(vec!["Rome".into(), "Greece".into()])
.build(),
);
for player in &mut game.players {
player.objective_cards.clear();
player.action_cards.clear();
}
game.players[0].objective_cards = vec![card];
game.current_player_index = 0;
game.starting_player_index = 0;
reload(game)
}
fn infantry(n: u8) -> Units {
Units {
infantry: n,
..Units::empty()
}
}
fn stats(
attacking: bool,
opponent: usize,
result: CombatResult,
losses: Units,
ground: Battleground,
) -> CombatStats {
let own = CombatPlayerStats::new(0, infantry(3), Position::from_offset("C2"));
let mut other = CombatPlayerStats::new(opponent, infantry(3), Position::from_offset("C1"));
other.losses = losses;
let (attacker, defender) = if attacking {
(own, other)
} else {
(other, own)
};
CombatStats::new(ground, false, attacker, defender, Some(result), None)
}
fn finish(mut game: Game, stats: CombatStats) -> Game {
current_turn_log_mut(&mut game)
.actions
.push(ActionLogAction::new(
Action::Playing(PlayingAction::EndTurn),
0,
None,
0,
));
game.log_index += 1;
on_end_combat(&mut game, stats);
while let Some(handler) = game.current_event_handler() {
let PersistentEventRequest::ResourceReward(request) = &handler.request else {
break;
};
let response = Action::Response(EventResponse::ResourceReward(
request.reward.payment_options.default.clone(),
));
let player = game.active_player();
game = crate::game_api::execute(game, response, player);
}
game
}
fn offered(game: &Game) -> bool {
game.events.iter().any(|event| matches!(&event.event_type,
PersistentEventType::SelectObjectives(info) if info.shown_objective.as_deref() == Some("Aggressor")))
}
fn reload(game: Game) -> Game {
let data = serde_json::from_str(&serde_json::to_string(&game.cloned_data()).unwrap()).unwrap();
Game::from_data(data, game.cache.clone(), GameContext::Play)
}
fn claim(game: Game, card: u8) -> Game {
assert!(offered(&game));
let PersistentEventRequest::SelectHandCards(request) =
&game.current_event_handler().unwrap().request
else {
panic!("expected objective choice");
};
assert!(request.choices.contains(&HandCard::ObjectiveCard(card)));
let game = crate::game_api::execute(
game,
Action::Response(EventResponse::SelectHandCards(vec![
HandCard::ObjectiveCard(card),
])),
0,
);
assert_eq!(game.players[0].completed_objectives.len(), 1);
assert_eq!(game.players[0].completed_objectives[0].name, "Aggressor");
assert_eq!(game.players[0].completed_objectives[0].card, card);
assert!(!game.players[0].objective_cards.contains(&card));
game
}
#[test]
fn aggressor_offers_and_claims_attacker_wins_losses_and_draws() {
for card in CARDS {
for result in [
CombatResult::AttackerWins,
CombatResult::DefenderWins,
CombatResult::Draw,
] {
for ground in [
Battleground::Land,
Battleground::City,
Battleground::CityWithFortress,
] {
let game = finish(
game(card),
stats(true, 1, result.clone(), infantry(2), ground),
);
let game = claim(reload(game), card);
assert_eq!(reload(game).players[0].completed_objectives.len(), 1);
}
}
}
}
#[test]
fn aggressor_rejects_defenders_barbarians_insufficient_army_losses_and_sea() {
for card in CARDS {
for result in [
CombatResult::AttackerWins,
CombatResult::DefenderWins,
CombatResult::Draw,
] {
for battle in [
stats(false, 1, result.clone(), infantry(2), Battleground::Land),
stats(true, 2, result.clone(), infantry(2), Battleground::Land),
stats(true, 1, result.clone(), infantry(1), Battleground::Land),
stats(
true,
1,
result.clone(),
Units {
settlers: 2,
..Units::empty()
},
Battleground::Land,
),
stats(
true,
1,
result.clone(),
Units {
ships: 2,
..Units::empty()
},
Battleground::Sea,
),
stats(true, 1, result.clone(), infantry(2), Battleground::Sea),
] {
let game = finish(game(card), battle);
assert!(!offered(&game), "card {card}, result {result:?}");
assert!(game.players[0].completed_objectives.is_empty());
}
}
}
}
#[test]
fn aggressor_builder_filter_keeps_only_noncombat_halves() {
let options = GameOptions {
variant: GameVariant::Builder,
..GameOptions::default()
};
let cards = crate::content::objective_cards::get_all_uncached(&options);
for card in CARDS {
let game = game(card);
let objective = game
.cache
.get_objective_card(card)
.objectives
.iter()
.find(|o| o.name == "Aggressor")
.unwrap();
assert!(objective.requires_player_combat);
assert!(objective.status_phase_check.is_none());
assert_eq!(
objective.description,
"Immediately after eliminating at least 2 army units in a battle you started against another player."
);
let builder_card = cards.iter().find(|c| c.id == card).unwrap();
assert_eq!(builder_card.objectives.len(), 1);
assert_ne!(builder_card.objectives[0].name, "Aggressor");
}
}
#[test]
fn aggressor_preserves_saved_legacy_pending_choices_and_completed_awards() {
for card in CARDS {
// Historical eligibility was recorded when the prompt was created. Loading
// an already offered choice does not rerun the changed combat predicate.
let mut game = game(card);
present_objective_cards(&mut game, 0, vec!["Aggressor".into()]);
let game = claim(reload(game), card);
let game = reload(game);
assert_eq!(game.players[0].completed_objectives[0].card, card);
assert_eq!(game.players[0].completed_objectives[0].name, "Aggressor");
}
}
#[test]
fn aggressor_actual_movement_battles_offer_and_claim_both_cards() {
use crate::advance::Advance;
use crate::map::{Map, Terrain};
use crate::movement::{MoveUnits, MovementAction};
use crate::resource_pile::ResourcePile;
use crate::unit::{Unit, UnitType};
for card in CARDS {
for (attackers, defenders, expected) in [
(3, 2, CombatResult::AttackerWins),
(2, 3, CombatResult::DefenderWins),
(2, 2, CombatResult::Draw),
] {
let mut game = game(card);
let start = Position::from_offset("C2");
let end = Position::from_offset("C1");
game.map = Map::new([(start, Terrain::Fertile), (end, Terrain::Fertile)].into());
for player in &mut game.players {
player.cities.clear();
player.units.clear();
player.advances = [Advance::Farming, Advance::Mining, Advance::Tactics].into();
}
for (player, count, position) in [(0, attackers, start), (1, defenders, end)] {
game.players[player].units = (0..count)
.map(|id| Unit::new(player, position, UnitType::Infantry, id))
.collect();
game.players[player].next_unit_id = count;
}
game.dice_roll_outcomes = vec![11; 10];
let game = crate::game_api::execute(
reload(game),
Action::Movement(MovementAction::Move(MoveUnits::new(
(0..attackers).collect(),
end,
None,
ResourcePile::empty(),
))),
0,
);
let turn = crate::log::current_turn_log_without_redo(&game);
let stats = turn
.actions
.iter()
.find_map(|a| a.combat_stats.as_ref())
.unwrap();
assert_eq!(stats.result, Some(expected));
assert_eq!(stats.defender.losses.infantry, 2);
claim(reload(game), card);
}
}
}
#[test]
fn aggressor_rules_boundary_preserves_legacy_and_switches_at_current_action() {
for card in CARDS {
for boundary in [None, Some(usize::MAX), Some(0)] {
for (attacker, opponent, result, legacy, corrected) in [
(false, 1, CombatResult::DefenderWins, true, false),
(true, 2, CombatResult::AttackerWins, true, false),
(true, 1, CombatResult::DefenderWins, false, true),
(true, 1, CombatResult::Draw, false, true),
] {
let mut game = game(card);
game.aggressor_eligibility_from = boundary;
let game = finish(
reload(game),
stats(attacker, opponent, result, infantry(2), Battleground::Land),
);
assert_eq!(
offered(&game),
if boundary == Some(0) {
corrected
} else {
legacy
}
);
if offered(&game) {
claim(reload(game), card);
}
}
}
// finish appends exactly one action. Equality must already use new rules.
let mut game = game(card);
game.aggressor_eligibility_from = Some(crate::game_api::log_length(&game) + 1);
let game = finish(
game,
stats(true, 1, CombatResult::Draw, infantry(2), Battleground::Land),
);
claim(game, card);
}
}
#[test]
fn aggressor_builder_metadata_does_not_change_legacy_deck_ids_or_rng() {
// Both affected cards retain their other half. Filtering the added metadata
// must not remove cards, reorder the deck, or consume additional shuffle RNG.
let options = GameOptions {
variant: GameVariant::Builder,
..GameOptions::default()
};
let cards = crate::content::objective_cards::get_all_uncached(&options);
assert_eq!(
cards.iter().map(|c| c.id).collect::<Vec<_>>(),
(1..=38).collect::<Vec<_>>()
);
for (id, half) in [(23, "Seafarers"), (25, "Government")] {
let card = cards.iter().find(|c| c.id == id).unwrap();
assert_eq!(card.objectives.len(), 1);
assert_eq!(card.objectives[0].name, half);
}
}
#[test]
fn aggressor_legacy_saved_battle_claim_replays_and_new_branch_changes_eligibility() {
use crate::advance::Advance;
use crate::map::{Map, Terrain};
use crate::movement::{MoveUnits, MovementAction};
use crate::resource_pile::ResourcePile;
use crate::unit::{Unit, UnitType};
for card in CARDS {
for defender_owner in [false, true] {
let mut saved = game(card);
let start = Position::from_offset("C2");
let end = Position::from_offset("C1");
saved.map = Map::new([(start, Terrain::Fertile), (end, Terrain::Fertile)].into());
let (attacker, defender) = if defender_owner { (1, 0) } else { (0, 2) };
saved.current_player_index = attacker;
for player in &mut saved.players {
player.cities.clear();
player.units.clear();
player.advances = [Advance::Farming, Advance::Mining, Advance::Tactics].into();
}
for (player, count, position) in [
(attacker, if defender_owner { 2 } else { 3 }, start),
(defender, if defender_owner { 3 } else { 2 }, end),
] {
saved.players[player].units = (0..count)
.map(|id| Unit::new(player, position, UnitType::Infantry, id))
.collect();
saved.players[player].next_unit_id = count;
}
saved.dice_roll_outcomes = vec![11; 10];
saved.aggressor_eligibility_from = Some(usize::MAX);
let movement = Action::Movement(MovementAction::Move(MoveUnits::new(
(0..if defender_owner { 2 } else { 3 }).collect(),
end,
None,
ResourcePile::empty(),
)));
// Synthetic saved-position replay, deliberately not a from-init fixture.
let prefix =
crate::game_api::execute(reload(saved.clone()), movement.clone(), attacker);
let completed = claim(reload(prefix), card);
// Defender completion hands control back to the attacker and seals undo.
let redone = if defender_owner {
completed
} else {
let undone = crate::game_api::execute(completed, Action::Undo, 0);
assert!(offered(&undone));
assert_eq!(undone.aggressor_eligibility_from, Some(usize::MAX));
crate::game_api::execute(undone, Action::Redo, 0)
};
assert_eq!(redone.players[0].completed_objectives[0].name, "Aggressor");
let replayed = claim(
crate::game_api::execute(reload(saved.clone()), movement.clone(), attacker),
card,
);
assert_eq!(
replayed.players[0].completed_objectives,
redone.players[0].completed_objectives
);
// Loading an unversioned old live save adopts the correction on its
// first new action, unlike replaying already recorded old actions.
saved.aggressor_eligibility_from = None;
let branched = crate::game_api::execute(reload(saved), movement, attacker);
assert!(!offered(&branched));
assert!(branched.aggressor_eligibility_from.is_some());
}
}
}
#[test]
fn aggressor_legacy_builder_keeps_barbarian_awards_and_pending_claims() {
for card in CARDS {
let mut old = game(card);
old.options.variant = GameVariant::Builder;
old.cache = crate::cache::Cache::new(&old.options);
old.aggressor_eligibility_from = None;
let old = reload(old);
assert!(
old.cache
.get_objective_card(card)
.has_objective("Aggressor")
);
let pending = finish(
old,
stats(
true,
2,
CombatResult::AttackerWins,
infantry(2),
Battleground::Land,
),
);
let completed = claim(reload(pending), card);
assert_eq!(
reload(completed).players[0].completed_objectives[0].name,
"Aggressor"
);
}
}
#[test]
fn aggressor_legacy_builder_setup_preserves_exact_deal_and_rng() {
let options = GameOptions {
variant: GameVariant::Builder,
..GameOptions::default()
};
let setup = GameSetupBuilder::new(2)
.options(options.clone())
.seed("legacy-builder-aggressor".into())
.build();
let current = setup_game(&setup);
let mut cache = crate::cache::Cache::new(&options);
cache.retain_legacy_builder_aggressor();
let legacy = crate::game_setup::setup_game_with_cache(&setup, cache);
assert_eq!(
serde_json::to_value(current.cloned_data()).unwrap(),
serde_json::to_value(legacy.cloned_data()).unwrap()
);
assert_eq!(legacy.cache.get_objective_card(23).objectives.len(), 2);
assert_eq!(current.cache.get_objective_card(23).objectives.len(), 1);
}

View file

@ -272,14 +272,25 @@ pub(crate) fn aggressor() -> Objective {
let name = "Aggressor";
Objective::builder(
name,
"You won a land battle as attacker in which you killed at least 2 army units.",
"Immediately after eliminating at least 2 army units in a battle you started against another player.",
)
.requires_player_combat()
.add_simple_persistent_event_listener(
|event| &mut event.combat_end,
10,
|game, p, s| {
let player = p.index;
if s.is_winner(player)
// The boundary is the action evaluating combat_end, not the battle's
// start: an old pending battle completed by a new move uses new rules.
let corrected = game.aggressor_eligibility_from.is_some_and(|from| {
crate::game_api::log_length(game) >= from
});
let eligible = if corrected {
s.is_attacker(player) && s.opponent_is_human(player, game)
} else {
s.is_winner(player)
};
if eligible
&& s.battleground.is_land()
&& s.opponent(player).fighter_losses(s.battleground).amount() >= 2
{
@ -461,3 +472,7 @@ pub(crate) fn sea_cleansing() -> Objective {
#[cfg(test)]
#[path = "resistance_tests.rs"]
mod resistance_tests;
#[cfg(test)]
#[path = "aggressor_tests.rs"]
mod aggressor_tests;

View file

@ -157,6 +157,8 @@ pub struct Game {
pub options: GameOptions,
pub asynchronous_combat_from: Option<usize>,
pub finalized_combat_from: Option<usize>,
pub great_architect_action_cost_from: Option<usize>,
pub aggressor_eligibility_from: Option<usize>,
pub home_layout: crate::map::HomeLayout,
pub version: u16, // JSON schema version
pub state: GameState,

View file

@ -41,6 +41,10 @@ pub struct GameData {
asynchronous_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
finalized_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
great_architect_action_cost_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
aggressor_eligibility_from: Option<usize>,
#[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")]
home_layout: crate::map::HomeLayout,
#[serde(default)]
@ -142,7 +146,12 @@ pub struct GameData {
///
/// Panics if any wonder does not exist
#[must_use]
pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
pub fn from_data(data: GameData, mut cache: Cache, context: GameContext) -> Game {
if data.options.variant == crate::game::GameVariant::Builder
&& data.aggressor_eligibility_from != Some(0)
{
cache.retain_legacy_builder_aggressor();
}
let mut game = Game {
action_plan: data.action_plan,
early_choices: data
@ -160,6 +169,8 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
version: data.version,
asynchronous_combat_from: data.asynchronous_combat_from,
finalized_combat_from: data.finalized_combat_from,
great_architect_action_cost_from: data.great_architect_action_cost_from,
aggressor_eligibility_from: data.aggressor_eligibility_from,
home_layout: data.home_layout,
state: data.state,
players: Vec::new(),
@ -224,6 +235,8 @@ pub fn data(game: Game) -> GameData {
version: game.version,
asynchronous_combat_from: game.asynchronous_combat_from,
finalized_combat_from: game.finalized_combat_from,
great_architect_action_cost_from: game.great_architect_action_cost_from,
aggressor_eligibility_from: game.aggressor_eligibility_from,
home_layout: game.home_layout,
state: game.state,
events: game.events,
@ -274,6 +287,8 @@ pub fn cloned_data(game: &Game) -> GameData {
version: game.version,
asynchronous_combat_from: game.asynchronous_combat_from,
finalized_combat_from: game.finalized_combat_from,
great_architect_action_cost_from: game.great_architect_action_cost_from,
aggressor_eligibility_from: game.aggressor_eligibility_from,
home_layout: game.home_layout,
state: game.state.clone(),
events: game.events.clone(),

View file

@ -207,6 +207,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
context: GameContext::Play,
asynchronous_combat_from: Some(0),
finalized_combat_from: Some(0),
great_architect_action_cost_from: Some(0),
aggressor_eligibility_from: Some(0),
version: JSON_SCHEMA_VERSION,
options: GameOptions {
legacy_undo: None,

View file

@ -448,6 +448,14 @@ pub(crate) fn linear_action_log(game: &Game) -> Vec<Action> {
}
pub(crate) fn add_log_action(game: &mut Game, item: Action) {
let next = crate::game_api::log_length(game).saturating_add(1);
if matches!(
item,
Action::Playing(crate::playing_actions::PlayingAction::ActionCard(155))
) {
game.great_architect_action_cost_from.get_or_insert(next);
}
game.aggressor_eligibility_from.get_or_insert(next);
let active_events = game.events.len();
let player = game.active_player();
let origin = action_origin(&item, game.player(player)).clone();
@ -458,6 +466,11 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) {
let next = crate::game_api::log_length(game).saturating_add(1);
game.asynchronous_combat_from = game.asynchronous_combat_from.map(|from| from.min(next));
game.finalized_combat_from = game.finalized_combat_from.map(|from| from.min(next));
game.great_architect_action_cost_from = game
.great_architect_action_cost_from
.map(|from| from.min(next));
game.aggressor_eligibility_from =
game.aggressor_eligibility_from.map(|from| from.min(next));
}
let l = &mut current_turn_log_mut(game).actions;
remove_redo_actions(l, i);

View file

@ -97,7 +97,7 @@ impl ObjectiveCard {
}
#[must_use]
fn has_objective(&self, name: &str) -> bool {
pub(crate) fn has_objective(&self, name: &str) -> bool {
self.objectives.iter().any(|o| name == o.name)
}

View file

@ -16,6 +16,10 @@ pub struct ReplayGameData {
asynchronous_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
finalized_combat_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
great_architect_action_cost_from: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
aggressor_eligibility_from: Option<usize>,
#[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")]
home_layout: crate::map::HomeLayout,
log: Vec<ActionLogAge>,
@ -116,7 +120,16 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
.collect::<Result<Vec<_>, _>>()?;
builder = builder.assigned_civilizations(civilizations);
}
let mut game = setup_game(&builder.build());
let setup = builder.build();
let mut game = if data.options.variant == crate::game::GameVariant::Builder
&& data.aggressor_eligibility_from != Some(0)
{
let mut cache = crate::cache::Cache::new(&data.options);
cache.retain_legacy_builder_aggressor();
crate::game_setup::setup_game_with_cache(&setup, cache)
} else {
setup_game(&setup)
};
game.asynchronous_combat_from = Some(
data.asynchronous_combat_from
.unwrap_or(actions.len().saturating_add(1)),
@ -125,6 +138,14 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
data.finalized_combat_from
.unwrap_or(actions.len().saturating_add(1)),
);
game.great_architect_action_cost_from = Some(
data.great_architect_action_cost_from
.unwrap_or(actions.len().saturating_add(1)),
);
game.aggressor_eligibility_from = Some(
data.aggressor_eligibility_from
.unwrap_or(actions.len().saturating_add(1)),
);
if data.options.civilization == CivSetupOption::DraftThree {
// Draft locks are private and absent from the action log; setup turns
// record their final choices. Re-deal before locking to preserve the RNG.
@ -162,6 +183,13 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
{
game.context = crate::game::GameContext::Replay;
}
// Availability is queried after the recorded action is appended.
if matches!(
item.action,
Action::Playing(crate::playing_actions::PlayingAction::ActionCard(155))
) {
game.context = crate::game::GameContext::Replay;
}
game = try_execute_action(game, item.action.clone(), item.player)
.map_err(|e| format!("Failed to replay move {}: {e}", i + 1))?;
game.context = context;
@ -184,6 +212,12 @@ pub fn replay(data: ReplayGameData, to: Option<usize>) -> Result<Game, String> {
game.finalized_combat_from = game
.finalized_combat_from
.map(|from| from.min(to.saturating_add(1)));
game.great_architect_action_cost_from = game
.great_architect_action_cost_from
.map(|from| from.min(to.saturating_add(1)));
game.aggressor_eligibility_from = game
.aggressor_eligibility_from
.map(|from| from.min(to.saturating_add(1)));
for player in data.players {
game.players[player.id].settings = player.settings;
}

View file

@ -5,7 +5,7 @@ use crate::movement::execute_movement_action;
use json_patch::{PatchOperation, patch};
use serde_json::Value;
const IGNORE_PATHS: [&str; 9] = [
const IGNORE_PATHS: [&str; 11] = [
"/calendar_knowledge",
"/log/",
"/log_index",
@ -18,6 +18,8 @@ const IGNORE_PATHS: [&str; 9] = [
// point and accidentally make redo execute a newly recorded battle as legacy.
"/asynchronous_combat_from",
"/finalized_combat_from",
"/great_architect_action_cost_from",
"/aggressor_eligibility_from",
];
pub(crate) fn clean_patch(mut patch: Vec<PatchOperation>) -> Vec<PatchOperation> {

View file

@ -0,0 +1,148 @@
use serde_json::{Value, json};
use server::action::Action;
use server::game_api;
use server::playing_actions::PlayingAction;
use server::replay::replay;
fn fixture() -> Value {
serde_json::from_str(include_str!("fixtures/legacy_architect_170.json"))
.expect("valid Architect replay fixture")
}
#[test]
fn old_architect_history_replays_free_wonder_and_three_following_actions() {
let fixture = fixture();
for (cursor, actions_left) in [("pending", 3), ("built", 3), ("full", 0)] {
let game = replay(
serde_json::from_value(fixture["history"].clone())
.expect("valid Architect replay fixture"),
Some(
fixture[cursor]
.as_u64()
.expect("valid Architect replay fixture") as usize,
),
)
.expect("valid Architect replay fixture");
assert_eq!(game.actions_left, actions_left);
if cursor != "pending" {
assert!(
game.players[1]
.wonders_built
.contains(&server::wonder::Wonder::GreatWall)
);
}
// Both independent rule boundaries preserve precisely the retained prefix.
assert_eq!(
game.aggressor_eligibility_from,
Some(game_api::log_length(&game) + 1)
);
assert_eq!(
game.great_architect_action_cost_from,
Some(game_api::log_length(&game) + 1)
);
}
}
#[test]
fn legacy_pending_payment_resumes_free_but_branch_before_card_pays_once() {
let fixture = fixture();
let history = || {
serde_json::from_value(fixture["history"].clone()).expect("valid Architect replay fixture")
};
let payment: Action = serde_json::from_value(
json!({"Response":{"Payment":[{"food":3,"wood":2,"ore":7,"culture_tokens":2}]}}),
)
.expect("valid Architect replay fixture");
let pending = replay(
history(),
Some(
fixture["pending"]
.as_u64()
.expect("valid Architect replay fixture") as usize,
),
)
.expect("valid Architect replay fixture");
let resumed = game_api::execute(pending, payment.clone(), 1);
assert_eq!(resumed.actions_left, 3);
let before = replay(
history(),
Some(
fixture["before"]
.as_u64()
.expect("valid Architect replay fixture") as usize,
),
)
.expect("valid Architect replay fixture");
let new = game_api::execute(before, Action::Playing(PlayingAction::ActionCard(155)), 1);
assert_eq!(new.actions_left, 2);
let new = game_api::execute(new, payment, 1);
assert_eq!(new.actions_left, 2);
let saved = serde_json::to_value(new.cloned_data()).expect("valid Architect replay fixture");
let replayed = replay(
serde_json::from_value(saved).expect("valid Architect replay fixture"),
None,
)
.expect("valid Architect replay fixture");
assert_eq!(replayed.actions_left, 2);
assert_eq!(replayed.players[1].resources, new.players[1].resources);
}
#[test]
fn independent_aggressor_boundary_survives_full_partial_and_new_history_replay() {
let fixture = fixture();
let before = fixture["before"].as_u64().unwrap() as usize;
for boundary in [0, before, before + 4] {
let mut history = fixture["history"].clone();
history["aggressor_eligibility_from"] = json!(boundary);
let partial = replay(
serde_json::from_value(history.clone()).unwrap(),
Some(before),
)
.unwrap();
assert_eq!(
partial.aggressor_eligibility_from,
Some(boundary.min(before + 1))
);
let full = replay(serde_json::from_value(history).unwrap(), None).unwrap();
assert_eq!(full.aggressor_eligibility_from, Some(boundary));
let saved = serde_json::to_value(full.cloned_data()).unwrap();
let replayed = replay(serde_json::from_value(saved).unwrap(), None).unwrap();
assert_eq!(replayed.aggressor_eligibility_from, Some(boundary));
}
}
#[test]
fn architect_redo_keeps_recorded_cost_policy_but_replacing_future_charges() {
let fixture = fixture();
let history = || serde_json::from_value(fixture["history"].clone()).unwrap();
for legacy in [false, true] {
let pending = if legacy {
replay(
history(),
Some(fixture["pending"].as_u64().unwrap() as usize),
)
.unwrap()
} else {
let before = replay(
history(),
Some(fixture["before"].as_u64().unwrap() as usize),
)
.unwrap();
game_api::execute(before, Action::Playing(PlayingAction::ActionCard(155)), 1)
};
let boundary = pending.great_architect_action_cost_from;
assert_eq!(pending.actions_left, if legacy { 3 } else { 2 });
let undone = game_api::execute(pending, Action::Undo, 1);
assert_eq!(undone.actions_left, 3);
assert_eq!(undone.great_architect_action_cost_from, boundary);
let redone = game_api::execute(undone.clone(), Action::Redo, 1);
assert_eq!(redone.actions_left, if legacy { 3 } else { 2 });
assert_eq!(redone.great_architect_action_cost_from, boundary);
let branch = game_api::execute(undone, Action::Playing(PlayingAction::ActionCard(155)), 1);
assert_eq!(branch.actions_left, 2);
assert_eq!(
branch.great_architect_action_cost_from,
Some(fixture["pending"].as_u64().unwrap() as usize)
);
}
}

View file

@ -174,6 +174,7 @@ fn builder_removes_only_objectives_requiring_player_combat() {
"Naval Assault",
"Scavenger",
"Brutus",
"Aggressor",
];
assert_eq!(
builder.get_objective_cards().len(),

View file

@ -152,6 +152,12 @@ fn clean_json(expected: &str) -> String {
.unwrap()
.remove("finalized_combat_from");
}
if value["aggressor_eligibility_from"] == serde_json::json!(usize::MAX) {
value
.as_object_mut()
.unwrap()
.remove("aggressor_eligibility_from");
}
// Only public action-log items qualify, never arbitrary arrays or game state.
if let Some(ages) = value
.get_mut("log")
@ -484,6 +490,9 @@ pub fn load_game(path: &GamePath) -> Game {
if game.asynchronous_combat_from.is_none() {
game.asynchronous_combat_from = Some(usize::MAX);
}
if game.aggressor_eligibility_from.is_none() {
game.aggressor_eligibility_from = Some(usize::MAX);
}
if update_expected() {
write_result(&to_json(&game), path);
}

File diff suppressed because it is too large Load diff

View file

@ -5,6 +5,8 @@
"version": 2,
"asynchronous_combat_from": 0,
"finalized_combat_from": 0,
"great_architect_action_cost_from": 0,
"aggressor_eligibility_from": 0,
"home_layout": "ClockwiseV1",
"state": "ChooseCivilization",
"players": [

View file

@ -1,4 +1,5 @@
{
"great_architect_action_cost_from": 3,
"state": "Playing",
"players": [
{
@ -373,6 +374,17 @@
}
},
"player": 0,
"items": [
{
"player": 0,
"Action": {
"balance": "Pay"
},
"origin": {
"Ability": "Build Wonder"
}
}
],
"active_events": 2
},
{
@ -448,7 +460,7 @@
],
"log_index": 5,
"undo_limit": 1,
"actions_left": 2,
"actions_left": 1,
"round": 2,
"age": 1,
"messages": [

View file

@ -1834,3 +1834,23 @@ viewer and engine together. Preserve catalog 8 / 46 definitions, artwork 4, all
60 named assets, gallery, Standard options, settings and preferences. Only the
artwork manifest's lockfile integrity pin changes; no artwork is republished and
no production game edits, repairs, backfills or history rewrites are performed.
# Viewer 0.1.240 / engine 0.4.171 — Aggressor and Great Architect
Aggressor now requires starting a land battle against another human player and
eliminating at least two army units, without requiring victory. Great Architect
remains a free public modifier with its three-culture discount and prerequisite
waiver, but ordinary wonder construction costs one action. Engineering and the
existing city-specific Nebuchadnezzar/Qin exemptions remain unchanged; Shogunate
does not waive this construction. Independent persisted boundaries preserve old
awards, historical replay and already-started Architect operations, while new
branches adopt the corrections. Legacy Builder caches retain historical Aggressor
claims without changing seeded deals. Native and web undo retain all four rule
boundaries. See `docs/aggressor-eligibility.md` and
`docs/great-architect-action-cost.md` for scope and frozen old-engine evidence.
Require exact-commit Check and Web viewer CI green before publishing matching
frozen artifacts. Verify 39 viewer files and engine bytes, catalog 8 / 46 entries,
artwork 4, all 60 named assets and unchanged gallery, Standard options, preferences
and settings. Only the artwork manifest's lockfile pin changes. No production
moves, repairs, backfills, point changes or historical save writes are performed.

View file

@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.239",
"version": "0.1.240",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
"version": "0.1.239",
"version": "0.1.240",
"dependencies": {
"@boardgamers/protocol": "0.11.0",
"lucide-svelte": "^0.577.0",

View file

@ -1,13 +1,13 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.239",
"version": "0.1.240",
"private": true,
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 8643",
"build": "vite build",
"check": "svelte-check --tsconfig ./tsconfig.json",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs ../scripts/withdrawal.test.cjs ../scripts/viking-cargo.test.cjs",
"test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs ../scripts/withdrawal.test.cjs ../scripts/viking-cargo.test.cjs ../scripts/aggressor.test.cjs ../scripts/great-architect.test.cjs",
"test:boarding": "npm run build:bridge && npm run build && node --test scripts/boarding.test.mjs && node scripts/boarding-smoke.mjs",
"test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs",
"build:achievement-assets": "node scripts/build-achievement-assets.mjs",

View file

@ -13,7 +13,7 @@
"web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0",
"web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b",
"server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332",
"web-client/package-lock.json": "4e6b5fb67d993f97e8d2faef7943aa29ae78787f62930d97879cc6ac30415434",
"web-client/package-lock.json": "ecba98cab2766ff0ecf4278b50ee5aa9a78e2d63edf31e0f6c9bc20a060b3fe6",
"web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be",
"web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a",
"web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db"

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-server",
"version": "0.4.170",
"version": "0.4.171",
"description": "Clash of Cultures: Monumental edition engine for Boardgamers Space",
"license": "MIT",
"type": "commonjs",

View file

@ -0,0 +1,80 @@
// Real engine, normal viewer clicks; only the frozen synthetic legal history is used.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createRequire } from 'node:module';
import path from 'node:path';
import { chromium } from 'playwright';
const engine = createRequire(import.meta.url)(process.env.CLASH_WASM || '../.engine/server.js');
const dist = process.env.CLASH_VIEWER_DIR || new URL('../dist/', import.meta.url).pathname;
const fixture = JSON.parse(
await readFile(new URL('../../server/tests/fixtures/legacy_architect_170.json', import.meta.url)),
);
const browser = await chromium.launch({
headless: true,
args: ['--use-gl=angle', '--use-angle=swiftshader'],
});
try {
for (const width of [1400, 390]) {
for (const legacy of [false, true]) {
let state = JSON.parse(
engine.replay(JSON.stringify(fixture.history), { to: fixture[legacy ? 'pending' : 'before'] }),
);
const page = await browser.newPage({ viewport: { width, height: 900 } });
const errors = [],
moves = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.exposeFunction('applyMove', async (action) => {
const parsed = typeof action === 'string' ? JSON.parse(action) : action;
state = JSON.parse(engine.tryMove(JSON.stringify(state), JSON.stringify(parsed), 1));
moves.push(parsed);
await page.evaluate((raw) => host.emit('state', raw), engine.stripSecret(JSON.stringify(state), 1));
});
await page.route('**/*', async (route) => {
const url = new URL(route.request().url());
if (url.hostname !== 'clash.test') return route.abort();
if (url.pathname === '/')
return route.fulfill({
contentType: 'text/html',
body: '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><div id="app"></div><script src="/viewer.js"></script>',
});
return route.fulfill({
contentType: url.pathname.endsWith('.wasm') ? 'application/wasm' : 'text/javascript',
body: await readFile(path.join(dist, url.pathname)),
});
});
await page.goto('http://clash.test/');
await page.evaluate(
(raw) => {
window.host = clash3d.launch('#app');
host.on('move', (action) => window.applyMove(action));
host.emit('player', { index: 1 });
host.emit('preferences', { sound: false });
host.emit('state', raw);
},
engine.stripSecret(JSON.stringify(state), 1),
);
if (!legacy) {
await page.getByRole('button', { name: /^Wonders:/ }).click();
await page.getByRole('button', { name: 'Use Great Architect', exact: true }).click();
}
const pay = page.locator('.decision-panel').getByRole('button', { name: /^Pay / });
await pay.waitFor();
assert.equal(state.actions_left, legacy ? 3 : 2);
await pay.click();
await page.waitForFunction(() => !document.querySelector('.decision-panel'));
assert.equal(moves.length, legacy ? 1 : 2);
assert.equal(state.actions_left, legacy ? 3 : 2);
assert.ok(state.players[1].wonders_built.includes('GreatWall'));
assert.ok(!state.players[1].action_cards.includes(155));
assert.equal(await page.getByRole('alert').count(), 0);
assert.deepEqual(errors, []);
await page.screenshot({ path: `/tmp/clash-architect-${legacy ? 'legacy' : 'new'}-${width}.png` });
console.log(
`${width}px ${legacy ? 'legacy pending stays free' : 'new Architect costs one action'}: real payment and wonder verified`,
);
await page.close();
}
}
} finally {
await browser.close();
}

View file

@ -947,3 +947,21 @@ test('known local Calendar stays local across an optimistic move acknowledgement
assert.equal(app.session().view!.canUndo, true);
} finally { app.close(); }
});
test('predicted undo preserves all independent persisted rule boundaries', () => {
const previous = { log_index: 0, log: [{ rounds: [{ turns: [{ actions: [] }] }] }] };
const boundaries = {
asynchronous_combat_from: 3,
finalized_combat_from: 4,
great_architect_action_cost_from: 5,
aggressor_eligibility_from: 1,
};
const current = {
...previous,
...boundaries,
log_index: 1,
log: [{ rounds: [{ turns: [{ actions: [{ action: ore }] }] }] }],
};
const undone = JSON.parse(predictUndo(JSON.stringify(previous), JSON.stringify(current))!);
for (const [field, value] of Object.entries(boundaries)) assert.equal(undone[field], value);
});

View file

@ -193,6 +193,17 @@ export function predictUndo(previous: string, current: string): string | null {
delete undone.combat_stats;
delete undone.undo;
before.log = log;
// Rule-version boundaries are excluded from native undo patches too. Keep
// the current boundary when undoing the first action of an upgraded save.
for (const field of [
'asynchronous_combat_from',
'finalized_combat_from',
'great_architect_action_cost_from',
'aggressor_eligibility_from',
]) {
if (after[field] !== undefined) before[field] = after[field];
else delete before[field];
}
delete before.early_choice_update;
// Calendar may let the triggering action be undone while sealing everything
// before it, as if the owner had peeked first. Knowledge is not rewound.