From 19d5c33d440797221fa91b2c3994d2f4974b8c93 Mon Sep 17 00:00:00 2001
From: coyotte508
Date: Mon, 2 Nov 2026 00:14:01 +0000
Subject: [PATCH] Fix tactics, action queues, clock credits and wonder
performance; release 0.4.125
---
server/src/action_queue.rs | 84 +-
server/src/board_history.rs | 28 +-
server/src/content/action_cards/spy.rs | 7 +-
server/src/content/civilizations/celts.rs | 32 +-
server/src/content/tactics_cards.rs | 11 +-
server/src/game.rs | 7 +-
server/src/game_api.rs | 64 +-
server/src/game_api_wrapper.rs | 28 +-
server/src/game_data.rs | 12 +-
server/src/game_setup.rs | 2 +
server/src/lib.rs | 7 +-
server/src/payment.rs | 201 +++--
server/src/payment_search_tests.rs | 260 ++++++
server/src/replay.rs | 9 +
server/src/tactics_card.rs | 80 +-
server/src/timing.rs | 80 ++
server/src/undo.rs | 9 +-
server/src/unit.rs | 2 +-
server/src/web_view/combat_estimate.rs | 34 +
server/src/web_view/decisions.rs | 66 +-
server/tests/action_queue_tests.rs | 479 ++++++++++-
server/tests/card_privacy_tests.rs | 523 ++++++++++++
server/tests/scouts_tests.rs | 455 +++++++++++
server/tests/timing_tests.rs | 358 +++++++++
server/tests/wonder_payment_tests.rs | 168 ++++
web-client/README.md | 2 +-
web-client/docs/viewer-publishing.md | 25 +
web-client/package-lock.json | 4 +-
web-client/package.json | 2 +-
web-client/release/engine-checks.json | 5 +-
.../scripts/egypt-collect-queue-fixture.json | 749 ++++++++++++++++++
web-client/scripts/release-engine-check.mjs | 17 +-
web-client/scripts/tactics-choices-smoke.mjs | 1 +
web-client/scripts/timing-check.mjs | 91 +++
web-client/scripts/wonder-payment-perf.mjs | 58 ++
web-client/src/DecisionPanel.svelte | 18 +-
web-client/src/action-queue.test.ts | 57 ++
web-client/src/decision-controls.test.ts | 44 +
web-client/src/decision-controls.ts | 11 +
web-client/src/localization/da.json | 3 +
web-client/src/localization/de.json | 3 +
web-client/src/localization/el.json | 3 +
web-client/src/localization/en.json | 3 +
web-client/src/localization/fa.json | 3 +
web-client/src/localization/fr.json | 3 +
web-client/src/localization/hi.json | 3 +
web-client/src/localization/it.json | 3 +
web-client/src/localization/ko.json | 3 +
web-client/src/localization/nl.json | 3 +
web-client/src/localization/pl.json | 3 +
web-client/src/localization/pt-BR.json | 3 +
web-client/src/localization/ro.json | 3 +
web-client/src/localization/ru.json | 3 +
web-client/src/localization/vi.json | 3 +
web-client/src/localization/zh-CN.json | 3 +
web-client/src/localization/zh-TW.json | 3 +
web-client/src/prediction.test.ts | 68 ++
web-client/src/prediction.ts | 13 +
web-client/src/types.ts | 1 +
59 files changed, 4043 insertions(+), 180 deletions(-)
create mode 100644 server/src/payment_search_tests.rs
create mode 100644 server/src/timing.rs
create mode 100644 server/tests/card_privacy_tests.rs
create mode 100644 server/tests/scouts_tests.rs
create mode 100644 server/tests/timing_tests.rs
create mode 100644 server/tests/wonder_payment_tests.rs
create mode 100644 web-client/scripts/egypt-collect-queue-fixture.json
create mode 100644 web-client/scripts/timing-check.mjs
create mode 100644 web-client/scripts/wonder-payment-perf.mjs
diff --git a/server/src/action_queue.rs b/server/src/action_queue.rs
index 3e75e697..31218375 100644
--- a/server/src/action_queue.rs
+++ b/server/src/action_queue.rs
@@ -43,40 +43,78 @@ pub fn offer(game: &Game, player: usize) -> Option<(String, String)> {
{
"Choosing an advance"
}
- (PersistentEventType::Incident(i), EventOrigin::Incident(id),
- PersistentEventRequest::SelectPositions(request))
- if i.active_player == player && *id == i.incident_id
- && [27, 28, 34, 35].contains(id) && handler.priority == 11
- && i.selected_player == Some(game.active_player())
- && request.choices.iter().all(|position|
- game.player(game.active_player()).cities.iter().any(|city| city.position == *position)) =>
+ (
+ PersistentEventType::Incident(i),
+ EventOrigin::Incident(id),
+ PersistentEventRequest::SelectPositions(request),
+ ) if i.active_player == player
+ && *id == i.incident_id
+ && [27, 28, 34, 35].contains(id)
+ && handler.priority == 11
+ && i.selected_player == Some(game.active_player())
+ && request.choices.iter().all(|position| {
+ game.player(game.active_player())
+ .cities
+ .iter()
+ .any(|city| city.position == *position)
+ }) =>
{
"Placing a settler"
}
- (PersistentEventType::Incident(i), EventOrigin::Incident(id),
- PersistentEventRequest::Payment(requests))
- if i.active_player == player && *id == i.incident_id
- && !i.consumed && !i.replaced_by_sacrifice && i.selected_player.is_none()
- && game.cache.get_incident(*id).action_card.is_some()
- && handler.priority == 10
- && requests.iter().any(|request| request.name == "Pay to gain the Action Card") =>
+ (
+ PersistentEventType::Incident(i),
+ EventOrigin::Incident(id),
+ PersistentEventRequest::Payment(requests),
+ ) if i.active_player == player
+ && *id == i.incident_id
+ && !i.consumed
+ && !i.replaced_by_sacrifice
+ && i.selected_player.is_none()
+ && game.cache.get_incident(*id).action_card.is_some()
+ && handler.priority == 10
+ && requests
+ .iter()
+ .any(|request| request.name == "Pay to gain the Action Card") =>
{
game.cache.get_incident(*id).name.as_str()
}
- (PersistentEventType::Incident(i), EventOrigin::Incident(id),
- PersistentEventRequest::SelectPlayer(_))
- if i.active_player == player && *id == 57 && i.incident_id == *id
- && handler.priority == 1 && i.selected_player == Some(game.active_player()) =>
+ (
+ PersistentEventType::Incident(i),
+ EventOrigin::Incident(id),
+ PersistentEventRequest::SelectPlayer(_),
+ ) if i.active_player == player
+ && *id == 57
+ && i.incident_id == *id
+ && handler.priority == 1
+ && i.selected_player == Some(game.active_player()) =>
{
"Choose a player"
}
+ (
+ PersistentEventType::Incident(i),
+ EventOrigin::Incident(47),
+ PersistentEventRequest::ResourceReward(_),
+ ) if i.active_player == player
+ && i.incident_id == 47
+ && !i.consumed
+ && !i.replaced_by_sacrifice
+ && i.selected_player.is_none()
+ && handler.priority == 0 =>
+ {
+ // Only Era of Stability's reward, never its earlier exhausted-land
+ // choice or another incident's resource/mood effects.
+ "Choose resources"
+ }
_ => return None,
};
- // Passing a Great Person to another recipient (or choosing a Diplomat
- // partner) continues the same unresolved reaction. Preserve queued actions
- // and the explicit Wait preference while that reaction progresses.
- if let Some(plan) = game.action_plan.as_ref().filter(|plan|
- plan.player == player && plan.error.is_none()) {
+ // Passing a Great Person to another recipient, choosing a Diplomat partner,
+ // or handing off Era of Stability rewards continues the same unresolved
+ // reaction. Preserve queued actions and the explicit Wait preference.
+ if let Some(plan) = game
+ .action_plan
+ .as_ref()
+ .filter(|plan| plan.player == player && plan.error.is_none())
+ {
return Some((plan.key.clone(), label.into()));
}
let key = format!(
diff --git a/server/src/board_history.rs b/server/src/board_history.rs
index e8e7ca24..8de97dcb 100644
--- a/server/src/board_history.rs
+++ b/server/src/board_history.rs
@@ -158,15 +158,23 @@ fn title(action: &Action) -> String {
}
pub fn execute(game: Game, action: Action, player: usize) -> Result {
- if matches!(action, Action::QueueChoice { .. } | Action::QueueMoves { .. }) {
+ if matches!(
+ action,
+ Action::QueueChoice { .. } | Action::QueueMoves { .. }
+ ) {
return try_execute_action(game, action, player);
}
- let undo = matches!(action, Action::Undo);
+ let history_navigation = matches!(action, Action::Undo | Action::Redo);
let mut game = execute_one(game, action, player)?;
crate::early_choices::prune_objectives(&mut game);
+ // Navigating history must not start fresh automatic actions or resume plans:
+ // those could otherwise award credits (and make Undo immediately redo itself).
+ if history_navigation {
+ return Ok(game);
+ }
// Save automatic responses as ordinary actions. Replay then reproduces them
// without needing past settings; undo never immediately replays a skipped choice.
- while !undo && game.context == crate::game::GameContext::Play {
+ while game.context == crate::game::GameContext::Play {
if let Some(response) = crate::early_choices::take_ready(&mut game) {
let player = game.active_player();
game = execute_one(game, Action::Response(response), player)?;
@@ -175,10 +183,18 @@ pub fn execute(game: Game, action: Action, player: usize) -> Result Result ActionCard {
))
},
|game, s, a| {
- game.information_revealed(); // can't undo swap - the other player saw your card
+ if s.choice.is_empty() {
+ // Keep the existing undo boundary, but declining reveals no card.
+ game.lock_undo();
+ } else {
+ game.information_revealed(); // the other player saw your card
+ }
let _ = swap_spy_cards(
game,
diff --git a/server/src/content/civilizations/celts.rs b/server/src/content/civilizations/celts.rs
index 1377ebd5..aaae4e5f 100644
--- a/server/src/content/civilizations/celts.rs
+++ b/server/src/content/civilizations/celts.rs
@@ -162,7 +162,9 @@ pub(crate) fn loyalty_controller(game: &Game, c: &Combat) -> Option {
.find(|p| {
p.index != c.opponent(barb)
&& p.active_leader() == Some(Leader::Viriatus)
- && game.map.within_revealed_distance(leader_position(p), c.defender_position(), 2)
+ && game
+ .map
+ .within_revealed_distance(leader_position(p), c.defender_position(), 2)
})
.map(|p| p.index)
}
@@ -194,9 +196,33 @@ fn viriatus() -> LeaderInfo {
.add_hand_card_request(|e|&mut e.loyalty,0,|game,p,r|{
let barb=r.combat.players().into_iter().find(|id|game.player(*id).civilization.is_barbarian())?;
if get_combat_strength(barb,r).deny_tactics_card{return None;}
- let cards=p.get(game).action_cards.iter().filter(|id|crate::tactics_card::can_play_tactics_card(game,barb,game.cache.get_action_card(**id),&r.combat)).map(|id|HandCard::ActionCard(*id)).collect();
+ let cards=p.get(game).action_cards.iter().filter(|id|crate::tactics_card::can_play_tactics_card(game,barb,game.cache.get_action_card(**id),r)).map(|id|HandCard::ActionCard(*id)).collect();
Some(HandCardsRequest::new(cards,0..=1,"Loyalty · Play a tactics card for the Barbarians"))
- },|game,s,r|{if let Some(HandCard::ActionCard(id))=s.choice.first(){let barb=r.combat.players().into_iter().find(|id|game.player(*id).civilization.is_barbarian()).unwrap();game.player_mut(barb).custom_data.insert("Loyalty controller".into(),crate::player::Data::Number(s.player_index as u32));update_combat_strength(game,barb,r,|_,_,strength,_|strength.tactics_card=Some(*id));crate::action_card::discard_action_card(game,s.player_index,*id,&s.origin,HandCardLocation::PlayToDiscardFaceDown);}}).build())
+ }, |game, s, r| {
+ if let Some(HandCard::ActionCard(id)) = s.choice.first() {
+ let barb = r.combat.players().into_iter()
+ .find(|id| game.player(*id).civilization.is_barbarian())
+ .expect("Loyalty requires a Barbarian combatant");
+ assert!(
+ !get_combat_strength(barb, r).deny_tactics_card
+ && crate::tactics_card::can_play_tactics_card(
+ game, barb, game.cache.get_action_card(*id), r,
+ ),
+ "Tactics card requirements are not met"
+ );
+ game.player_mut(barb).custom_data.insert(
+ "Loyalty controller".into(),
+ crate::player::Data::Number(s.player_index as u32),
+ );
+ update_combat_strength(game, barb, r, |_, _, strength, _| {
+ strength.tactics_card = Some(*id);
+ });
+ crate::action_card::discard_action_card(
+ game, s.player_index, *id, &s.origin,
+ HandCardLocation::PlayToDiscardFaceDown,
+ );
+ }
+ }).build())
}
fn rapid_recruitment(mut b: LeaderAbilityBuilder) -> LeaderAbilityBuilder {
for i in 0..8u32 {
diff --git a/server/src/content/tactics_cards.rs b/server/src/content/tactics_cards.rs
index b5eb3f2e..6886d22f 100644
--- a/server/src/content/tactics_cards.rs
+++ b/server/src/content/tactics_cards.rs
@@ -8,7 +8,8 @@ use crate::game::Game;
use crate::position::Position;
use crate::resource_pile::ResourcePile;
use crate::tactics_card::{
- CombatLocation, CombatRole, FighterRequirement, TacticsCard, TacticsCardTarget,
+ CombatLocation, CombatRole, FighterRequirement, OpponentTacticsStatus, TacticsCard,
+ TacticsCardTarget, opponent_tactics_status,
};
use crate::unit::set_unit_position;
use crate::utils::a_or_an;
@@ -131,7 +132,8 @@ pub(crate) fn high_ground(id: u8) -> TacticsCard {
"Unless you attack a city: Your opponent can't use dice-symbol abilities this round.",
)
.location_requirement(CombatLocation::Land)
- .checker(|player, game, combat| {
+ .checker(|player, game, round| {
+ let combat = &round.combat;
combat.role(player) == CombatRole::Defender || combat.defender_city(game).is_none()
})
.target(TacticsCardTarget::Opponent)
@@ -253,7 +255,7 @@ pub(crate) fn tactical_retreat(id: u8) -> TacticsCard {
)
.fighter_requirement(FighterRequirement::Army)
.role_requirement(CombatRole::Defender)
- .checker(|_, game, c| !tactical_retreat_targets(c, game).is_empty())
+ .checker(|_, game, round| !tactical_retreat_targets(&round.combat, game).is_empty())
.add_position_request(
|event| &mut event.combat_round_start_tactics,
0,
@@ -311,6 +313,9 @@ pub(crate) fn scout(id: u8) -> TacticsCard {
"Scout",
"Ignore the enemy tactics card and take it to your hand.",
)
+ .checker(|player, game, round| {
+ opponent_tactics_status(game, player, round) != OpponentTacticsStatus::None
+ })
.add_simple_persistent_event_listener(
|event| &mut event.combat_round_start_reveal_tactics,
0,
diff --git a/server/src/game.rs b/server/src/game.rs
index 4f0d5def..b3f9c2f1 100644
--- a/server/src/game.rs
+++ b/server/src/game.rs
@@ -145,6 +145,10 @@ pub struct Game {
pub current_player_index: usize,
pub log: Vec,
pub board_history: crate::board_history::BoardHistory,
+ /// Monotonic platform credits; deliberately outside the undoable position.
+ pub(crate) time_increments: Vec,
+ /// Transient signal for one saved atomic action, not a persisted undo cursor.
+ pub(crate) timing_revealed: bool,
// index for the next action log
pub log_index: usize,
pub undo_limit: usize,
@@ -247,6 +251,7 @@ impl Game {
}
pub(crate) fn information_revealed(&mut self) {
+ self.timing_revealed = true;
self.lock_undo();
}
@@ -254,7 +259,7 @@ impl Game {
self.lock_undo();
}
- fn lock_undo(&mut self) {
+ pub(crate) fn lock_undo(&mut self) {
if self.context != GameContext::AI {
self.undo_limit = self.log_index;
current_turn_log_mut(self).clear_undo();
diff --git a/server/src/game_api.rs b/server/src/game_api.rs
index 248a110e..9144d88f 100644
--- a/server/src/game_api.rs
+++ b/server/src/game_api.rs
@@ -1,6 +1,7 @@
use super::player::Player;
use crate::action::execute_action;
use crate::card::{HandCard, HandCardLocation};
+use crate::combat_listeners::CombatEventPhase;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest, PersistentEventType,
@@ -146,8 +147,15 @@ pub fn civilizations(game: Game) -> Vec {
#[must_use]
pub fn strip_secret(mut game: Game, player_index: Option) -> Game {
- if game.action_plan.as_ref().is_some_and(|p| Some(p.player) != player_index) {game.action_plan=None;}
- game.early_choices.retain(|c| Some(c.player) == player_index);
+ if game
+ .action_plan
+ .as_ref()
+ .is_some_and(|p| Some(p.player) != player_index)
+ {
+ game.action_plan = None;
+ }
+ game.early_choices
+ .retain(|c| Some(c.player) == player_index);
if let Some(draft) = &mut game.civilization_draft {
for i in 0..draft.offers.len() {
if player_index != Some(i) {
@@ -210,7 +218,7 @@ fn strip_action(action: &mut ActionLogAction, player_index: Option) {
for item in &mut action.items {
if let ActionLogEntry::HandCard { card, from, to } = &mut item.entry
- && is_visible_card_info(player_index, from, to)
+ && !is_visible_card_info(player_index, from, to)
{
match &card {
HandCard::ActionCard(_) => *card = HandCard::ActionCard(0),
@@ -226,13 +234,13 @@ fn is_visible_card_info(
from: &HandCardLocation,
to: &HandCardLocation,
) -> bool {
- from.player() == player_index
- || to.player() == player_index
+ player_index.is_some_and(|player| from.player() == Some(player) || to.player() == Some(player))
|| from.is_public()
|| to.is_public()
}
fn strip_events(game: &mut Game, player_index: Option) {
+ let mut pending_tactics = Vec::new();
for s in &mut game.events {
match &mut s.event_type {
PersistentEventType::CustomAction(a)
@@ -248,11 +256,29 @@ fn strip_events(game: &mut Game, player_index: Option) {
}
}
}
- PersistentEventType::CombatRoundStart(r) => {
- if r.attacker_strength.tactics_card.is_some() {
- // defender shouldn't see attacker's tactics card
- r.attacker_strength.tactics_card = Some(0);
+ PersistentEventType::CombatRoundStart(r)
+ if matches!(
+ r.phase,
+ CombatEventPhase::AllowTacticsCard
+ | CombatEventPhase::Loyalty
+ | CombatEventPhase::Default
+ ) =>
+ {
+ // Committing immediately adds the card to the discard pile. Save
+ // the real IDs before replacing them with the presence sentinel.
+ for (card, participant) in [
+ (r.attacker_strength.tactics_card, r.combat.attacker()),
+ (r.defender_strength.tactics_card, r.combat.defender()),
+ ] {
+ if let Some(card) = card.filter(|id| *id != 0) {
+ pending_tactics.push((card, participant));
+ }
}
+ // Either side may commit first (Loyalty can supply the defender).
+ // Keep presence for eligibility/status, but never disclose the ID
+ // before reveal. Owners still see their own card in the transfer log.
+ r.attacker_strength.tactics_card = r.attacker_strength.tactics_card.map(|_| 0);
+ r.defender_strength.tactics_card = r.defender_strength.tactics_card.map(|_| 0);
}
PersistentEventType::SelectObjectives(o) if Some(s.player.index) != player_index => {
// player shouldn't see other player's objectives
@@ -279,4 +305,24 @@ fn strip_events(game: &mut Game, player_index: Option) {
}
}
}
+ pending_tactics.sort_unstable();
+ pending_tactics.dedup();
+ for (card, participant) in pending_tactics {
+ // The hand owner may be the Loyalty controller, not the combatant.
+ // Match discard_card's insertion end and mask only this commitment:
+ // an earlier, publicly discarded copy of the same ID can remain here.
+ let owner = crate::content::civilizations::celts::delegated_player(game, participant);
+ let discarded = &mut game.action_cards_discarded;
+ let position = if game.players[owner]
+ .wonders_owned
+ .contains(Wonder::GreatMausoleum)
+ {
+ discarded.iter().position(|id| *id == card)
+ } else {
+ discarded.iter().rposition(|id| *id == card)
+ };
+ if let Some(position) = position {
+ discarded[position] = 0;
+ }
+ }
}
diff --git a/server/src/game_api_wrapper.rs b/server/src/game_api_wrapper.rs
index 2388ae69..0e15a630 100644
--- a/server/src/game_api_wrapper.rs
+++ b/server/src/game_api_wrapper.rs
@@ -62,7 +62,9 @@ pub fn set_player_settings(
if settings.skip_raze_city.is_some() {
p.settings.skip_raze_city = settings.skip_raze_city;
}
- if settings.keep_government.is_some() { p.settings.keep_government = settings.keep_government; }
+ if settings.keep_government.is_some() {
+ p.settings.keep_government = settings.keep_government;
+ }
Ok(from_game(game))
}
@@ -181,8 +183,12 @@ pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) ->
if let Some(raw) = move_data.as_string()
&& let Ok(crate::action::Action::QueueMoves { key, .. }) = serde_json::from_str(&raw)
{
- return crate::action_queue::offer(&game, player).is_some_and(|(current,_)| current == key)
- || game.action_plan.as_ref().is_some_and(|p|p.player==player && p.key==key && p.error.is_some());
+ return crate::action_queue::offer(&game, player)
+ .is_some_and(|(current, _)| current == key)
+ || game
+ .action_plan
+ .as_ref()
+ .is_some_and(|p| p.player == player && p.key == key && p.error.is_some());
}
if let Some(raw) = move_data.as_string()
&& let Ok(crate::action::Action::QueueChoice { key, response }) = serde_json::from_str(&raw)
@@ -208,9 +214,19 @@ pub fn can_move_out_of_turn(data: String, move_data: JsValue, player: usize) ->
#[wasm_bindgen(js_name = "isLiveUpdate")]
pub fn is_live_update(data: String) -> bool {
let game = get_game(data);
- game.early_choice_update || game
- .civilization_draft
- .is_some_and(|draft| draft.live_update)
+ game.early_choice_update
+ || game
+ .civilization_draft
+ .is_some_and(|draft| draft.live_update)
+}
+
+/// Protocol clock hook: a JS array of cumulative human-seat credits, not JSON.
+#[wasm_bindgen(js_name = "timeIncrements")]
+pub fn time_increments(data: String) -> JsValue {
+ with_view_game(data, |game| {
+ serde_wasm_bindgen::to_value(&crate::timing::time_increments(game))
+ .expect("time increments should serialize")
+ })
}
#[wasm_bindgen(js_name = "logLength")]
diff --git a/server/src/game_data.rs b/server/src/game_data.rs
index de5a541c..353603dc 100644
--- a/server/src/game_data.rs
+++ b/server/src/game_data.rs
@@ -64,6 +64,12 @@ pub struct GameData {
skip_serializing_if = "crate::board_history::BoardHistory::is_empty"
)]
board_history: crate::board_history::BoardHistory,
+ #[serde(
+ default,
+ skip_serializing_if = "Vec::is_empty",
+ deserialize_with = "crate::timing::deserialize_counters"
+ )]
+ time_increments: Vec,
log_index: usize,
undo_limit: usize,
actions_left: u32,
@@ -136,6 +142,8 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
successful_cultural_influence: data.successful_cultural_influence,
log: data.log,
board_history: data.board_history,
+ time_increments: data.time_increments,
+ timing_revealed: false,
log_index: data.log_index,
undo_limit: data.undo_limit,
round: data.round,
@@ -161,7 +169,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
if game.options.legacy_undo.take().as_deref() == Some("SamePlayer") {
game.undo_limit = game.log_index;
if !game.log.is_empty() {
- game.information_revealed();
+ game.lock_undo();
}
}
for player_data in data.players {
@@ -192,6 +200,7 @@ pub fn data(game: Game) -> GameData {
current_player_index: game.current_player_index,
log: game.log,
board_history: game.board_history,
+ time_increments: game.time_increments,
log_index: game.log_index,
undo_limit: game.undo_limit,
actions_left: game.actions_left,
@@ -232,6 +241,7 @@ pub fn cloned_data(game: &Game) -> GameData {
current_player_index: game.current_player_index,
log: game.log.clone(),
board_history: game.board_history.clone(),
+ time_increments: game.time_increments.clone(),
log_index: game.log_index,
undo_limit: game.undo_limit,
actions_left: game.actions_left,
diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs
index 6d0d759e..b193bcc3 100644
--- a/server/src/game_setup.rs
+++ b/server/src/game_setup.rs
@@ -210,6 +210,8 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game {
current_player_index: starting_player,
log: Vec::new(),
board_history: Default::default(),
+ time_increments: vec![],
+ timing_revealed: false,
log_index: 0,
undo_limit: 0,
actions_left: ACTIONS,
diff --git a/server/src/lib.rs b/server/src/lib.rs
index 9552e105..861e457d 100644
--- a/server/src/lib.rs
+++ b/server/src/lib.rs
@@ -13,10 +13,9 @@ extern crate core;
pub mod ability_initializer;
pub mod action;
-pub mod early_choices;
-pub mod action_queue;
pub mod action_card;
mod action_cost;
+pub mod action_queue;
pub mod advance;
#[cfg(not(target_arch = "wasm32"))]
pub mod ai;
@@ -43,11 +42,11 @@ pub mod construct;
pub mod consts;
pub mod content;
pub mod cultural_influence;
+pub mod early_choices;
pub mod events;
mod explore;
pub mod game;
pub mod game_api;
-mod move_summary;
pub mod game_api_wrapper;
pub mod game_data;
pub mod game_setup;
@@ -58,6 +57,7 @@ mod leader_ability;
pub mod log;
pub mod map;
mod move_routes;
+mod move_summary;
pub mod movement;
pub mod objective_card;
pub mod payment;
@@ -75,6 +75,7 @@ mod special_advance;
pub mod status_phase;
pub mod structure;
pub mod tactics_card;
+pub mod timing;
mod undo;
pub mod unit;
pub mod utils;
diff --git a/server/src/payment.rs b/server/src/payment.rs
index 85df82fe..15280709 100644
--- a/server/src/payment.rs
+++ b/server/src/payment.rs
@@ -427,6 +427,78 @@ pub fn can_convert(
)
}
+// Bounds describe only directions, not amounts: if no remaining conversion can
+// decrease a resource, an excess can never become affordable. For an exact
+// payment, a missing resource must likewise still be producible. The total is
+// included to reject under/overpayment of one-for-one exchanges immediately.
+// These are necessary conditions only; the ordinary search still proves every
+// accepted payment, including chained exchanges, discounts and alternatives.
+#[derive(Clone, Copy, Default)]
+struct ConversionBounds {
+ decreases: u16,
+ increases: u16,
+}
+
+fn payment_amounts(pile: &ResourcePile) -> [u16; 9] {
+ let amounts = [
+ pile.food,
+ pile.wood,
+ pile.ore,
+ pile.ideas,
+ pile.gold,
+ pile.mood_tokens,
+ pile.culture_tokens,
+ pile.captives,
+ ]
+ .map(u16::from);
+ [
+ amounts[0],
+ amounts[1],
+ amounts[2],
+ amounts[3],
+ amounts[4],
+ amounts[5],
+ amounts[6],
+ amounts[7],
+ amounts.into_iter().sum(),
+ ]
+}
+
+impl ConversionBounds {
+ fn include(&mut self, from: &ResourcePile, to: &ResourcePile) {
+ for (i, (from, to)) in payment_amounts(from)
+ .into_iter()
+ .zip(payment_amounts(to))
+ .enumerate()
+ {
+ if from > to {
+ self.decreases |= 1 << i;
+ }
+ if from < to {
+ self.increases |= 1 << i;
+ }
+ }
+ }
+
+ fn allows(&self, current: &ResourcePile, available: &[u16; 9], exact: bool) -> bool {
+ payment_amounts(current)
+ .into_iter()
+ .zip(available)
+ .enumerate()
+ .all(|(i, (current, &available))| {
+ (current <= available || self.decreases & (1 << i) != 0)
+ && (!exact || current >= available || self.increases & (1 << i) != 0)
+ })
+ }
+}
+
+struct ConversionStep<'a> {
+ from: &'a ResourcePile,
+ to: &'a ResourcePile,
+ upper_limit: u8,
+ bounds: ConversionBounds,
+}
+
fn find_conversion(
available: &ResourcePile,
current: &ResourcePile,
@@ -435,6 +507,55 @@ fn find_conversion(
discount_left: u8,
may_overpay: bool,
exact: bool,
+) -> Option {
+ // Flatten in exactly the old traversal order. Bounds for each suffix are
+ // built once, instead of rescanning conversions at every search node.
+ let mut steps: Vec<_> = conversions
+ .iter()
+ .enumerate()
+ .flat_map(|(i, conversion)| {
+ let upper_limit = match conversion.payment_conversion_type {
+ PaymentConversionType::Unlimited => u8::MAX,
+ PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i,
+ };
+ conversion
+ .from
+ .iter()
+ .skip(if i == 0 { skip_from } else { 0 })
+ .map(move |from| ConversionStep {
+ from,
+ to: &conversion.to,
+ upper_limit,
+ bounds: ConversionBounds::default(),
+ })
+ })
+ .collect();
+ let mut bounds = ConversionBounds::default();
+ for step in steps.iter_mut().rev() {
+ if step.upper_limit > 0 {
+ bounds.include(step.from, step.to);
+ }
+ step.bounds = bounds;
+ }
+ find_payment_steps(
+ available,
+ &payment_amounts(available),
+ current,
+ &steps,
+ discount_left,
+ may_overpay,
+ exact,
+ )
+}
+
+fn find_payment_steps(
+ available: &ResourcePile,
+ available_amounts: &[u16; 9],
+ current: &ResourcePile,
+ steps: &[ConversionStep<'_>],
+ discount_left: u8,
+ may_overpay: bool,
+ exact: bool,
) -> Option {
if (if exact {
available == current
@@ -444,73 +565,49 @@ fn find_conversion(
{
return Some(current.clone());
}
-
- if conversions.is_empty() {
+ let (step, rest) = steps.split_first()?;
+ if !step.bounds.allows(current, available_amounts, exact) {
return None;
}
- let conversion = &conversions[0];
- if skip_from >= conversion.from.len() {
- return find_conversion(
- available,
- current,
- &conversions[1..],
- 0,
- discount_left,
- may_overpay,
- exact,
- );
- }
- let from = &conversion.from[skip_from];
- let upper_limit = match conversion.payment_conversion_type {
- PaymentConversionType::Unlimited => u8::MAX,
- PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i,
- };
-
- for amount in 1..=upper_limit {
- if !current.has_at_least_times(from, amount)
- || (conversion.to.is_empty() && amount > discount_left)
+ for amount in 1..=step.upper_limit {
+ if !current.has_at_least_times(step.from, amount)
+ || (step.to.is_empty() && amount > discount_left)
{
- return find_conversion(
- available,
- current,
- conversions,
- skip_from + 1,
- discount_left,
- may_overpay,
- exact,
- );
+ break;
}
-
- let mut current = current.clone();
+ let mut next = current.clone();
for _ in 0..amount {
- current -= from.clone();
- current += conversion.to.clone();
+ next -= step.from.clone();
+ next += step.to.clone();
}
- let new_discount_left = if conversion.to.is_empty() {
+ let new_discount_left = if step.to.is_empty() {
discount_left - amount
} else {
discount_left
};
-
- let can = find_conversion(
+ if let Some(payment) = find_payment_steps(
available,
- ¤t,
- conversions,
- skip_from + 1,
+ available_amounts,
+ &next,
+ rest,
new_discount_left,
may_overpay,
exact,
- );
- if can.is_some() {
- return can;
+ ) {
+ return Some(payment);
}
}
- // A usable conversion can still lead to an unaffordable payment. Try the
- // remaining alternatives against the original cost before giving up.
- find_conversion(
- available, current, conversions, skip_from + 1,
- discount_left, may_overpay, exact,
+ // A usable conversion can still lead to an unaffordable payment. Keep the
+ // original cost available to the remaining conversions as well.
+ find_payment_steps(
+ available,
+ available_amounts,
+ current,
+ rest,
+ discount_left,
+ may_overpay,
+ exact,
)
}
@@ -953,3 +1050,7 @@ impl CustomCost {
}
}
}
+
+#[cfg(test)]
+#[path = "payment_search_tests.rs"]
+mod search_tests;
diff --git a/server/src/payment_search_tests.rs b/server/src/payment_search_tests.rs
new file mode 100644
index 00000000..7210622a
--- /dev/null
+++ b/server/src/payment_search_tests.rs
@@ -0,0 +1,260 @@
+//! Differential regression for the search pruning. Keep the original exhaustive
+//! traversal here as a small-input oracle, independent of bounds/flattening.
+use super::*;
+
+fn exhaustive_conversion(
+ available: &ResourcePile,
+ current: &ResourcePile,
+ conversions: &[&PaymentConversion],
+ skip_from: usize,
+ discount_left: u8,
+ may_overpay: bool,
+ exact: bool,
+) -> Option {
+ if (if exact {
+ available == current
+ } else {
+ available.has_at_least(current)
+ }) && (discount_left == 0 || may_overpay)
+ {
+ return Some(current.clone());
+ }
+
+ if conversions.is_empty() {
+ return None;
+ }
+ let conversion = &conversions[0];
+ if skip_from >= conversion.from.len() {
+ return exhaustive_conversion(
+ available,
+ current,
+ &conversions[1..],
+ 0,
+ discount_left,
+ may_overpay,
+ exact,
+ );
+ }
+ let from = &conversion.from[skip_from];
+
+ let upper_limit = match conversion.payment_conversion_type {
+ PaymentConversionType::Unlimited => u8::MAX,
+ PaymentConversionType::MayOverpay(i) | PaymentConversionType::MayNotOverpay(i) => i,
+ };
+
+ for amount in 1..=upper_limit {
+ if !current.has_at_least_times(from, amount)
+ || (conversion.to.is_empty() && amount > discount_left)
+ {
+ return exhaustive_conversion(
+ available,
+ current,
+ conversions,
+ skip_from + 1,
+ discount_left,
+ may_overpay,
+ exact,
+ );
+ }
+
+ let mut current = current.clone();
+ for _ in 0..amount {
+ current -= from.clone();
+ current += conversion.to.clone();
+ }
+ let new_discount_left = if conversion.to.is_empty() {
+ discount_left - amount
+ } else {
+ discount_left
+ };
+
+ let can = exhaustive_conversion(
+ available,
+ ¤t,
+ conversions,
+ skip_from + 1,
+ new_discount_left,
+ may_overpay,
+ exact,
+ );
+ if can.is_some() {
+ return can;
+ }
+ }
+ // A usable conversion can still lead to an unaffordable payment. Try the
+ // remaining alternatives against the original cost before giving up.
+ exhaustive_conversion(
+ available,
+ current,
+ conversions,
+ skip_from + 1,
+ discount_left,
+ may_overpay,
+ exact,
+ )
+}
+
+#[test]
+fn pruning_preserves_exact_and_affordable_payments() {
+ let gold = PaymentConversion::resource_options(
+ base_resources(),
+ ResourcePile::gold(1),
+ PaymentConversionType::Unlimited,
+ );
+ let mut architecture_from = base_resources();
+ architecture_from.extend([ResourcePile::culture_tokens(1), ResourcePile::gold(1)]);
+ let architecture = PaymentConversion::resource_options(
+ architecture_from,
+ ResourcePile::mood_tokens(1),
+ PaymentConversionType::Unlimited,
+ );
+ let mut scenarios = vec![
+ (
+ ResourcePile::new(2, 1, 0, 0, 0, 0, 1),
+ vec![gold.clone(), architecture],
+ 0,
+ false,
+ ),
+ // Expanding, chained and reversed-order exchanges must not be mistaken
+ // for fixed-total payments or currently unaffordable final payments.
+ (
+ ResourcePile::food(2),
+ vec![
+ PaymentConversion::unlimited(ResourcePile::wood(1), ResourcePile::gold(1)),
+ PaymentConversion::unlimited(ResourcePile::food(1), ResourcePile::wood(2)),
+ ],
+ 0,
+ false,
+ ),
+ (
+ ResourcePile::food(2) + ResourcePile::wood(2),
+ vec![
+ PaymentConversion::limited(
+ ResourcePile::food(1) + ResourcePile::wood(1),
+ ResourcePile::mood_tokens(1),
+ 1,
+ ),
+ PaymentConversion::unlimited(ResourcePile::mood_tokens(1), ResourcePile::gold(2)),
+ ],
+ 0,
+ false,
+ ),
+ (
+ ResourcePile::culture_tokens(2) + ResourcePile::mood_tokens(1),
+ vec![
+ PaymentConversion::unlimited(
+ ResourcePile::mood_tokens(1),
+ ResourcePile::culture_tokens(1),
+ ),
+ PaymentConversion::unlimited(
+ ResourcePile::culture_tokens(1),
+ ResourcePile::mood_tokens(1),
+ ),
+ ],
+ 0,
+ false,
+ ),
+ (
+ ResourcePile::culture_tokens(2) + ResourcePile::mood_tokens(1),
+ vec![PaymentConversion::resource_options(
+ vec![
+ ResourcePile::culture_tokens(1),
+ ResourcePile::mood_tokens(1),
+ ],
+ ResourcePile::captives(1),
+ PaymentConversionType::Unlimited,
+ )],
+ 0,
+ false,
+ ),
+ ];
+ for (discount, may_overpay) in [
+ (PaymentConversionType::MayNotOverpay(1), false),
+ (PaymentConversionType::MayOverpay(1), true),
+ ] {
+ scenarios.push((
+ ResourcePile::food(2) + ResourcePile::wood(1),
+ vec![
+ gold.clone(),
+ PaymentConversion::resource_options(
+ base_resources(),
+ ResourcePile::empty(),
+ discount,
+ ),
+ ],
+ 1,
+ may_overpay,
+ ));
+ }
+ for (current, conversions, discount_left, may_overpay) in scenarios {
+ for order in conversions.iter().permutations(conversions.len()) {
+ // Exhaust every small stock/payment across all six relevant types.
+ for mut index in 0..3_usize.pow(6) {
+ let mut pile = ResourcePile::empty();
+ for resource in [
+ ResourceType::Food,
+ ResourceType::Wood,
+ ResourceType::Gold,
+ ResourceType::MoodTokens,
+ ResourceType::CultureTokens,
+ ResourceType::Captives,
+ ] {
+ *pile.get_mut(&resource) = (index % 3) as u8;
+ index /= 3;
+ }
+ for exact in [false, true] {
+ for skip_from in [0, 1] {
+ assert_eq!(
+ find_conversion(
+ &pile,
+ ¤t,
+ &order,
+ skip_from,
+ discount_left,
+ may_overpay,
+ exact
+ ),
+ exhaustive_conversion(
+ &pile,
+ ¤t,
+ &order,
+ skip_from,
+ discount_left,
+ may_overpay,
+ exact
+ ),
+ "current={current:?}, available={pile:?}, conversions={order:?}, exact={exact}, skip={skip_from}"
+ );
+ }
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn alternative_costs_keep_their_own_payment_totals() {
+ let mut cost = PaymentOptions::new(
+ ResourcePile::food(2),
+ vec![PaymentConversion::unlimited(
+ ResourcePile::food(1),
+ ResourcePile::gold(1),
+ )],
+ vec![],
+ check_event_origin(),
+ );
+ cost.alternatives.push(ResourcePile::food(1));
+ cost.alternatives.push(ResourcePile::culture_tokens(3));
+ for payment in [
+ ResourcePile::food(2),
+ ResourcePile::food(1),
+ ResourcePile::gold(2),
+ ResourcePile::gold(1),
+ ResourcePile::culture_tokens(3),
+ ] {
+ assert!(cost.is_valid_payment(&payment), "{payment}");
+ assert_eq!(cost.first_valid_payment(&payment), Some(payment));
+ }
+ assert!(!cost.is_valid_payment(&ResourcePile::culture_tokens(2)));
+ assert!(!cost.is_valid_payment(&ResourcePile::gold(3)));
+}
diff --git a/server/src/replay.rs b/server/src/replay.rs
index 47525493..ef247681 100644
--- a/server/src/replay.rs
+++ b/server/src/replay.rs
@@ -17,6 +17,12 @@ pub struct ReplayGameData {
players: Vec,
#[serde(default)]
dropped_players: Vec,
+ #[serde(
+ default,
+ skip_serializing_if = "Vec::is_empty",
+ deserialize_with = "crate::timing::deserialize_counters"
+ )]
+ time_increments: Vec,
}
#[derive(Serialize, Deserialize, PartialEq)]
@@ -142,6 +148,9 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result {
game.players[player.id].settings = player.settings;
}
game.dropped_players = data.dropped_players;
+ // Clock totals belong to the live session, not the historical position.
+ // Reconstructing any cursor must neither earn nor revoke existing credits.
+ game.time_increments = data.time_increments;
if full_replay {
game.finish_after_drop();
}
diff --git a/server/src/tactics_card.rs b/server/src/tactics_card.rs
index 7de7d49a..dff9bb99 100644
--- a/server/src/tactics_card.rs
+++ b/server/src/tactics_card.rs
@@ -3,10 +3,10 @@ use crate::ability_initializer::{
};
use crate::action_card;
use crate::action_card::ActionCard;
-use crate::advance::AdvanceBuilder;
+use crate::advance::{Advance, AdvanceBuilder};
use crate::card::{HandCard, HandCardLocation};
use crate::combat::{Combat, CombatModifier, get_combat_strength, update_combat_strength};
-use crate::combat_listeners::{CombatRoundEnd, CombatRoundStart, CombatStrength};
+use crate::combat_listeners::{CombatEventPhase, CombatRoundEnd, CombatRoundStart, CombatStrength};
use crate::content::persistent_events::HandCardsRequest;
use crate::events::{EventOrigin, EventPlayer};
use crate::game::Game;
@@ -102,7 +102,58 @@ impl CombatRole {
}
}
-type TacticsChecker = Arc bool + Sync + Send>;
+#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum OpponentTacticsStatus {
+ Played,
+ Pending,
+ None,
+}
+
+pub(crate) fn opponent_tactics_status(
+ game: &Game,
+ player: usize,
+ round: &CombatRoundStart,
+) -> OpponentTacticsStatus {
+ let combat = &round.combat;
+ let opponent = combat.opponent(player);
+ // Only the presence of a face-down card is public. Some(0) in a
+ // filtered view counts too; never inspect its identity or the hand.
+ if get_combat_strength(opponent, round).tactics_card.is_some() {
+ return OpponentTacticsStatus::Played;
+ }
+ if !game.player(opponent).is_human() {
+ // Ordinary Barbarians/Pirates cannot play tactics. A card supplied
+ // by Viriatus's earlier Loyalty phase is handled above.
+ return OpponentTacticsStatus::None;
+ }
+ if get_combat_strength(opponent, round).deny_tactics_card
+ || !game.player(opponent).can_use_advance(Advance::Tactics)
+ || (opponent == combat.defender()
+ && combat.first_round()
+ && combat.modifiers.contains(&CombatModifier::TrojanHorse))
+ {
+ return OpponentTacticsStatus::None;
+ }
+ let pending = match round.phase {
+ // Loyalty happens before either participant's normal choice, even
+ // when the Barbarians receiving Scouts are the defender.
+ CombatEventPhase::AllowTacticsCard | CombatEventPhase::Loyalty => true,
+ // The attacker chooses first, face down. The defender may still
+ // play a card, but a defending Scout cannot target a passed attacker.
+ CombatEventPhase::Default => combat.role(player) == CombatRole::Attacker,
+ _ => false,
+ };
+ if pending {
+ OpponentTacticsStatus::Pending
+ } else {
+ OpponentTacticsStatus::None
+ }
+}
+
+// Check the live round supplied by the event listener, not game.current_event():
+// its saved snapshot can predate a choice just made by the other participant.
+type TacticsChecker = Arc bool + Sync + Send>;
#[derive(Clone)]
pub struct TacticsCard {
@@ -181,7 +232,7 @@ impl TacticsCardBuilder {
pub(crate) fn checker(
mut self,
- checker: impl Fn(usize, &Game, &Combat) -> bool + Clone + 'static + Sync + Send,
+ checker: impl Fn(usize, &Game, &CombatRoundStart) -> bool + Clone + 'static + Sync + Send,
) -> Self {
self.checker = Some(Arc::new(checker));
self
@@ -320,7 +371,7 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder {
return None;
}
- let cards = available_tactics_cards(game, p, &s.combat);
+ let cards = available_tactics_cards(game, p, s);
if cards.is_empty() {
return None;
}
@@ -349,12 +400,7 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder {
panic!("Expected ActionCard, got {:?}", s.choice[0]);
};
assert!(
- can_play_tactics_card(
- game,
- player,
- game.cache.get_action_card(card),
- &r.combat
- ),
+ can_play_tactics_card(game, player, game.cache.get_action_card(card), r),
"Tactics card requirements are not met"
);
update_combat_strength(game, player, r, move |_game, _c, s, _role| {
@@ -372,12 +418,12 @@ pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder {
)
}
-fn available_tactics_cards(game: &Game, player: usize, combat: &Combat) -> Vec {
+fn available_tactics_cards(game: &Game, player: usize, round: &CombatRoundStart) -> Vec {
game.players[player]
.action_cards
.iter()
.map(|id| game.cache.get_action_card(*id))
- .filter(|a| can_play_tactics_card(game, player, a, combat))
+ .filter(|a| can_play_tactics_card(game, player, a, round))
.map(|a| HandCard::ActionCard(a.id))
.collect()
}
@@ -386,8 +432,9 @@ pub(crate) fn can_play_tactics_card(
game: &Game,
player: usize,
card: &ActionCard,
- combat: &Combat,
+ round: &CombatRoundStart,
) -> bool {
+ let combat = &round.combat;
match &card.tactics_card {
Some(card) => {
let position_met = card
@@ -417,10 +464,7 @@ pub(crate) fn can_play_tactics_card(
CombatLocation::Land => combat.is_land_battle(game),
});
- let checker_met = card
- .checker
- .as_ref()
- .is_none_or(|c| c(player, game, combat));
+ let checker_met = card.checker.as_ref().is_none_or(|c| c(player, game, round));
position_met && fighter_met && location_met && checker_met
}
diff --git a/server/src/timing.rs b/server/src/timing.rs
new file mode 100644
index 00000000..5ba666e6
--- /dev/null
+++ b/server/src/timing.rs
@@ -0,0 +1,80 @@
+//! Platform clock credits, separate from the turn-local undo cursor and RNG.
+//!
+//! Only the live, saved-action boundary (`board_history`) calls `execute`.
+//! Rules previews, queue validation and historical replay use the lower-level
+//! executor and cannot earn credits. Automatic responses and resumed plans pass
+//! through the same boundary, attributed to their own actor, not the submitter.
+use crate::action::{Action, try_execute_action};
+use crate::game::{Game, GameContext, GameState};
+use serde::{Deserialize, Deserializer};
+
+/// The protocol requires JavaScript-safe integers, even for very long games.
+const MAX_INCREMENT: u64 = (1_u64 << 53) - 1;
+
+/// Cumulative credits in platform seat order, including dropped human players,
+/// never NPCs. Missing counters in older saves mean zero, not historical credit.
+#[must_use]
+pub fn time_increments(game: &Game) -> Vec {
+ game.players
+ .iter()
+ .filter(|player| player.is_human())
+ .map(|player| game.time_increments.get(player.index).copied().unwrap_or(0))
+ .collect()
+}
+
+pub(crate) fn deserialize_counters<'de, D>(deserializer: D) -> Result, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ let counters = Vec::::deserialize(deserializer)?;
+ if counters.iter().any(|&value| value > MAX_INCREMENT) {
+ return Err(serde::de::Error::custom(
+ "time increment is not a safe integer",
+ ));
+ }
+ Ok(counters)
+}
+
+pub(crate) fn execute(mut game: Game, action: Action, actor: usize) -> Result {
+ let eligible = game.context == GameContext::Play
+ && !matches!(
+ action,
+ Action::Undo
+ | Action::Redo
+ | Action::StartTurn
+ | Action::QueueChoice { .. }
+ | Action::QueueMoves { .. }
+ );
+ let before_player = game.active_player();
+ // Committing a simultaneous draft seat relinquishes control of that seat.
+ // Revisions must not credit again, including when loading a pre-hook save.
+ let draft_commit = game
+ .civilization_draft
+ .as_ref()
+ .map(|draft| draft.ready.get(actor).is_some_and(|ready| !ready));
+ game.timing_revealed = false;
+ let mut next = try_execute_action(game, action, actor)?;
+ let revealed = std::mem::take(&mut next.timing_revealed);
+ let boundary = draft_commit.unwrap_or_else(|| {
+ revealed || next.active_player() != before_player || next.state == GameState::Finished
+ });
+ if eligible
+ && boundary
+ && next
+ .players
+ .get(actor)
+ .is_some_and(|player| player.is_human())
+ {
+ // Human seats precede NPCs and never disappear, including after a drop.
+ let humans = next
+ .players
+ .iter()
+ .filter(|player| player.is_human())
+ .count();
+ next.time_increments.resize(humans, 0);
+ if let Some(counter) = next.time_increments.get_mut(actor) {
+ *counter = counter.saturating_add(1).min(MAX_INCREMENT);
+ }
+ }
+ Ok(next)
+}
diff --git a/server/src/undo.rs b/server/src/undo.rs
index 5ed0be53..9c842694 100644
--- a/server/src/undo.rs
+++ b/server/src/undo.rs
@@ -5,7 +5,14 @@ use crate::movement::execute_movement_action;
use json_patch::{PatchOperation, patch};
use serde_json::Value;
-const IGNORE_PATHS: [&str; 5] = ["/log/", "/log_index", "/early_choices", "/early_choice_update", "/action_plan"];
+const IGNORE_PATHS: [&str; 6] = [
+ "/log/",
+ "/log_index",
+ "/early_choices",
+ "/early_choice_update",
+ "/action_plan",
+ "/time_increments",
+];
pub(crate) fn clean_patch(mut patch: Vec) -> Vec {
patch.retain(|op| {
diff --git a/server/src/unit.rs b/server/src/unit.rs
index 1548c57c..7fb89a3e 100644
--- a/server/src/unit.rs
+++ b/server/src/unit.rs
@@ -761,7 +761,7 @@ fn save_carried_units(game: &mut Game, player: usize, pos: Position) {
return;
}
- game.information_revealed(); // strange bug when redoing this
+ game.lock_undo(); // redo workaround, not a hidden-information reveal
let mut embark = vec![];
diff --git a/server/src/web_view/combat_estimate.rs b/server/src/web_view/combat_estimate.rs
index b476cefc..816be727 100644
--- a/server/src/web_view/combat_estimate.rs
+++ b/server/src/web_view/combat_estimate.rs
@@ -79,6 +79,40 @@ pub(super) fn estimate(game: &Game, seat: usize, input: &Value) -> Result Option {
&h.origin,
EventOrigin::Advance(crate::advance::Advance::Tactics)
) || matches!(&h.origin, EventOrigin::LeaderAbility(name) if name == "Loyalty"));
+ let tactics_context = if tactics_selection
+ && let PersistentEventType::CombatRoundStart(round) = &game.current_event().event_type
+ {
+ // Loyalty supplies the hand, but the Barbarian army is the combatant.
+ let player = if matches!(&h.origin, EventOrigin::LeaderAbility(name) if name == "Loyalty") {
+ round
+ .combat
+ .players()
+ .into_iter()
+ .find(|index| game.player(*index).civilization.is_barbarian())
+ } else {
+ Some(p.index)
+ };
+ player.map(|player| (player, round))
+ } else {
+ None
+ };
let options = match &h.request {
PersistentEventRequest::ExploreResolution => return None,
PersistentEventRequest::BoolRequest(_) => return None,
PersistentEventRequest::ResourceReward(r)
if r.reward.payment_options.default.amount() == 1
- && payment_choices(&r.reward.payment_options, &ResourcePile::empty(), true, false).is_some() =>
+ && payment_choices(
+ &r.reward.payment_options,
+ &ResourcePile::empty(),
+ true,
+ false,
+ )
+ .is_some() =>
{
return None;
}
@@ -500,24 +528,12 @@ pub(super) fn describe(game: &Game, seat: usize) -> Option {
r.choices
.iter()
.filter(|card| {
- if tactics_selection
- && let PersistentEventType::CombatRoundStart(round) = &game.current_event().event_type
+ if let Some((player, round)) = tactics_context
&& let HandCard::ActionCard(id) = card
{
- // Loyalty supplies cards from the Celtic hand, but the
- // participating army and combat role belong to Barbarians.
- let combat_player = if matches!(&h.origin, EventOrigin::LeaderAbility(name) if name == "Loyalty") {
- round.combat.players().into_iter().find(|index| {
- game.player(*index).civilization.is_barbarian()
- })
- } else {
- Some(p.index)
- };
- return combat_player.is_some_and(|index| {
- crate::tactics_card::can_play_tactics_card(
- game, index, game.cache.get_action_card(*id), &round.combat,
- )
- });
+ return crate::tactics_card::can_play_tactics_card(
+ game, player, game.cache.get_action_card(*id), round,
+ );
}
true
})
@@ -626,15 +642,19 @@ pub(super) fn describe(game: &Game, seat: usize) -> Option {
_ => {}
}
}
- Some(
- json!({"origin":h.origin,"name":title,"description":description,"min":min,"max":max,"options":options,"fields":fields,
+ let mut decision = json!({"origin":h.origin,"name":title,"description":description,"min":min,"max":max,"options":options,"fields":fields,
"eventContext":event_context,
"reward":matches!(h.request,PersistentEventRequest::ResourceReward(_)),
"tacticsSelection":tactics_selection,
"advanceSelection":matches!(h.request,PersistentEventRequest::SelectAdvance(_)),
"advanceMode":matches!(h.request,PersistentEventRequest::SelectAdvance(_)).then(|| advance_mode(game, h)),
- "endOfAge":crate::status_phase::get_status_phase(game).is_some()}),
- )
+ "endOfAge":crate::status_phase::get_status_phase(game).is_some()});
+ if let Some((player, round)) = tactics_context {
+ decision["opponentTactics"] = json!(crate::tactics_card::opponent_tactics_status(
+ game, player, round,
+ ));
+ }
+ Some(decision)
}
fn government_choices(game: &Game, seat: usize) -> Vec {
diff --git a/server/tests/action_queue_tests.rs b/server/tests/action_queue_tests.rs
index 0d3eea3a..925bc53d 100644
--- a/server/tests/action_queue_tests.rs
+++ b/server/tests/action_queue_tests.rs
@@ -2,8 +2,13 @@ use server::{
action::Action,
action_queue, board_history,
cache::Cache,
+ content::persistent_events::{EventResponse, PersistentEventRequest, PersistentEventType},
+ events::EventOrigin,
game::{Game, GameContext},
game_data::GameData,
+ map::Terrain,
+ position::Position,
+ resource_pile::ResourcePile,
};
fn action(value: serde_json::Value) -> Action {
serde_json::from_value(value).unwrap()
@@ -148,10 +153,12 @@ fn event_triggering_research_is_not_queued() {
fn pending_incident(id: u8, third_player: bool) -> Game {
let mut value: serde_json::Value = serde_json::from_str(include_str!(
"test_games/incidents/great_persons/great_artist.outcome.json"
- )).unwrap();
+ ))
+ .unwrap();
value["events"][0]["event_type"]["Incident"]["incident_id"] = serde_json::json!(id);
value["events"][0]["handler"]["origin"] = serde_json::json!({"Incident": id});
- value["events"][0]["handler"]["request"]["Payment"][0]["cost"]["origin"] = serde_json::json!({"Incident": id});
+ value["events"][0]["handler"]["request"]["Payment"][0]["cost"]["origin"] =
+ serde_json::json!({"Incident": id});
if third_player {
let mut extra = value["players"][1].clone();
extra["id"] = serde_json::json!(2);
@@ -171,15 +178,31 @@ fn great_person_queue_and_wait_survive_pass_to_next_player() {
let mut game = pending_incident(19, true);
let (key, _) = action_queue::offer(&game, 0).unwrap();
assert!(action_queue::offer(&game, 2).is_none());
- action_queue::save(&mut game, 0, &key,
- vec![action(serde_json::json!({"Playing":"EndTurn"}))], true).unwrap();
- game = board_history::execute(game, action(serde_json::json!({"Response":{"Payment":[{}]}})), 1).unwrap();
+ action_queue::save(
+ &mut game,
+ 0,
+ &key,
+ vec![action(serde_json::json!({"Playing":"EndTurn"}))],
+ true,
+ )
+ .unwrap();
+ game = board_history::execute(
+ game,
+ action(serde_json::json!({"Response":{"Payment":[{}]}})),
+ 1,
+ )
+ .unwrap();
assert_eq!(game.active_player(), 2);
assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
assert!(game.action_plan.as_ref().unwrap().waiting);
assert_eq!(game.action_plan.as_ref().unwrap().actions.len(), 1);
assert_eq!(game.current_player_index, 0);
- game = board_history::execute(game.clone(), action(serde_json::json!({"Response":{"Payment":[{"culture_tokens":2}]}})), 2).unwrap();
+ game = board_history::execute(
+ game.clone(),
+ action(serde_json::json!({"Response":{"Payment":[{"culture_tokens":2}]}})),
+ 2,
+ )
+ .unwrap();
assert!(game.action_plan.is_none());
assert_eq!(game.current_player_index, 1);
assert!(game.player(2).action_cards.contains(&119));
@@ -187,10 +210,17 @@ fn great_person_queue_and_wait_survive_pass_to_next_player() {
#[test]
fn population_boom_and_migration_allow_waiting_for_settler_placement() {
- use server::content::persistent_events::{PersistentEventRequest, PersistentEventType, PositionRequest};
+ use server::content::persistent_events::{
+ PersistentEventRequest, PersistentEventType, PositionRequest,
+ };
for id in [27, 28, 34, 35] {
let mut game = pending_incident(id, false);
- let positions = game.player(1).cities.iter().map(|city| city.position).collect();
+ let positions = game
+ .player(1)
+ .cities
+ .iter()
+ .map(|city| city.position)
+ .collect();
let event = game.events.last_mut().unwrap();
if let PersistentEventType::Incident(info) = &mut event.event_type {
info.selected_player = Some(1);
@@ -199,17 +229,31 @@ fn population_boom_and_migration_allow_waiting_for_settler_placement() {
let handler = event.player.handler.as_mut().unwrap();
handler.priority = 11;
handler.request = PersistentEventRequest::SelectPositions(PositionRequest::new(
- positions, 1..=1, "Select a city to gain 1 settler"));
+ positions,
+ 1..=1,
+ "Select a city to gain 1 settler",
+ ));
let (key, label) = action_queue::offer(&game, 0).unwrap();
assert_eq!(label, "Placing a settler");
action_queue::save(&mut game, 0, &key, vec![], true).unwrap();
assert!(game.action_plan.as_ref().unwrap().waiting);
assert_eq!(game.active_player(), 1);
- action_queue::save(&mut game, 0, &key,
- vec![action(serde_json::json!({"Playing":"EndTurn"}))], false).unwrap();
+ action_queue::save(
+ &mut game,
+ 0,
+ &key,
+ vec![action(serde_json::json!({"Playing":"EndTurn"}))],
+ false,
+ )
+ .unwrap();
let count = game.player(1).units.len();
let position = game.player(1).cities[0].position.to_string();
- game = board_history::execute(game.clone(), action(serde_json::json!({"Response":{"SelectPositions":[position]}})), 1).unwrap();
+ game = board_history::execute(
+ game.clone(),
+ action(serde_json::json!({"Response":{"SelectPositions":[position]}})),
+ 1,
+ )
+ .unwrap();
assert_eq!(game.player(1).units.len(), count + 1);
assert!(game.action_plan.is_none());
assert_eq!(game.current_player_index, 1);
@@ -220,13 +264,29 @@ fn population_boom_and_migration_allow_waiting_for_settler_placement() {
fn great_diplomat_partner_choice_keeps_the_queue() {
let mut game = pending_incident(57, true);
let (key, _) = action_queue::offer(&game, 0).unwrap();
- action_queue::save(&mut game, 0, &key,
- vec![action(serde_json::json!({"Playing":"EndTurn"}))], false).unwrap();
- game = board_history::execute(game, action(serde_json::json!({"Response":{"Payment":[{"culture_tokens":2}]}})), 1).unwrap();
+ action_queue::save(
+ &mut game,
+ 0,
+ &key,
+ vec![action(serde_json::json!({"Playing":"EndTurn"}))],
+ false,
+ )
+ .unwrap();
+ game = board_history::execute(
+ game,
+ action(serde_json::json!({"Response":{"Payment":[{"culture_tokens":2}]}})),
+ 1,
+ )
+ .unwrap();
assert_eq!(game.active_player(), 1);
assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
assert_eq!(game.action_plan.as_ref().unwrap().actions.len(), 1);
- game = board_history::execute(game, action(serde_json::json!({"Response":{"SelectPlayer":0}})), 1).unwrap();
+ game = board_history::execute(
+ game,
+ action(serde_json::json!({"Response":{"SelectPlayer":0}})),
+ 1,
+ )
+ .unwrap();
assert!(game.action_plan.is_none());
assert_eq!(game.current_player_index, 1);
assert!(!game.permanent_effects.is_empty());
@@ -236,14 +296,391 @@ fn great_diplomat_partner_choice_keeps_the_queue() {
fn declining_a_great_person_during_research_opens_planning() {
let data: GameData = serde_json::from_str(include_str!(
"test_games/incidents/great_persons/great_engineer.json"
- )).unwrap();
+ ))
+ .unwrap();
let cache = Cache::new(&data.options);
let game = Game::from_data(data, cache, GameContext::Play);
- let game = board_history::execute(game, action(serde_json::json!({"Playing":{"Advance":{
- "advance":"Storage", "payment":{"food":2}
- }}})), 0).unwrap();
+ let game = board_history::execute(
+ game,
+ action(serde_json::json!({"Playing":{"Advance":{
+ "advance":"Storage", "payment":{"food":2}
+ }}})),
+ 0,
+ )
+ .unwrap();
assert!(action_queue::offer(&game, 0).is_none());
- let game = board_history::execute(game, action(serde_json::json!({"Response":{"Payment":[{}]}})), 0).unwrap();
+ let game = board_history::execute(
+ game,
+ action(serde_json::json!({"Response":{"Payment":[{}]}})),
+ 0,
+ )
+ .unwrap();
assert_eq!(game.active_player(), 1);
assert!(action_queue::offer(&game, 0).is_some());
}
+
+fn era_of_stability_game(third_player: bool) -> Game {
+ let mut value: serde_json::Value = serde_json::from_str(include_str!(
+ "test_games/incidents/trade/era_of_stability.json"
+ ))
+ .unwrap();
+ if third_player {
+ let mut extra = value["players"][1].clone();
+ extra["id"] = serde_json::json!(2);
+ extra["civilization"] = serde_json::json!("Egypt");
+ extra["cities"] = serde_json::json!([
+ {"position": "B3", "mood_state": "Happy", "city_pieces": {"temple": 2}}
+ ]);
+ extra["units"] = serde_json::json!([]);
+ value["players"][2]["id"] = serde_json::json!(3);
+ value["players"].as_array_mut().unwrap().insert(2, extra);
+ }
+ let data: GameData = serde_json::from_value(value).unwrap();
+ let cache = Cache::new(&data.options);
+ Game::from_data(data, cache, GameContext::Play)
+}
+
+fn trigger_era_of_stability(game: Game) -> Game {
+ board_history::execute(
+ game,
+ action(serde_json::json!({"Playing":{"Advance":{
+ "advance":"Storage", "payment":{"gold":2}
+ }}})),
+ 0,
+ )
+ .unwrap()
+}
+
+fn token_reward(game: Game, player: usize, reward: ResourcePile) -> Game {
+ board_history::execute(
+ game,
+ Action::Response(EventResponse::ResourceReward(reward)),
+ player,
+ )
+ .unwrap()
+}
+
+fn pending_era_of_stability(third_player: bool) -> Game {
+ // Exercise the real incident listeners, including the turn owner's reward,
+ // rather than manufacturing a ResourceReward handler for incident 47.
+ let game = trigger_era_of_stability(era_of_stability_game(third_player));
+ assert_eq!(game.active_player(), 0);
+ assert!(action_queue::offer(&game, 0).is_none());
+ let game = token_reward(game, 0, ResourcePile::culture_tokens(1));
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(game.events.len(), 1);
+ game
+}
+
+fn collect_at_a1() -> Action {
+ action(serde_json::json!({"Playing":{"Collect":{
+ "city_position":"A1",
+ "collections":[{"position":"A1","pile":{"food":1},"times":1}],
+ "action_type":"Collect"
+ }}}))
+}
+
+fn end_turn() -> Action {
+ action(serde_json::json!({"Playing":"EndTurn"}))
+}
+
+#[test]
+fn era_of_stability_off_turn_reward_only_after_exhausted_land_and_own_choice() {
+ let mut game = era_of_stability_game(false);
+ // The original fixture has only one eligible land tile (auto-resolved).
+ // Add a second so the actual exhausted-land choice must be answered.
+ game.map
+ .tiles
+ .insert(Position::from_offset("A2"), Terrain::Fertile);
+ let game = trigger_era_of_stability(game);
+ let handler = game.current_event_handler().unwrap();
+ assert!(matches!(
+ handler.request,
+ PersistentEventRequest::SelectPositions(_)
+ ));
+ assert_eq!(handler.origin, EventOrigin::Incident(47));
+ assert!(handler.priority > 0);
+ assert!(action_queue::offer(&game, 0).is_none());
+ // Even if it were another player's exhausted-land choice, it is not safe
+ // to project past a map-changing base effect.
+ let mut off_turn = game.clone();
+ off_turn.events[0].player.index = 1;
+ assert!(action_queue::offer(&off_turn, 0).is_none());
+
+ let game = board_history::execute(
+ game,
+ Action::Response(EventResponse::SelectPositions(vec![Position::from_offset(
+ "A2",
+ )])),
+ 0,
+ )
+ .unwrap();
+ assert!(matches!(
+ game.map.get(Position::from_offset("A2")),
+ Some(Terrain::Exhausted(_))
+ ));
+ assert_eq!(game.active_player(), 0);
+ assert!(matches!(
+ game.current_event_handler().unwrap().request,
+ PersistentEventRequest::ResourceReward(_)
+ ));
+ assert!(action_queue::offer(&game, 0).is_none());
+ assert!(action_queue::project(&game, 0, &[]).is_err());
+
+ let game = token_reward(game, 0, ResourcePile::culture_tokens(1));
+ let (_, label) = action_queue::offer(&game, 0).expect("another player's Era reward");
+ assert_eq!(label, "Choose resources");
+ assert_eq!(game.current_event_handler().unwrap().priority, 0);
+ assert!(action_queue::offer(&game, 1).is_none());
+ assert!(action_queue::offer(&game, 2).is_none());
+ let projected = action_queue::project(&game, 0, &[collect_at_a1()]).unwrap();
+ assert_eq!(
+ projected.player(0).resources.food,
+ game.player(0).resources.food + 1
+ );
+ assert!(projected.events.is_empty());
+ assert_eq!(
+ game.events.len(),
+ 1,
+ "the authoritative incident stays pending"
+ );
+}
+
+#[test]
+fn era_of_stability_queue_keeps_narrow_incident_and_game_guards() {
+ let game = pending_era_of_stability(false);
+ assert!(action_queue::offer(&game, 0).is_some());
+ let value = serde_json::to_value(game.cloned_data()).unwrap();
+ // Each variant retains an off-turn reward but breaks one required guard.
+ for (pointer, replacement) in [
+ (
+ "/events/0/event_type/Incident/incident_id",
+ serde_json::json!(54),
+ ),
+ (
+ "/events/0/event_type/Incident/active_player",
+ serde_json::json!(1),
+ ),
+ (
+ "/events/0/handler/origin",
+ serde_json::json!({"Incident": 54}),
+ ),
+ (
+ "/events/0/handler/origin",
+ serde_json::json!({"Advance": "Nationalism"}),
+ ),
+ ("/events/0/handler/priority", serde_json::json!(1)),
+ ("/events/0/handler/priority", serde_json::json!(10)),
+ (
+ "/events/0/event_type",
+ serde_json::json!({"CityActivationMoodDecreased":"C1"}),
+ ),
+ ("/round", serde_json::json!(4)),
+ ] {
+ let mut changed = value.clone();
+ *changed.pointer_mut(pointer).unwrap() = replacement;
+ let data: GameData = serde_json::from_value(changed).unwrap();
+ let changed = Game::from_data(data, game.cache.clone(), GameContext::Play);
+ assert!(
+ action_queue::offer(&changed, 0).is_none(),
+ "guard: {pointer}"
+ );
+ }
+ for field in ["consumed", "replaced_by_sacrifice", "selected_player"] {
+ let mut changed = value.clone();
+ changed["events"][0]["event_type"]["Incident"][field] = if field == "selected_player" {
+ serde_json::json!(1)
+ } else {
+ serde_json::json!(true)
+ };
+ let data: GameData = serde_json::from_value(changed).unwrap();
+ let changed = Game::from_data(data, game.cache.clone(), GameContext::Play);
+ assert!(action_queue::offer(&changed, 0).is_none(), "guard: {field}");
+ }
+ let mut nested = game.clone();
+ nested.events.push(nested.events[0].clone());
+ assert!(action_queue::offer(&nested, 0).is_none());
+ let mut drafting = game;
+ drafting.civilization_draft = Some(
+ serde_json::from_value(serde_json::json!({
+ "offers":[], "choices":[], "ready":[], "random_map":false
+ }))
+ .unwrap(),
+ );
+ assert!(action_queue::offer(&drafting, 0).is_none());
+}
+
+#[test]
+fn other_incident_rewards_and_mood_loss_choices_do_not_open_queue() {
+ let game = pending_era_of_stability(false);
+ // Other incidents' resource rewards are not covered by the Era exception,
+ // even at the same priority and with a matching incident origin.
+ for id in [1, 26, 45, 46, 54] {
+ let mut other = game.clone();
+ if let PersistentEventType::Incident(i) = &mut other.events[0].event_type {
+ i.incident_id = id;
+ }
+ let handler = other.events[0].player.handler.as_mut().unwrap();
+ handler.origin = EventOrigin::Incident(id);
+ if let PersistentEventRequest::ResourceReward(r) = &mut handler.request {
+ r.reward.payment_options.origin = EventOrigin::Incident(id);
+ }
+ assert!(action_queue::offer(&other, 0).is_none(), "incident {id}");
+ }
+ // Real off-turn Myths payment protects cities from Pestilence mood loss.
+ let data: GameData = serde_json::from_str(include_str!(
+ "test_games/incidents/famine/pestilence.outcome2.json"
+ ))
+ .unwrap();
+ let cache = Cache::new(&data.options);
+ let game = Game::from_data(data, cache, GameContext::Play);
+ assert_eq!(game.current_player_index, 0);
+ assert_eq!(game.active_player(), 1);
+ assert!(matches!(
+ game.current_event_handler().unwrap().request,
+ PersistentEventRequest::Payment(_)
+ ));
+ assert!(action_queue::offer(&game, 0).is_none());
+ assert!(action_queue::project(&game, 0, &[collect_at_a1()]).is_err());
+}
+
+#[test]
+fn era_of_stability_queue_and_wait_survive_all_recipients_then_replay() {
+ let mut game = pending_era_of_stability(true);
+ let (key, _) = action_queue::offer(&game, 0).unwrap();
+ let before = game.player(0).resources.clone();
+ let actions_left = game.actions_left;
+ let actions = vec![collect_at_a1(), end_turn()];
+ action_queue::save(&mut game, 0, &key, actions.clone(), true).unwrap();
+ let saved = game.action_plan.clone();
+ assert_eq!(game.player(0).resources, before);
+ assert_eq!(game.actions_left, actions_left);
+ assert!(
+ server::game_api::strip_secret(game.clone(), Some(1))
+ .action_plan
+ .is_none()
+ );
+
+ let reward_before = game.player(1).resources.culture_tokens;
+ game = token_reward(game, 1, ResourcePile::culture_tokens(1));
+ assert_eq!(game.player(1).resources.culture_tokens, reward_before + 1);
+ assert_eq!(game.active_player(), 2);
+ assert_eq!(game.current_player_index, 0);
+ assert_eq!(game.events.len(), 1);
+ assert_eq!(
+ game.action_plan, saved,
+ "handoff must not replay or reset Wait"
+ );
+ assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
+ assert_eq!(game.player(0).resources, before);
+ assert_eq!(game.actions_left, actions_left);
+ assert!(action_queue::offer(&game, 1).is_none());
+ assert!(action_queue::offer(&game, 2).is_none());
+
+ // Reload during the second recipient's choice: server replay must not
+ // depend on the planning player being connected.
+ let data = serde_json::from_str(&serde_json::to_string(&game.cloned_data()).unwrap()).unwrap();
+ game = Game::from_data(data, game.cache.clone(), GameContext::Play);
+ assert_eq!(game.action_plan, saved);
+ assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
+ let reward_before = game.player(2).resources.mood_tokens;
+ game = token_reward(game, 2, ResourcePile::mood_tokens(1));
+ assert_eq!(game.player(2).resources.mood_tokens, reward_before + 1);
+ assert_eq!(game.player(0).resources.food, before.food + 1);
+ assert_eq!(
+ game.current_player_index, 1,
+ "End turn replays only after all rewards"
+ );
+ assert!(game.events.is_empty());
+ assert!(game.action_plan.is_none());
+}
+
+#[test]
+fn era_of_stability_wait_only_survives_handoff_without_ending_turn() {
+ let mut game = pending_era_of_stability(true);
+ let (key, _) = action_queue::offer(&game, 0).unwrap();
+ let before = game.player(0).resources.clone();
+ let actions_left = game.actions_left;
+ action_queue::save(&mut game, 0, &key, vec![], true).unwrap();
+ game = token_reward(game, 1, ResourcePile::mood_tokens(1));
+ assert_eq!(action_queue::offer(&game, 0).unwrap().0, key);
+ assert!(game.action_plan.as_ref().unwrap().waiting);
+ assert!(game.action_plan.as_ref().unwrap().actions.is_empty());
+ game = token_reward(game, 2, ResourcePile::culture_tokens(1));
+ assert!(game.events.is_empty());
+ assert!(game.action_plan.is_none());
+ assert_eq!(game.current_player_index, 0);
+ assert_eq!(game.actions_left, actions_left);
+ assert_eq!(game.player(0).resources, before);
+}
+
+#[test]
+fn era_of_stability_end_turn_is_terminal_and_queued_collection_can_be_undone() {
+ let mut game = pending_era_of_stability(false);
+ let (key, _) = action_queue::offer(&game, 0).unwrap();
+ assert!(
+ action_queue::save(&mut game, 0, &key, vec![end_turn(), collect_at_a1()], false).is_err()
+ );
+ action_queue::save(&mut game, 0, &key, vec![collect_at_a1(), end_turn()], false).unwrap();
+ let before = game.player(0).resources.clone();
+ let actions_left = game.actions_left;
+ // The UI's queued Undo replaces the plan, not the authoritative history.
+ game = board_history::execute(
+ game,
+ Action::QueueMoves {
+ key: key.clone(),
+ actions: vec![collect_at_a1()],
+ waiting: false,
+ },
+ 0,
+ )
+ .unwrap();
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(game.player(0).resources, before);
+ game = token_reward(game, 1, ResourcePile::mood_tokens(1));
+ assert_eq!(game.current_player_index, 0);
+ assert_eq!(game.actions_left, actions_left - 1);
+ assert_eq!(game.player(0).resources.food, before.food + 1);
+ assert!(game.events.is_empty());
+ assert!(game.action_plan.is_none());
+ assert!(game.can_undo());
+ game = board_history::execute(game, Action::Undo, 0).unwrap();
+ assert_eq!(game.player(0).resources, before);
+ assert_eq!(game.actions_left, actions_left);
+ assert!(
+ game.events.is_empty(),
+ "undo collection must not reopen the incident"
+ );
+ assert!(
+ game.action_plan.is_none(),
+ "undo must not immediately replay collection"
+ );
+}
+
+#[test]
+fn era_of_stability_revalidates_after_last_reward_and_retains_failed_suffix() {
+ let mut game = pending_era_of_stability(true);
+ let (key, _) = action_queue::offer(&game, 0).unwrap();
+ let actions = vec![collect_at_a1(), end_turn()];
+ action_queue::save(&mut game, 0, &key, actions.clone(), false).unwrap();
+ game = token_reward(game, 1, ResourcePile::culture_tokens(1));
+ assert!(game.action_plan.as_ref().unwrap().error.is_none());
+ // Simulate an authoritative change since planning. Replay must validate
+ // the real board again rather than trust a previously valid projection.
+ game.actions_left = 0;
+ let before = game.player(0).resources.clone();
+ game = token_reward(game, 2, ResourcePile::mood_tokens(1));
+ assert!(game.events.is_empty());
+ assert_eq!(
+ game.current_player_index, 0,
+ "failed collection must not run End turn"
+ );
+ assert_eq!(game.player(0).resources, before);
+ let plan = game.action_plan.as_ref().unwrap();
+ assert_eq!(plan.key, key);
+ assert_eq!(plan.actions, actions);
+ assert!(plan.error.is_some());
+ assert!(action_queue::offer(&game, 0).is_none());
+ action_queue::save(&mut game, 0, &key, vec![], false).unwrap();
+ assert!(game.action_plan.is_none());
+}
diff --git a/server/tests/card_privacy_tests.rs b/server/tests/card_privacy_tests.rs
new file mode 100644
index 00000000..0a71e839
--- /dev/null
+++ b/server/tests/card_privacy_tests.rs
@@ -0,0 +1,523 @@
+use server::action::Action;
+use server::advance::Advance;
+use server::cache::Cache;
+use server::card::{HandCard, HandCardLocation};
+use server::city::City;
+use server::city_pieces::Building;
+use server::construct::Construct;
+use server::content::persistent_events::{
+ EventResponse, PersistentEventRequest, PersistentEventType,
+};
+use server::events::EventOrigin;
+use server::game::{Game, GameContext};
+use server::game_api;
+use server::game_data::GameData;
+use server::leader::Leader;
+use server::log::{ActionLogAction, ActionLogEntry, ActionLogItem};
+use server::map::Terrain;
+use server::movement::{MoveUnits, MovementAction};
+use server::player::Player;
+use server::playing_actions::PlayingAction;
+use server::position::Position;
+use server::resource_pile::ResourcePile;
+use server::unit::UnitType;
+use server::wonder::Wonder;
+
+fn fixture(name: &str) -> Game {
+ let path = format!(
+ "{}/tests/test_games/{name}.json",
+ env!("CARGO_MANIFEST_DIR")
+ );
+ let data: GameData = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
+ let cache = Cache::new(&data.options);
+ Game::from_data(data, cache, GameContext::Play)
+}
+
+fn add_mausoleum(game: &mut Game, player: usize) {
+ game.players[player].cities[0]
+ .pieces
+ .wonders
+ .push(Wonder::GreatMausoleum);
+ game.players[player]
+ .wonders_owned
+ .insert(Wonder::GreatMausoleum);
+}
+
+fn move_to(destination: &str) -> Action {
+ Action::Movement(MovementAction::Move(MoveUnits::new(
+ vec![0],
+ Position::from_offset(destination),
+ None,
+ ResourcePile::empty(),
+ )))
+}
+
+fn select_card(id: u8) -> Action {
+ Action::Response(EventResponse::SelectHandCards(vec![HandCard::ActionCard(
+ id,
+ )]))
+}
+
+fn actions(game: &Game) -> impl Iterator- {
+ game.log.iter().flat_map(|age| {
+ age.rounds
+ .iter()
+ .flat_map(|round| round.turns.iter().flat_map(|turn| &turn.actions))
+ })
+}
+
+fn transfers(game: &Game) -> Vec<(HandCard, HandCardLocation, HandCardLocation)> {
+ actions(game)
+ .flat_map(|action| &action.items)
+ .filter_map(|item| match &item.entry {
+ ActionLogEntry::HandCard { card, from, to } => {
+ Some((card.clone(), from.clone(), to.clone()))
+ }
+ _ => None,
+ })
+ .collect()
+}
+
+fn commitments(game: &Game) -> (Option, Option) {
+ let round = game
+ .events
+ .iter()
+ .rev()
+ .find_map(|event| match &event.event_type {
+ PersistentEventType::CombatRoundStart(round) => Some(round),
+ _ => None,
+ })
+ .expect("pending combat round");
+ (
+ round.attacker_strength.tactics_card,
+ round.defender_strength.tactics_card,
+ )
+}
+
+fn round_phase(game: &Game) -> String {
+ let round = game
+ .events
+ .iter()
+ .rev()
+ .find_map(|event| match &event.event_type {
+ PersistentEventType::CombatRoundStart(round) => Some(round),
+ _ => None,
+ })
+ .expect("pending combat round");
+ serde_json::to_value(&round.phase)
+ .unwrap()
+ .as_str()
+ .unwrap()
+ .to_string()
+}
+
+// Check the actual wire representation, not just the strength field. Card IDs
+// can also occur in hands/piles, event choices/responses/origins and log entries.
+fn assert_no_serialized_card_identity(game: &Game, card: u8) {
+ fn visit(value: &serde_json::Value, path: &str, card: u8, names: &[&str]) {
+ match value {
+ serde_json::Value::Object(fields) => {
+ for (key, value) in fields {
+ let path = format!("{path}.{key}");
+ if matches!(
+ key.as_str(),
+ "ActionCard" | "TacticsCard" | "CivilCard" | "tactics_card"
+ ) {
+ assert_ne!(value.as_u64(), Some(u64::from(card)), "{path}");
+ }
+ if matches!(
+ key.as_str(),
+ "action_cards"
+ | "action_cards_left"
+ | "action_cards_discarded"
+ | "tactics_cards"
+ | "ignored_tactics_cards"
+ ) && let Some(ids) = value.as_array()
+ {
+ assert!(
+ !ids.contains(&serde_json::json!(card)),
+ "card {card} leaked at {path}: {ids:?}"
+ );
+ }
+ visit(value, &path, card, names);
+ }
+ }
+ serde_json::Value::Array(values) => {
+ for (i, value) in values.iter().enumerate() {
+ visit(value, &format!("{path}[{i}]"), card, names);
+ }
+ }
+ serde_json::Value::String(text) => {
+ for name in names {
+ assert!(!text.contains(name), "{name} leaked at {path}: {text}");
+ }
+ }
+ _ => {}
+ }
+ }
+ let card_info = game.cache.get_action_card(card);
+ visit(
+ &serde_json::to_value(game.cloned_data()).unwrap(),
+ "$",
+ card,
+ &[
+ &card_info.civil_card.name,
+ &game.cache.get_tactics_card(card).name,
+ ],
+ );
+}
+
+fn assert_serialized_discards(game: &Game, expected: &[u8]) {
+ assert_eq!(game.action_cards_discarded, expected);
+ assert_eq!(
+ serde_json::to_value(game.cloned_data()).unwrap()["action_cards_discarded"],
+ serde_json::json!(expected)
+ );
+}
+
+fn assert_reveal(game: &Game, card: u8) {
+ let expected = format!(
+ "Reveal Tactics Card {}",
+ game.cache.get_tactics_card(card).name
+ );
+ assert!(
+ actions(game)
+ .flat_map(|action| &action.items)
+ .any(|item| { matches!(&item.entry, ActionLogEntry::Text(text) if text == &expected) })
+ );
+}
+
+#[test]
+fn attacker_commitment_is_private_until_scouts_reveals_the_cards() {
+ let mut game = fixture("tactics_cards/scout");
+ game.action_cards_discarded = vec![5, 9];
+ game.players
+ .push(Player::new(game.cache.get_civilization("Celts"), 2));
+ let game = game_api::execute(game.clone(), move_to("C1"), 0);
+ let game = game_api::execute(game, select_card(1), 0);
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(commitments(&game).0, Some(1));
+ assert_eq!(commitments(&game).1, None);
+ assert_serialized_discards(&game, &[5, 9, 1]);
+ let original = serde_json::to_value(game.cloned_data()).unwrap();
+
+ for viewer in [Some(0), Some(1), Some(2), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ // Keep the commitment's presence, not its identity, for eligibility/status UI.
+ assert_eq!(commitments(&filtered).0, Some(0));
+ assert_eq!(commitments(&filtered).1, None);
+ assert_serialized_discards(&filtered, &[5, 9, 0]);
+ if viewer != Some(0) {
+ assert_no_serialized_card_identity(&filtered, 1);
+ }
+ // Re-filtering an already private state must neither reveal anything
+ // nor mask a legitimate public discard with the same sentinel.
+ let twice = game_api::strip_secret(filtered.clone(), viewer);
+ assert_serialized_discards(&twice, &[5, 9, 0]);
+ assert_eq!(
+ transfers(&filtered),
+ vec![(
+ HandCard::ActionCard(if viewer == Some(0) { 1 } else { 0 }),
+ HandCardLocation::Hand(0),
+ HandCardLocation::PlayToDiscardFaceDown,
+ )],
+ "face-down transfer for {viewer:?}"
+ );
+ let handler = filtered.current_event().player.handler.as_ref().unwrap();
+ let PersistentEventRequest::SelectHandCards(request) = &handler.request else {
+ panic!("defender should still choose a tactics card");
+ };
+ assert_eq!(
+ request.choices,
+ if viewer == Some(1) {
+ vec![HandCard::ActionCard(23)]
+ } else {
+ vec![]
+ }
+ );
+ for action in actions(&filtered) {
+ assert!(action.undo.is_empty());
+ if let Action::Response(EventResponse::SelectHandCards(cards)) = &action.action {
+ assert!(cards.is_empty(), "raw response must not disclose a card");
+ }
+ }
+ }
+
+ assert_eq!(serde_json::to_value(game.cloned_data()).unwrap(), original);
+ let filtered = game_api::strip_secret(game.clone(), Some(1));
+ let view = server::web_view::view(&filtered, Some(1));
+ assert_eq!(view["decision"]["opponentTactics"], "played");
+ assert!(
+ view["decision"]["options"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|option| option["value"]["ActionCard"] == 23)
+ );
+ // A filtered combat preview must not try to look up the discarded sentinel
+ // as a real card. The authoritative game remains the only resolution input.
+ let estimate = server::web_view::query(
+ &filtered,
+ 1,
+ serde_json::json!({
+ "kind": "combatEstimate",
+ "action": Action::Response(EventResponse::SelectHandCards(vec![])),
+ "samples": 1,
+ }),
+ )
+ .expect("filtered combat estimate");
+ assert_eq!(estimate["samples"], 1);
+ let scouts_estimate = server::web_view::query(
+ &filtered,
+ 1,
+ serde_json::json!({
+ "kind": "combatEstimate",
+ "action": select_card(23),
+ "samples": 1,
+ }),
+ );
+ assert_eq!(
+ scouts_estimate.unwrap_err(),
+ "Estimate unavailable for Scout"
+ );
+
+ let revealed = game_api::execute(game, select_card(23), 1);
+ for viewer in [Some(0), Some(1), Some(2), None] {
+ let filtered = game_api::strip_secret(revealed.clone(), viewer);
+ assert_serialized_discards(&filtered, &[5, 9, 1, 23]);
+ assert_reveal(&filtered, 1);
+ assert_reveal(&filtered, 23);
+ }
+}
+
+#[test]
+fn loyalty_defender_commitment_is_private_before_attacker_chooses() {
+ // Mirror the live Viriatus/Tactical Retreat fixture, but leave the human
+ // attacker's card pending so Loyalty cannot immediately reveal its card.
+ let mut game = fixture("civilizations/china/fast_war");
+ game.action_cards_discarded = vec![5, 9];
+ game.current_player_index = 1;
+ game.players[0].civilization = game.cache.get_civilization("Celts");
+ game.players[0].action_cards = vec![17];
+ game.players[0].units[0].unit_type = UnitType::Leader(Leader::Viriatus);
+ game.players[0].units[0].position = Position::from_offset("E7");
+ game.players[0].units[0].id = 42;
+ game.players[0].next_unit_id = 43;
+ for terrain in game.map.tiles.values_mut() {
+ *terrain = Terrain::Fertile;
+ }
+ game.players[1].cities = vec![City::new(1, Position::from_offset("D1"))];
+ game.players[1].units[0].position = Position::from_offset("E8");
+ game.players[1].advances.insert(Advance::Tactics);
+ game.players[1].action_cards = vec![1];
+ let mut barbarians = Player::new(game.cache.get_civilization("Barbarians"), 2);
+ let mut unit = game.players[1].units[0].clone();
+ unit.player_index = 2;
+ unit.position = Position::from_offset("D8");
+ barbarians.units = vec![unit];
+ barbarians.next_unit_id = 1;
+ game.players.push(barbarians);
+ game.players
+ .push(Player::new(game.cache.get_civilization("Greece"), 3));
+
+ let game = game_api::execute(game.clone(), move_to("D8"), 1);
+ assert_eq!(game.active_player(), 0);
+ let game = game_api::execute(game, select_card(17), 0);
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(round_phase(&game), "Default");
+ assert_eq!(commitments(&game).0, None);
+ assert_eq!(commitments(&game).1, Some(17));
+ assert_serialized_discards(&game, &[5, 9, 17]);
+ let original = serde_json::to_value(game.cloned_data()).unwrap();
+
+ for viewer in [Some(0), Some(1), Some(2), Some(3), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ assert_eq!(commitments(&filtered).0, None);
+ assert_eq!(commitments(&filtered).1, Some(0));
+ assert_serialized_discards(&filtered, &[5, 9, 0]);
+ if viewer != Some(0) {
+ // Includes the Barbarian combatant: only its Celtic controller owns
+ // the committed hand card and may see its face-down transfer.
+ assert_no_serialized_card_identity(&filtered, 17);
+ }
+ assert_eq!(
+ transfers(&filtered),
+ vec![(
+ HandCard::ActionCard(if viewer == Some(0) { 17 } else { 0 }),
+ HandCardLocation::Hand(0),
+ HandCardLocation::PlayToDiscardFaceDown,
+ )],
+ "the Celtic hand owner, not the Barbarian participant, knows the card"
+ );
+ }
+
+ // Match Great Mausoleum's front insertion when the *controller* owns it;
+ // the Barbarian combatant does not. An older public occurrence stays public.
+ let mut mausoleum = game.clone();
+ add_mausoleum(&mut mausoleum, 0);
+ mausoleum.action_cards_discarded = vec![17, 5, 9, 17];
+ for viewer in [Some(0), Some(1), Some(2), Some(3), None] {
+ let filtered = game_api::strip_secret(mausoleum.clone(), viewer);
+ assert_serialized_discards(&filtered, &[0, 5, 9, 17]);
+ }
+
+ assert_eq!(serde_json::to_value(game.cloned_data()).unwrap(), original);
+ let revealed = game_api::execute(game, select_card(1), 1);
+ assert_eq!(
+ revealed.active_player(),
+ 0,
+ "Loyalty controller chooses retreat"
+ );
+ assert_eq!(round_phase(&revealed), "TacticsCard");
+ for viewer in [Some(0), Some(1), Some(2), Some(3), None] {
+ let filtered = game_api::strip_secret(revealed.clone(), viewer);
+ assert_eq!(commitments(&filtered).0, Some(1));
+ assert_eq!(commitments(&filtered).1, Some(17));
+ assert_serialized_discards(&filtered, &[5, 9, 17, 1]);
+ assert_reveal(&filtered, 1);
+ assert_reveal(&filtered, 17);
+ }
+}
+
+#[test]
+fn masking_preserves_public_discard_duplicates_and_mausoleum_insertion_order() {
+ for mausoleum in [false, true] {
+ let mut game = fixture("tactics_cards/scout");
+ // Reused cards can leave earlier public occurrences in the discard list.
+ game.action_cards_discarded = vec![1, 5, 9];
+ if mausoleum {
+ add_mausoleum(&mut game, 0);
+ }
+ let game = game_api::execute(game, move_to("C1"), 0);
+ let game = game_api::execute(game, select_card(1), 0);
+ let expected = if mausoleum {
+ vec![0, 1, 5, 9]
+ } else {
+ vec![1, 5, 9, 0]
+ };
+ for viewer in [Some(0), Some(1), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ assert_serialized_discards(&filtered, &expected);
+ assert_eq!(commitments(&filtered).0, Some(0));
+ // Re-filtering must not hide the earlier public occurrence as well.
+ let filtered = game_api::strip_secret(filtered, viewer);
+ assert_serialized_discards(&filtered, &expected);
+ }
+ }
+}
+
+#[test]
+fn ordinary_observatory_draw_is_visible_only_to_the_owner() {
+ let mut game = fixture("base/construct");
+ game.action_cards_left = vec![17];
+ let game = game_api::execute(
+ game,
+ Action::Playing(PlayingAction::Construct(Construct::new(
+ Position::from_offset("C2"),
+ Building::Observatory,
+ ResourcePile::new(1, 1, 1, 0, 0, 0, 0),
+ ))),
+ 0,
+ );
+ assert!(transfers(&game).contains(&(
+ HandCard::ActionCard(17),
+ HandCardLocation::DrawPile,
+ HandCardLocation::Hand(0),
+ )));
+ for viewer in [Some(0), Some(1), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ let draws: Vec<_> = transfers(&filtered)
+ .into_iter()
+ .filter(|(_, from, _)| from == &HandCardLocation::DrawPile)
+ .collect();
+ assert_eq!(
+ draws,
+ vec![(
+ HandCard::ActionCard(if viewer == Some(0) { 17 } else { 0 }),
+ HandCardLocation::DrawPile,
+ HandCardLocation::Hand(0),
+ )]
+ );
+ }
+}
+
+fn game_with_transfer(card: HandCard, from: HandCardLocation, to: HandCardLocation) -> Game {
+ let mut game = fixture("tactics_cards/scout");
+ game.players
+ .push(Player::new(game.cache.get_civilization("Celts"), 2));
+ let mut action = ActionLogAction::new(Action::StartTurn, 0, None, 0);
+ action.items.push(ActionLogItem::new(
+ 0,
+ ActionLogEntry::hand_card(card, from, to),
+ EventOrigin::Advance(Advance::Tactics),
+ vec![],
+ ));
+ game.log[0].rounds[0].turns[0].actions.push(action);
+ game.log_index = 1;
+ game
+}
+
+#[test]
+fn hidden_draws_and_transfers_require_an_actual_hand_owner() {
+ use HandCardLocation::{DrawPile, DrawPilePeeked, GreatSeer, Hand, PlayToDiscardFaceDown};
+ for (card, hidden) in [
+ (HandCard::ActionCard(17), HandCard::ActionCard(0)),
+ (HandCard::ObjectiveCard(1), HandCard::ObjectiveCard(0)),
+ (
+ HandCard::Wonder(Wonder::Pyramids),
+ HandCard::Wonder(Wonder::Hidden),
+ ),
+ ] {
+ for (from, to, owners) in [
+ (DrawPile, Hand(0), vec![0]),
+ (Hand(0), Hand(1), vec![0, 1]),
+ (Hand(0), DrawPile, vec![0]),
+ (Hand(0), PlayToDiscardFaceDown, vec![0]),
+ (DrawPile, GreatSeer(0), vec![]),
+ (DrawPilePeeked(0), DrawPile, vec![]),
+ ] {
+ let game = game_with_transfer(card.clone(), from.clone(), to.clone());
+ for viewer in [Some(0), Some(1), Some(2), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ let expected = if viewer.is_some_and(|p| owners.contains(&p)) {
+ &card
+ } else {
+ &hidden
+ };
+ assert_eq!(
+ transfers(&filtered),
+ vec![(expected.clone(), from.clone(), to.clone())],
+ "{card:?}: {from:?} -> {to:?} for {viewer:?}"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn public_card_transfers_keep_their_identity_for_every_viewer() {
+ use HandCardLocation::{DiscardPile, Hand, PlayToDiscard, Public, RevealedHand};
+ for card in [
+ HandCard::ActionCard(17),
+ HandCard::ObjectiveCard(1),
+ HandCard::Wonder(Wonder::Pyramids),
+ ] {
+ for (from, to) in [
+ (Hand(0), DiscardPile),
+ (DiscardPile, Hand(0)),
+ (Hand(0), PlayToDiscard),
+ (Public, Hand(0)),
+ (RevealedHand(0), Hand(1)),
+ ] {
+ let game = game_with_transfer(card.clone(), from.clone(), to.clone());
+ for viewer in [Some(0), Some(1), Some(2), None] {
+ let filtered = game_api::strip_secret(game.clone(), viewer);
+ assert_eq!(
+ transfers(&filtered),
+ vec![(card.clone(), from.clone(), to.clone())],
+ "{card:?}: {from:?} -> {to:?} for {viewer:?}"
+ );
+ }
+ }
+ }
+}
diff --git a/server/tests/scouts_tests.rs b/server/tests/scouts_tests.rs
new file mode 100644
index 00000000..d57bcc13
--- /dev/null
+++ b/server/tests/scouts_tests.rs
@@ -0,0 +1,455 @@
+use common::{JsonTest, move_action};
+use server::action::Action;
+use server::advance::Advance;
+use server::card::HandCard;
+use server::content::persistent_events::{
+ EventResponse, PersistentEventRequest, PersistentEventType,
+};
+use server::game::Game;
+use server::game_api;
+use server::leader::Leader;
+use server::map::Terrain;
+use server::player::Player;
+use server::position::Position;
+use server::unit::{Unit, UnitType};
+use std::panic::{AssertUnwindSafe, catch_unwind};
+
+mod common;
+
+const SCOUTS: u8 = 23;
+const PELTASTS: u8 = 1;
+const HIGH_MORALE: u8 = 6;
+
+fn setup(attacker_cards: &[u8], defender_cards: &[u8]) -> Game {
+ let mut game = JsonTest::new("tactics_cards").load_game("scout");
+ game.players[0].action_cards = attacker_cards.to_vec();
+ game.players[1].action_cards = defender_cards.to_vec();
+ game
+}
+
+fn attack(game: Game) -> Game {
+ game_api::execute(game, move_action(vec![0], Position::from_offset("C1")), 0)
+}
+
+fn choose(game: Game, player: usize, card: Option) -> Game {
+ game_api::execute(
+ game,
+ Action::Response(EventResponse::SelectHandCards(
+ card.into_iter().map(HandCard::ActionCard).collect(),
+ )),
+ player,
+ )
+}
+
+macro_rules! round {
+ ($game:expr) => {
+ match &$game.current_event().event_type {
+ PersistentEventType::CombatRoundStart(round) => round,
+ _ => panic!("Expected combat round start"),
+ }
+ };
+}
+
+fn assert_status(game: &Game, player: usize, expected: &str) {
+ assert_eq!(
+ server::web_view::view(game, Some(player))["decision"]["opponentTactics"],
+ expected
+ );
+ let filtered = game_api::strip_secret(game.clone(), Some(player));
+ assert_eq!(
+ server::web_view::view(&filtered, Some(player))["decision"]["opponentTactics"],
+ expected
+ );
+}
+
+fn request_cards(game: &Game) -> Vec {
+ let PersistentEventRequest::SelectHandCards(request) =
+ &game.current_event_handler().unwrap().request
+ else {
+ panic!("Expected tactics selection");
+ };
+ request.choices.clone()
+}
+
+fn view_cards(game: &Game, player: usize) -> Vec {
+ server::web_view::view(game, Some(player))["decision"]["options"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|option| option["value"]["ActionCard"].as_u64().unwrap() as u8)
+ .collect()
+}
+
+fn restore(game: &Game) -> Game {
+ let json = serde_json::to_string(&game.cloned_data()).unwrap();
+ Game::from_data(
+ serde_json::from_str(&json).unwrap(),
+ game.cache.clone(),
+ game.context.clone(),
+ )
+}
+
+fn add_stale_scouts_choice(game: &mut Game) {
+ let PersistentEventRequest::SelectHandCards(request) =
+ &mut game.current_event_handler_mut().unwrap().request
+ else {
+ panic!("Expected tactics selection");
+ };
+ if !request.choices.contains(&HandCard::ActionCard(SCOUTS)) {
+ request.choices.push(HandCard::ActionCard(SCOUTS));
+ }
+}
+
+fn assert_stale_scouts_rejected(mut game: Game, player: usize) {
+ add_stale_scouts_choice(&mut game);
+ let game = restore(&game);
+ assert!(request_cards(&game).contains(&HandCard::ActionCard(SCOUTS)));
+ assert_eq!(view_cards(&game, player), vec![HIGH_MORALE]);
+ assert_eq!(
+ view_cards(&game_api::strip_secret(game.clone(), Some(player)), player),
+ vec![HIGH_MORALE]
+ );
+ let Err(panic) = catch_unwind(AssertUnwindSafe(|| choose(game, player, Some(SCOUTS)))) else {
+ panic!("A stale Scouts choice must fail authoritative validation");
+ };
+ let message = panic
+ .downcast_ref::()
+ .map(String::as_str)
+ .or_else(|| panic.downcast_ref::<&str>().copied());
+ assert_eq!(message, Some("Tactics card requirements are not met"));
+}
+
+fn npc_setup(civilization: &str, attacker_cards: &[u8]) -> Game {
+ let mut game = setup(attacker_cards, &[]);
+ // Human seats stay contiguous; neutral factions follow them.
+ game.players[1].units.clear();
+ game.players[1].cities = vec![server::city::City::new(1, Position::from_offset("B1"))];
+ let mut npc = Player::new(game.cache.get_civilization(civilization), 2);
+ npc.units.push(Unit::new(
+ 2,
+ Position::from_offset("C1"),
+ UnitType::Infantry,
+ 0,
+ ));
+ npc.next_unit_id = 1;
+ npc.cities
+ .push(server::city::City::new(2, Position::from_offset("C1")));
+ game.players.push(npc);
+ game
+}
+
+#[test]
+fn scouts_not_offered_against_ordinary_barbarians_or_pirates_and_stale_choices_rejected() {
+ for civilization in ["Barbarians", "Pirates"] {
+ let mut game = npc_setup(civilization, &[SCOUTS, HIGH_MORALE]);
+ if civilization == "Pirates" {
+ // Exercise a real sea battle rather than merely relabeling a land army.
+ let from = Position::from_offset("C2");
+ let to = Position::from_offset("C1");
+ game.map.tiles.insert(from, Terrain::Water);
+ game.map.tiles.insert(to, Terrain::Water);
+ game.players[0].units.truncate(1);
+ for player in &mut game.players {
+ player
+ .cities
+ .retain(|city| city.position != from && city.position != to);
+ for unit in &mut player.units {
+ unit.unit_type = UnitType::Ship;
+ }
+ }
+ }
+ let game = attack(game.clone()); // rebuild the changed civilization's listeners
+ assert_eq!(game.current_event().player.index, 0);
+ assert_eq!(
+ request_cards(&game),
+ vec![HandCard::ActionCard(HIGH_MORALE)]
+ );
+ assert_eq!(view_cards(&game, 0), vec![HIGH_MORALE]);
+ assert_status(&game, 0, "none");
+ assert_stale_scouts_rejected(game, 0);
+ }
+}
+
+#[test]
+fn defending_scouts_not_offered_after_attacker_passes_or_has_no_tactics() {
+ for attacker_cards in [vec![PELTASTS], vec![]] {
+ let mut game = attack(setup(&attacker_cards, &[SCOUTS, HIGH_MORALE]));
+ if !attacker_cards.is_empty() {
+ game = choose(game, 0, None);
+ }
+ assert_eq!(game.current_event().player.index, 1);
+ assert_eq!(round!(&game).attacker_strength.tactics_card, None);
+ assert_eq!(
+ request_cards(&game),
+ vec![HandCard::ActionCard(HIGH_MORALE)]
+ );
+ assert_eq!(view_cards(&game, 1), vec![HIGH_MORALE]);
+ assert_status(&game, 1, "none");
+ assert_stale_scouts_rejected(game, 1);
+ }
+}
+
+#[test]
+fn attacking_scouts_remain_available_without_examining_the_defenders_hidden_hand() {
+ for defender_cards in [vec![], vec![PELTASTS], vec![7]] {
+ let game = attack(setup(&[SCOUTS, HIGH_MORALE], &defender_cards));
+ assert_eq!(round!(&game).defender_strength.tactics_card, None);
+ assert_eq!(
+ request_cards(&game),
+ vec![
+ HandCard::ActionCard(HIGH_MORALE),
+ HandCard::ActionCard(SCOUTS)
+ ]
+ );
+ assert_eq!(view_cards(&game, 0), vec![HIGH_MORALE, SCOUTS]);
+ assert_status(&game, 0, "pending");
+ assert_eq!(
+ view_cards(&game_api::strip_secret(game.clone(), Some(0)), 0),
+ vec![HIGH_MORALE, SCOUTS]
+ );
+ }
+}
+
+#[test]
+fn defending_scouts_see_a_just_played_card_and_steal_it_after_reveal() {
+ let game = choose(attack(setup(&[PELTASTS], &[SCOUTS])), 0, Some(PELTASTS));
+ // This request is built in the same event invocation as the attacker's
+ // response. Eligibility must use the live round, not its stale saved copy.
+ assert_eq!(request_cards(&game), vec![HandCard::ActionCard(SCOUTS)]);
+ assert_eq!(round!(&game).attacker_strength.tactics_card, Some(PELTASTS));
+ assert_status(&game, 1, "played");
+ let mut filtered = game_api::strip_secret(game.clone(), Some(1));
+ let PersistentEventType::CombatRoundStart(round) =
+ &mut filtered.events.last_mut().unwrap().event_type
+ else {
+ unreachable!();
+ };
+ // Explicitly exercise the hidden-card sentinel as well as authoritative data.
+ round.attacker_strength.tactics_card = Some(0);
+ assert_eq!(view_cards(&filtered, 1), vec![SCOUTS]);
+ let game = choose(restore(&game), 1, Some(SCOUTS));
+ assert!(game.player(1).action_cards.contains(&PELTASTS));
+ assert!(!game.player(1).action_cards.contains(&SCOUTS));
+ let log = serde_json::to_string(&game.log).unwrap();
+ assert!(log.contains("Ignore the enemy tactics"));
+ assert!(!log.contains("Peltasts rolls"));
+}
+
+#[test]
+fn attacking_scouts_can_steal_a_later_defender_card_or_risk_a_pass() {
+ for defender_card in [Some(PELTASTS), None] {
+ let game = choose(attack(setup(&[SCOUTS], &[PELTASTS])), 0, Some(SCOUTS));
+ assert_eq!(game.current_event().player.index, 1);
+ let game = choose(game, 1, defender_card);
+ assert_eq!(
+ game.player(0).action_cards.contains(&PELTASTS),
+ defender_card.is_some()
+ );
+ assert!(!game.player(0).action_cards.contains(&SCOUTS));
+ let log = serde_json::to_string(&game.log).unwrap();
+ assert_eq!(
+ log.contains("Cannot use - opponent didn't play a tactics card"),
+ defender_card.is_none()
+ );
+ }
+}
+
+fn loyalty_setup(attacker_cards: &[u8], loyalty_cards: &[u8]) -> Game {
+ let mut game = npc_setup("Barbarians", attacker_cards);
+ let mut celts = Player::new(game.cache.get_civilization("Celts"), 1);
+ celts.advances.insert(Advance::Tactics);
+ celts.action_cards = loyalty_cards.to_vec();
+ celts.cities = std::mem::take(&mut game.players[1].cities);
+ celts.units.push(Unit::new(
+ 1,
+ Position::from_offset("B2"),
+ UnitType::Leader(Leader::Viriatus),
+ 0,
+ ));
+ celts.next_unit_id = 1;
+ game.players[1] = celts;
+ game.clone() // register Viriatus's listeners
+}
+
+#[test]
+fn scouts_can_steal_a_barbarian_card_supplied_by_viriatus_but_not_after_loyalty_passes() {
+ for loyalty_card in [Some(PELTASTS), None] {
+ let game = attack(loyalty_setup(&[SCOUTS, HIGH_MORALE], &[PELTASTS]));
+ assert_eq!(
+ serde_json::to_value(&round!(&game).phase).unwrap(),
+ "Loyalty"
+ );
+ assert_eq!(game.current_event().player.index, 1);
+ assert_status(&game, 1, "pending");
+ let game = choose(game, 1, loyalty_card);
+ assert_eq!(
+ serde_json::to_value(&round!(&game).phase).unwrap(),
+ "Default"
+ );
+ assert_eq!(game.current_event().player.index, 0);
+ assert_status(
+ &game,
+ 0,
+ if loyalty_card.is_some() {
+ "played"
+ } else {
+ "none"
+ },
+ );
+ if loyalty_card.is_some() {
+ assert!(request_cards(&game).contains(&HandCard::ActionCard(SCOUTS)));
+ assert_eq!(view_cards(&game, 0), vec![HIGH_MORALE, SCOUTS]);
+ assert_eq!(
+ view_cards(&game_api::strip_secret(game.clone(), Some(0)), 0),
+ vec![HIGH_MORALE, SCOUTS]
+ );
+ let game = choose(restore(&game), 0, Some(SCOUTS));
+ assert!(game.player(0).action_cards.contains(&PELTASTS));
+ assert!(!game.player(1).action_cards.contains(&PELTASTS));
+ assert!(
+ serde_json::to_string(&game.log)
+ .unwrap()
+ .contains("Ignore the enemy tactics")
+ );
+ } else {
+ assert_eq!(
+ request_cards(&game),
+ vec![HandCard::ActionCard(HIGH_MORALE)]
+ );
+ assert_stale_scouts_rejected(game, 0);
+ }
+ }
+}
+
+#[test]
+fn loyalty_can_supply_defending_scouts_before_the_human_attacker_chooses() {
+ let game = attack(loyalty_setup(&[PELTASTS], &[SCOUTS]));
+ assert_eq!(
+ serde_json::to_value(&round!(&game).phase).unwrap(),
+ "Loyalty"
+ );
+ assert_eq!(round!(&game).attacker_strength.tactics_card, None);
+ assert_eq!(request_cards(&game), vec![HandCard::ActionCard(SCOUTS)]);
+ assert_eq!(view_cards(&game, 1), vec![SCOUTS]);
+ assert_status(&game, 1, "pending");
+ let game = choose(game, 1, Some(SCOUTS));
+ assert_eq!(round!(&game).defender_strength.tactics_card, Some(SCOUTS));
+ let game = choose(game, 0, Some(PELTASTS));
+ assert!(
+ serde_json::to_string(&game.log)
+ .unwrap()
+ .contains("Ignore the enemy tactics")
+ );
+}
+
+#[test]
+fn scouts_checker_uses_only_card_presence_and_public_choice_order_for_both_roles() {
+ let base = attack(setup(&[SCOUTS], &[HIGH_MORALE]));
+ for player in [0, 1] {
+ let opponent = 1 - player;
+ for civilization in ["Rome", "Barbarians", "Pirates"] {
+ for phase in ["Loyalty", "Default"] {
+ for card in [None, Some(0), Some(PELTASTS)] {
+ let mut game = base.clone();
+ game.players[opponent].civilization = game.cache.get_civilization(civilization);
+ let mut round = round!(&game).clone();
+ round.phase = serde_json::from_value(serde_json::json!(phase)).unwrap();
+ let strength = if opponent == 0 {
+ &mut round.attacker_strength
+ } else {
+ &mut round.defender_strength
+ };
+ strength.tactics_card = card;
+ let expected = card.is_some()
+ || (civilization == "Rome" && (phase == "Loyalty" || player == 0));
+ let checker = game
+ .cache
+ .get_tactics_card(SCOUTS)
+ .checker
+ .as_ref()
+ .unwrap();
+ assert_eq!(
+ checker(player, &game, &round),
+ expected,
+ "player={player}, opponent={civilization}, phase={phase:?}, card={card:?}"
+ );
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn scouts_respect_public_tactics_capability_including_a_borrowed_advance() {
+ for borrowed in [false, true] {
+ let mut game = setup(&[SCOUTS, HIGH_MORALE], &[]);
+ game.players[1].advances.remove(Advance::Tactics);
+ if borrowed {
+ game.players[1].great_library_advance = Some(Advance::Tactics);
+ }
+ let game = attack(game.clone());
+ assert_eq!(
+ request_cards(&game).contains(&HandCard::ActionCard(SCOUTS)),
+ borrowed
+ );
+ assert_status(&game, 0, if borrowed { "pending" } else { "none" });
+ if !borrowed {
+ assert_stale_scouts_rejected(game, 0);
+ }
+ }
+}
+
+#[test]
+fn scouts_not_offered_when_sparta_publicly_denies_the_defenders_tactics() {
+ let mut game = setup(&[SCOUTS, HIGH_MORALE], &[PELTASTS]);
+ game.players[0].civilization = game.cache.get_civilization("Greece");
+ game.players[0].advances.insert(Advance::Draft);
+ game.players[1].civilization = game.cache.get_civilization("Rome");
+ let game = attack(game.clone());
+ assert!(round!(&game).defender_strength.deny_tactics_card);
+ assert_eq!(
+ request_cards(&game),
+ vec![HandCard::ActionCard(HIGH_MORALE)]
+ );
+ assert_status(&game, 0, "none");
+ assert_stale_scouts_rejected(game, 0);
+}
+
+#[test]
+fn scouts_status_respects_trojan_horse_and_already_committed_cards() {
+ let mut game = attack(setup(&[SCOUTS, HIGH_MORALE], &[]));
+ let PersistentEventType::CombatRoundStart(round) =
+ &mut game.events.last_mut().unwrap().event_type
+ else {
+ unreachable!();
+ };
+ round
+ .combat
+ .modifiers
+ .push(server::combat::CombatModifier::TrojanHorse);
+ assert_status(&game, 0, "none");
+ assert_eq!(view_cards(&game, 0), vec![HIGH_MORALE]);
+ let PersistentEventType::CombatRoundStart(round) =
+ &mut game.events.last_mut().unwrap().event_type
+ else {
+ unreachable!();
+ };
+ // Presence takes precedence over public inability to make a new choice.
+ round.defender_strength.tactics_card = Some(0);
+ round.defender_strength.deny_tactics_card = true;
+ game.players[1].advances.remove(Advance::Tactics);
+ assert_status(&game, 0, "played");
+ assert_eq!(view_cards(&game, 0), vec![HIGH_MORALE, SCOUTS]);
+}
+
+#[test]
+fn loyalty_revalidates_scouts_from_a_stale_prompt() {
+ let mut game = attack(loyalty_setup(&[PELTASTS], &[SCOUTS, HIGH_MORALE]));
+ assert_status(&game, 1, "pending");
+ assert!(request_cards(&game).contains(&HandCard::ActionCard(SCOUTS)));
+ // Model an older pending request containing a now-ineligible card. The
+ // supplying Celtic seat must be checked as the defending Barbarian army.
+ game.players[0].advances.remove(Advance::Tactics);
+ assert_status(&game, 1, "none");
+ assert_stale_scouts_rejected(game, 1);
+}
diff --git a/server/tests/timing_tests.rs b/server/tests/timing_tests.rs
new file mode 100644
index 00000000..a3276819
--- /dev/null
+++ b/server/tests/timing_tests.rs
@@ -0,0 +1,358 @@
+//! Exercise the authoritative executor used by both BGS move and tryMove.
+use serde_json::{Value, json};
+use server::{
+ action::Action,
+ action_queue, board_history,
+ cache::Cache,
+ game::{CivSetupOption, Game, GameContext, GameOptions},
+ game_data::GameData,
+ game_setup::{GameSetupBuilder, setup_game},
+ timing::time_increments,
+};
+
+fn load(raw: &str) -> Game {
+ let data: GameData = serde_json::from_str(raw).unwrap();
+ let cache = Cache::new(&data.options);
+ Game::from_data(data, cache, GameContext::Play)
+}
+
+fn saved(game: &Game) -> Value {
+ serde_json::to_value(game.cloned_data()).unwrap()
+}
+
+fn play(game: Game, actor: usize, action: Value) -> Game {
+ board_history::execute(game, serde_json::from_value(action).unwrap(), actor).unwrap()
+}
+
+fn collect() -> Value {
+ json!({"Playing":{"Collect":{"city_position":"C2","collections":[{"position":"B1","pile":{"ore":1},"times":1}],"action_type":"Collect"}}})
+}
+
+#[test]
+fn deterministic_actions_undo_redo_and_reload_never_farm_credits() {
+ let mut value: Value = serde_json::from_str(include_str!(
+ "test_games/advances/collect_free_economy.json"
+ ))
+ .unwrap();
+ // Nonzero totals from an earlier reveal must survive all navigation.
+ value["time_increments"] = json!([11, 5]);
+ let mut game = load(&value.to_string());
+ for _ in 0..12 {
+ game = play(game, 0, collect());
+ assert_eq!(time_increments(&game), [11, 5]);
+ game = load(&saved(&game).to_string());
+ game = play(game, 0, json!("Undo"));
+ assert_eq!(time_increments(&game), [11, 5]);
+ game = play(game, 0, json!("Redo"));
+ assert_eq!(time_increments(&game), [11, 5]);
+ game = play(game, 0, json!("Undo"));
+ assert_eq!(time_increments(&game), [11, 5]);
+ }
+ assert!(board_history::execute(game.clone(), Action::Undo, 0).is_err());
+ assert_eq!(time_increments(&game), [11, 5]);
+ game = play(game, 0, json!({"Playing":"EndTurn"}));
+ assert_eq!(time_increments(&game), [12, 5]);
+ assert!(
+ !game.can_undo(),
+ "a credited boundary must not be replay-farmable"
+ );
+}
+
+#[test]
+fn old_saves_and_migrations_begin_at_zero_without_changing_npc_or_dropped_seats() {
+ let mut value: Value =
+ serde_json::from_str(include_str!("fixtures/legacy_0_4_16/setup.json")).unwrap();
+ value["options"]["undo"] = json!("SamePlayer");
+ let mut game = load(&value.to_string());
+ assert_eq!(time_increments(&game), [0, 0]);
+ assert!(game.players.len() > time_increments(&game).len());
+ game.dropped_players.push(1);
+ assert_eq!(time_increments(&game), [0, 0]);
+ assert_eq!(time_increments(&game.clone()), [0, 0]);
+}
+
+#[test]
+fn spy_reveals_without_rng_changes_but_payment_declaration_and_decline_do_not() {
+ let game = load(include_str!("test_games/action_cards/spy.json"));
+ let rng = saved(&game)["rng"].clone();
+ let game = play(game, 0, json!({"Playing":{"ActionCard":7}}));
+ assert_eq!(time_increments(&game), [0, 0]);
+ let game = play(
+ game,
+ 0,
+ json!({"Response":{"Payment":[{"culture_tokens":1}]}}),
+ );
+ assert_eq!(saved(&game)["rng"], rng);
+ assert_eq!(time_increments(&game), [1, 0]);
+ assert!(!game.can_undo());
+ let declined = play(game.clone(), 0, json!({"Response":{"SelectHandCards":[]}}));
+ assert_eq!(time_increments(&declined), [1, 0]);
+ let swapped = play(
+ game,
+ 0,
+ json!({"Response":{"SelectHandCards":[{"ActionCard":1},{"ActionCard":2}]}}),
+ );
+ assert_eq!(time_increments(&swapped), [2, 0]);
+ assert_eq!(saved(&swapped)["rng"], rng);
+}
+
+#[test]
+fn exploration_earns_once_but_deterministic_orientation_does_not() {
+ let game = load(include_str!("test_games/movement/explore_resolution.json"));
+ let game = play(
+ game,
+ 1,
+ json!({"Movement":{"Move":{"units":[0],"destination":"D6"}}}),
+ );
+ assert_eq!(time_increments(&game), [0, 1]);
+ assert!(!game.can_undo());
+ let game = play(game, 1, json!({"Response":{"ExploreResolution":3}}));
+ assert_eq!(time_increments(&game), [0, 1]);
+ let game = play(game, 1, json!("Undo"));
+ assert_eq!(time_increments(&game), [0, 1]);
+}
+
+#[test]
+fn a_card_draw_earns_once_even_when_the_pre_shuffled_rng_does_not_change() {
+ let game = load(include_str!("test_games/base/same_player_undo.json"));
+ let rng = saved(&game)["rng"].clone();
+ let game = play(
+ game,
+ 0,
+ json!({"Playing":{"Construct":{
+ "city_position":"C2", "city_piece":"Observatory", "payment":{"food":1,"wood":1,"ore":1}
+ }}}),
+ );
+ assert_eq!(time_increments(&game), [1, 0]);
+ assert_eq!(saved(&game)["rng"], rng);
+ assert!(!game.can_undo());
+}
+
+#[test]
+fn many_combat_rolls_in_one_action_coalesce_and_same_player_deterministic_response_does_not() {
+ let mut game = load(include_str!("test_games/combat/retreat.json"));
+ game.player_mut(0).units.retain(|unit| unit.id < 4);
+ for unit in &mut game.player_mut(0).units {
+ unit.unit_type = server::unit::UnitType::Infantry;
+ }
+ let defender = game.player(1).units[0].clone();
+ game.player_mut(1).units = (0..4)
+ .map(|id| {
+ let mut unit = defender.clone();
+ unit.id = id;
+ unit.unit_type = server::unit::UnitType::Cavalry;
+ unit
+ })
+ .collect();
+ game.player_mut(1).next_unit_id = 4;
+ game.dice_roll_outcomes = vec![4; 8];
+ let before_rolls = game.dice_roll_log.len();
+ let game = play(
+ game,
+ 0,
+ json!({"Movement":{"Move":{"units":[0,1,2,3],"destination":"C1"}}}),
+ );
+ assert_eq!(game.dice_roll_log.len() - before_rolls, 8);
+ assert_eq!(time_increments(&game), [1, 0]);
+ assert_eq!(game.active_player(), 0);
+ let game = play(game, 0, json!({"Response":{"Bool":true}}));
+ assert_eq!(time_increments(&game), [1, 0]);
+}
+
+#[test]
+fn off_turn_response_and_queued_end_turn_credit_their_own_actors() {
+ let mut value: Value =
+ serde_json::from_str(include_str!("test_games/action_cards/tech_trade.json")).unwrap();
+ value["round"] = json!(2);
+ value["players"][0]["advances"]
+ .as_array_mut()
+ .unwrap()
+ .push(json!("Irrigation"));
+ let game = play(
+ load(&value.to_string()),
+ 0,
+ json!({"Playing":{"ActionCard":39}}),
+ );
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(time_increments(&game), [1, 0]);
+ let (key, _) = action_queue::offer(&game, 0).unwrap();
+ let mut game = game;
+ for waiting in [true, false, true, false] {
+ game = play(
+ game,
+ 0,
+ json!({"QueueMoves":{"key":key,"actions":[{"Playing":"EndTurn"}],"waiting":waiting}}),
+ );
+ assert_eq!(time_increments(&game), [1, 0]);
+ }
+ game = load(&saved(&game).to_string());
+ game = play(game, 1, json!({"Response":{"SelectAdvance":"Fishing"}}));
+ assert_eq!(game.active_player(), 1);
+ assert_eq!(time_increments(&game), [2, 1]);
+ assert!(game.action_plan.is_none());
+}
+
+#[test]
+fn early_choice_revisions_are_free_then_automatic_handoffs_credit_each_actor() {
+ let game = load(include_str!(
+ "test_games/status_phase/raze_city_decline.json"
+ ));
+ let offer = server::early_choices::offers(&game, 1)
+ .into_iter()
+ .find(|offer| offer.title == "Raze city")
+ .unwrap();
+ let mut game = game;
+ for response in [
+ json!({"SelectPositions":[]}),
+ Value::Null,
+ json!({"SelectPositions":[]}),
+ ] {
+ game = play(
+ game,
+ 1,
+ json!({"QueueChoice":{"key":offer.key,"response":response}}),
+ );
+ assert_eq!(time_increments(&game), [0, 0]);
+ }
+ // Both responses are actual control handoffs, even though BGS saved one move.
+ game = play(game, 0, json!({"Response":{"SelectPositions":[]}}));
+ assert_eq!(time_increments(&game), [1, 1]);
+ assert!(game.early_choices.is_empty());
+}
+
+#[test]
+fn automatic_keep_government_is_not_a_boundary_when_control_stays_with_the_same_player() {
+ let mut game = load(include_str!("test_games/status_phase/keep_government.json"));
+ game.player_mut(0).settings.keep_government = Some(true);
+ assert_eq!(time_increments(&game), [0, 0]);
+ // Player 1 hands off to 0. Player 0's automatic payment then moves to a new
+ // status phase, but still asks player 0: an undo lock alone is not a credit.
+ game = play(game, 1, json!({"Response":{"SelectPositions":[]}}));
+ assert_eq!(game.active_player(), 0);
+ assert_eq!(time_increments(&game), [0, 1]);
+ assert!(matches!(
+ &game.current_event_handler().unwrap().request,
+ server::content::persistent_events::PersistentEventRequest::SelectPlayer(_)
+ ));
+}
+
+#[test]
+fn automatic_response_chain_keeps_the_preceding_multi_draw_credit() {
+ let game = load(include_str!("test_games/status_phase/free_advance.json"));
+ let game = play(game, 0, json!({"Playing":"EndTurn"}));
+ let game = play(game, 1, json!({"Response":{"SelectAdvance":"Storage"}}));
+ let before = time_increments(&game);
+ let cards_before: usize = game
+ .players
+ .iter()
+ .map(|p| p.action_cards.len() + p.objective_cards.len())
+ .sum();
+ let mut automatic = game.clone();
+ for player in &mut automatic.players {
+ player.settings.skip_raze_city = Some(true);
+ player.settings.keep_government = Some(true);
+ }
+ let response = json!({"Response":{"SelectAdvance":"Philosophy"}});
+ let mut manual = play(game, 0, response.clone());
+ assert_eq!(time_increments(&manual), [before[0] + 1, before[1]]);
+ let cards_after: usize = manual
+ .players
+ .iter()
+ .map(|p| p.action_cards.len() + p.objective_cards.len())
+ .sum();
+ assert!(
+ cards_after >= cards_before + 4,
+ "several draws still earn only one credit"
+ );
+ loop {
+ use server::content::persistent_events::PersistentEventRequest;
+ let response = match &manual.current_event_handler().unwrap().request {
+ PersistentEventRequest::SelectPositions(_) => {
+ json!({"Response":{"SelectPositions":[]}})
+ }
+ PersistentEventRequest::Payment(_) => json!({"Response":{"Payment":[{}]}}),
+ PersistentEventRequest::SelectPlayer(_) => break,
+ other => panic!("unexpected request {other:?}"),
+ };
+ let actor = manual.active_player();
+ manual = play(manual, actor, response);
+ }
+ let automatic = play(automatic, 0, response);
+ assert_eq!(time_increments(&automatic), time_increments(&manual));
+ assert_eq!(automatic.active_player(), manual.active_player());
+}
+
+#[test]
+fn initial_draft_commitments_credit_once_each_not_revisions_or_final_setup_draws() {
+ let mut game = setup_game(
+ &GameSetupBuilder::new(2)
+ .seed("timing-draft".into())
+ .options(GameOptions {
+ civilization: CivSetupOption::DraftThree,
+ ..GameOptions::default()
+ })
+ .build(),
+ );
+ let offers = game.civilization_draft.as_ref().unwrap().offers.clone();
+ assert_eq!(time_increments(&game), [0, 0]);
+ game = play(game, 0, json!({"ChooseCivilization":offers[0][0]}));
+ assert_eq!(time_increments(&game), [1, 0]);
+ game = load(&saved(&game).to_string());
+ for choice in &offers[0] {
+ game = play(game, 0, json!({"ChooseCivilization":choice}));
+ assert_eq!(time_increments(&game), [1, 0]);
+ }
+ game = play(game, 1, json!({"ChooseCivilization":offers[1][0]}));
+ assert!(game.civilization_draft.is_none());
+ assert_eq!(time_increments(&game), [1, 1]);
+}
+
+#[test]
+fn historical_replay_and_previews_preserve_not_recompute_clock_totals() {
+ let game = server::game_api::init(2, "timing-replay".into(), GameOptions::default());
+ let actor = game.active_player();
+ let game = play(game, actor, json!({"Playing":"EndTurn"}));
+ let counters = time_increments(&game);
+ let raw = saved(&game).to_string();
+ for target in [None, Some(server::game_api::log_length(&game))] {
+ let replayed = server::replay::replay(serde_json::from_str(&raw).unwrap(), target).unwrap();
+ assert_eq!(time_increments(&replayed), counters);
+ }
+ let next_actor = game.active_player();
+ let preview = server::action::try_execute_action(
+ game.clone(),
+ serde_json::from_value(json!({"Playing":"EndTurn"})).unwrap(),
+ next_actor,
+ )
+ .unwrap();
+ assert_eq!(time_increments(&preview), counters);
+ for context in [
+ GameContext::Replay,
+ GameContext::AI,
+ GameContext::CombatPreview,
+ ] {
+ let mut simulation = game.clone();
+ simulation.context = context;
+ let simulation = play(simulation, next_actor, json!({"Playing":"EndTurn"}));
+ assert_eq!(time_increments(&simulation), counters);
+ }
+}
+
+#[test]
+fn counters_saturate_at_js_safe_integer_and_reject_invalid_saved_values() {
+ let game = server::game_api::init(2, "timing-safe".into(), GameOptions::default());
+ let actor = game.active_player();
+ let mut value = saved(&game);
+ let max = (1_u64 << 53) - 1;
+ value["time_increments"] = json!([max, max]);
+ let game = play(
+ load(&value.to_string()),
+ actor,
+ json!({"Playing":"EndTurn"}),
+ );
+ assert_eq!(time_increments(&game), [max, max]);
+ for invalid in [json!([-1, 0]), json!([1.5, 0]), json!([max + 1, 0])] {
+ value["time_increments"] = invalid;
+ assert!(serde_json::from_value::(value.clone()).is_err());
+ }
+}
diff --git a/server/tests/wonder_payment_tests.rs b/server/tests/wonder_payment_tests.rs
new file mode 100644
index 00000000..d87c3137
--- /dev/null
+++ b/server/tests/wonder_payment_tests.rs
@@ -0,0 +1,168 @@
+use serde_json::{Value, json};
+use server::action::Action;
+use server::cache::Cache;
+use server::content::persistent_events::PersistentEventRequest;
+use server::game::{Game, GameContext};
+use server::game_data::GameData;
+use server::playing_actions::PlayingAction;
+use server::resource_pile::ResourcePile;
+use server::wonder::Wonder;
+use server::{game_api, web_view};
+use std::time::Instant;
+
+fn wonder_game(resources: ResourcePile) -> Game {
+ let mut data: Value =
+ serde_json::from_str(include_str!("test_games/wonders/colosseum.json")).unwrap();
+ // Engineering activates Architecture: mood may replace any construction
+ // resource or culture, in addition to the ordinary gold substitutions.
+ data["players"][0]["civilization"] = json!("Egypt");
+ data["players"][0]["resources"] = json!(resources);
+ let setup =
+ server::game_setup::setup_game(&server::game_setup::GameSetupBuilder::new(2).build());
+ let setup = serde_json::to_value(setup.data()).unwrap();
+ data["players"]
+ .as_array_mut()
+ .unwrap()
+ .extend(setup["players"].as_array().unwrap().iter().skip(2).cloned());
+ let data: GameData = serde_json::from_value(data).unwrap();
+ let cache = Cache::new(&data.options);
+ Game::from_data(data, cache, GameContext::Play)
+}
+
+#[test]
+#[ignore = "manual release-mode performance benchmark; prints the construct-to-payment path"]
+fn benchmark_wonder_payment_view() {
+ for resources in [
+ ResourcePile::new(3, 4, 5, 0, 2, 0, 5),
+ ResourcePile::new(7, 7, 7, 5, 7, 7, 7),
+ ] {
+ let game = wonder_game(resources.clone());
+ let start = Instant::now();
+ let before = web_view::view(&game, Some(0));
+ let availability = start.elapsed();
+ assert!(!before["wonderCards"][0]["action"].is_null());
+ let start = Instant::now();
+ let game = game_api::execute(
+ game,
+ Action::Playing(PlayingAction::WonderCard(Wonder::Colosseum)),
+ 0,
+ );
+ let construct = start.elapsed();
+ assert!(matches!(
+ game.current_event_handler().unwrap().request,
+ PersistentEventRequest::Payment(_)
+ ));
+ let start = Instant::now();
+ let view = web_view::view(&game, Some(0));
+ let payment_view = start.elapsed();
+ let start = Instant::now();
+ let query = web_view::query(&game, 0, json!({"kind":"decision", "values":[], "payments":[view["decision"]["fields"][0]["initial"]]})).unwrap();
+ let validation = start.elapsed();
+ assert!(!query["action"].is_null());
+ eprintln!(
+ "stock={resources:?}: availability={availability:?}, construct={construct:?}, payment view={payment_view:?}, query={validation:?}; choices={}",
+ view["decision"]["fields"][0]["choices"]
+ .as_array()
+ .map_or_else(|| "selectors".to_string(), |c| c.len().to_string())
+ );
+ }
+}
+
+#[test]
+fn architecture_preserves_all_bounded_wonder_payments() {
+ let stock = ResourcePile::new(3, 4, 5, 0, 2, 0, 5);
+ let game = game_api::execute(
+ wonder_game(stock.clone()),
+ Action::Playing(PlayingAction::WonderCard(Wonder::Colosseum)),
+ 0,
+ );
+ let view = web_view::view(&game, Some(0));
+ let choices: Vec =
+ serde_json::from_value(view["decision"]["fields"][0]["choices"].clone()).unwrap();
+ let mut expected = Vec::new();
+ for food_gold in 0..=2 {
+ for wood_gold in 0..=2 - food_gold {
+ for ore_gold in 0..=2 - food_gold - wood_gold {
+ expected.push(ResourcePile::new(
+ 3 - food_gold,
+ 4 - wood_gold,
+ 5 - ore_gold,
+ 0,
+ food_gold + wood_gold + ore_gold,
+ 0,
+ 5,
+ ));
+ }
+ }
+ }
+ assert_eq!(choices.len(), 10);
+ assert!(expected.iter().all(|payment| choices.contains(payment)));
+ for payment in choices {
+ assert!(
+ web_view::query(
+ &game,
+ 0,
+ json!({"kind":"decision", "values":[], "payments":[payment]})
+ )
+ .is_ok()
+ );
+ }
+ assert_eq!(
+ game.player(0).resources,
+ stock,
+ "Opening and quoting payments does not spend anything"
+ );
+}
+
+#[test]
+fn late_game_architecture_keeps_direct_mixed_payments_legal() {
+ let stock = ResourcePile::new(7, 7, 7, 5, 7, 7, 7);
+ let game = game_api::execute(
+ wonder_game(stock.clone()),
+ Action::Playing(PlayingAction::WonderCard(Wonder::Colosseum)),
+ 0,
+ );
+ let view = web_view::view(&game, Some(0));
+ let field = &view["decision"]["fields"][0];
+ assert!(
+ field["choices"].is_null(),
+ "Large spaces use direct amount selectors, not a truncated legal-payment list"
+ );
+ assert!(
+ field["resources"]
+ .as_array()
+ .unwrap()
+ .contains(&json!("mood_tokens"))
+ );
+ assert_eq!(game.player(0).resources, stock);
+ // Mood replaces two culture and two base resources, with four further
+ // resources replaced by gold. None of these alternatives may be capped.
+ let payment = ResourcePile::new(1, 2, 3, 0, 4, 4, 3);
+ let quote = web_view::query(
+ &game,
+ 0,
+ json!({"kind":"decision", "values":[], "payments":[payment]}),
+ )
+ .unwrap();
+ let mut underpayment = payment.clone();
+ underpayment.mood_tokens -= 1;
+ assert!(
+ web_view::query(
+ &game,
+ 0,
+ json!({"kind":"decision", "values":[], "payments":[underpayment]})
+ )
+ .is_err()
+ );
+ let action = serde_json::from_value(quote["action"].clone()).unwrap();
+ let paid = game_api::execute(game, action, 0);
+ let mut expected = stock;
+ expected -= payment;
+ assert_eq!(paid.player(0).resources, expected);
+ assert!(
+ paid.player(0)
+ .cities
+ .iter()
+ .any(|city| city.pieces.wonders.contains(&Wonder::Colosseum))
+ );
+}
diff --git a/web-client/README.md b/web-client/README.md
index acd0139c..50b03829 100644
--- a/web-client/README.md
+++ b/web-client/README.md
@@ -19,7 +19,7 @@ The local preview does not modify production games, catalog records, or chat roo
## Off-turn action queues
-After an opponent captures your city, its owner can plan while you place the replacement settler. Technology Trade also lets its owner plan while the recipient chooses their advance. Normal controls show the projected board; Undo removes the latest queued action with its payment responses. Wait for choice pauses planning. End turn may be queued last.
+After an opponent captures your city, its owner can plan while you place the replacement settler. Technology Trade also lets its owner plan while the recipient chooses their advance. Era of Stability permits planning while opponents choose their mood/culture token rewards, after the owner's own reward and exhausted-land choice have resolved. Queues persist across opponents' reward choices; they do not bypass mood-loss events. Normal controls show the projected board; Undo removes the latest queued action with its payment responses. Wait for choice pauses planning. End turn may be queued last.
Queues are private, stored in the game, and validated by the server. After the earlier response and any nested choices finish, valid queued actions execute in order even if the planning player is offline. Hidden draws, dice, battles and actions requiring another player cannot be queued. An invalid replay stops and reports an error.
diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md
index 4acc7825..d51504c9 100644
--- a/web-client/docs/viewer-publishing.md
+++ b/web-client/docs/viewer-publishing.md
@@ -663,3 +663,28 @@ the valid selection and preview when an extra tile is rejected. Selected
dual-resource tiles can be deselected from the map; resource replacement remains
available through the resource list. Add regressions for the four-tile limit,
dual-resource choices, deselection and Ballcourts capacity. No engine update required.
+
+## Viewer 0.1.186 / engine 0.4.125
+
+Filter Scouts when the opponent cannot play tactics or the attacker has passed,
+while preserving attacking Scouts and Viriatus's Loyalty. Show the opponent's
+public tactics commitment without exposing the card identity. Correct private
+card-log filtering and hide pending tactics in both combat state and discard piles.
+
+Allow action planning during opponents' Era of Stability token rewards, but not
+its exhausted-land choice or mood-loss events. Preserve queued actions across
+recipients. Normalize unordered collection-resource alternatives so Egypt's Flood
+Plains collection and Metallurgy choices can be queued while waiting for a settler.
+
+Export cumulative BGS time increments: credit genuine information reveals and
+player handoffs, not deterministic sub-actions, queue edits, Undo or Redo. Existing
+saves start from zero counters; credits survive history navigation and reload.
+
+Prune impossible wonder-payment conversion branches without limiting legal
+payments. Architecture payment views that took seconds now take roughly 9–10 ms
+in the local WASM benchmark. Publish the matching viewer and engine together.
+
+Verified 913 frontend tests, 199 targeted Rust tests, locale and type checks,
+engine protocol/timing checks, wonder-payment benchmarks, and desktop/mobile
+tactics browser checks. Broader Rust suites retain unrelated influence-log and
+Great Gardens error-text snapshot mismatches; those fixtures were not changed.
diff --git a/web-client/package-lock.json b/web-client/package-lock.json
index 38cc1f2a..a3e2cff9 100644
--- a/web-client/package-lock.json
+++ b/web-client/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@boardgamers/clash-web-client",
- "version": "0.1.185",
+ "version": "0.1.186",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@boardgamers/clash-web-client",
- "version": "0.1.185",
+ "version": "0.1.186",
"dependencies": {
"@boardgamers/protocol": "0.9.0",
"lucide-svelte": "^0.577.0",
diff --git a/web-client/package.json b/web-client/package.json
index 2f8eb1db..a3785838 100644
--- a/web-client/package.json
+++ b/web-client/package.json
@@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
- "version": "0.1.185",
+ "version": "0.1.186",
"private": true,
"type": "module",
"scripts": {
diff --git a/web-client/release/engine-checks.json b/web-client/release/engine-checks.json
index 3c93cc8d..93c4c539 100644
--- a/web-client/release/engine-checks.json
+++ b/web-client/release/engine-checks.json
@@ -8,9 +8,9 @@
"missing": []
},
"optional": {
- "completed": 14,
+ "completed": 15,
"total": 28,
- "percent": 50,
+ "percent": 54,
"missing": [
"presenceChanged",
"phase",
@@ -21,7 +21,6 @@
"moveAI",
"cancelled",
"toSave",
- "timeIncrements",
"stats",
"analysisUsesSimulation",
"analysisMove",
diff --git a/web-client/scripts/egypt-collect-queue-fixture.json b/web-client/scripts/egypt-collect-queue-fixture.json
new file mode 100644
index 00000000..4303dc36
--- /dev/null
+++ b/web-client/scripts/egypt-collect-queue-fixture.json
@@ -0,0 +1,749 @@
+{
+ "version": 2,
+ "state": {
+ "Movement": {
+ "movement_actions_left": 2,
+ "moved_units": [
+ 10
+ ]
+ }
+ },
+ "events": [
+ {
+ "event_type": {
+ "CombatEnd": {
+ "round": 1,
+ "battleground": "City",
+ "attacker": {
+ "position": "D6",
+ "player": 0,
+ "present": {
+ "elephants": 1
+ }
+ },
+ "defender": {
+ "position": "D7",
+ "player": 1
+ },
+ "result": "AttackerWins",
+ "city_mood": "Happy"
+ }
+ },
+ "players_used": [
+ 0
+ ],
+ "player": 1,
+ "last_priority_used": 102,
+ "handler": {
+ "priority": 102,
+ "request": {
+ "SelectPositions": {
+ "choices": [
+ "B6",
+ "D4"
+ ],
+ "needed": {
+ "start": 1,
+ "end": 1
+ },
+ "description": "Select a city to place the free Settler Unit"
+ }
+ },
+ "origin": {
+ "Ability": "Place Settler"
+ }
+ }
+ }
+ ],
+ "players": [
+ {
+ "id": 0,
+ "resources": {
+ "food": 4,
+ "ideas": 1,
+ "gold": 3,
+ "mood_tokens": 1,
+ "culture_tokens": 3
+ },
+ "resource_limit": {
+ "food": 7,
+ "wood": 7,
+ "ore": 7,
+ "ideas": 2,
+ "gold": 7
+ },
+ "cities": [
+ {
+ "city_pieces": {
+ "academy": 0,
+ "temple": 0,
+ "wonders": [
+ "GreatMausoleum"
+ ]
+ },
+ "mood_state": "Happy",
+ "position": "D2"
+ },
+ {
+ "city_pieces": {
+ "market": 0,
+ "wonders": [
+ "Pyramids"
+ ]
+ },
+ "mood_state": "Happy",
+ "position": "E3"
+ },
+ {
+ "city_pieces": {
+ "academy": 0
+ },
+ "mood_state": "Angry",
+ "position": "D7"
+ }
+ ],
+ "destroyed_structures": {
+ "obelisk": 1,
+ "observatory": 1,
+ "temple": 1,
+ "cities": 3
+ },
+ "units": [
+ {
+ "position": "C4",
+ "unit_type": {
+ "Leader": "Imhotep"
+ },
+ "id": 1
+ },
+ {
+ "position": "D7",
+ "unit_type": "Elephant",
+ "movement_restrictions": [
+ "Fertile",
+ "Battle",
+ "Fertile"
+ ],
+ "id": 10
+ },
+ {
+ "position": "E3",
+ "unit_type": "Settler",
+ "id": 11
+ }
+ ],
+ "civilization": "Egypt",
+ "available_leaders": [
+ "Cleopatra",
+ "Ramses"
+ ],
+ "recruited_leaders": [
+ "Imhotep"
+ ],
+ "advances": [
+ "Arts",
+ "Astronomy",
+ "Bartering",
+ "Conversion",
+ "Devotion",
+ "Dogma",
+ "Draft",
+ "Engineering",
+ "Fanaticism",
+ "Farming",
+ "Fishing",
+ "FreeEducation",
+ "Husbandry",
+ "Irrigation",
+ "Math",
+ "Medicine",
+ "Metallurgy",
+ "Mining",
+ "Monuments",
+ "Myths",
+ "Navigation",
+ "Philosophy",
+ "Priesthood",
+ "PublicEducation",
+ "Rituals",
+ "Roads",
+ "Sanitation",
+ "Sports",
+ "StateReligion",
+ "SteelWeapons",
+ "Storage",
+ "Tactics",
+ "Theaters",
+ "Writing"
+ ],
+ "wonders_built": [
+ "GreatMausoleum",
+ "Pyramids"
+ ],
+ "incident_tokens": 3,
+ "completed_objectives": [
+ {
+ "card": 24,
+ "name": "Barbarian Conquest"
+ },
+ {
+ "card": 36,
+ "name": "Legacy"
+ },
+ {
+ "card": 15,
+ "name": "Architecture"
+ },
+ {
+ "card": 18,
+ "name": "Culture Focus"
+ }
+ ],
+ "special_victory_points": [
+ {
+ "points": 2,
+ "origin": {
+ "Incident": 30
+ },
+ "attribution": "Events"
+ },
+ {
+ "points": 10,
+ "origin": {
+ "Incident": 31
+ },
+ "attribution": "Events"
+ }
+ ],
+ "action_cards": [
+ 0,
+ 0
+ ],
+ "objective_cards": [
+ 0,
+ 0,
+ 0
+ ],
+ "next_unit_id": 12
+ },
+ {
+ "id": 1,
+ "resources": {
+ "food": 4,
+ "wood": 2,
+ "ore": 2,
+ "ideas": 3,
+ "gold": 4,
+ "mood_tokens": 3,
+ "culture_tokens": 7
+ },
+ "resource_limit": {
+ "food": 7,
+ "wood": 7,
+ "ore": 7,
+ "ideas": 7,
+ "gold": 7
+ },
+ "cities": [
+ {
+ "city_pieces": {
+ "academy": 1,
+ "market": 1,
+ "port": 1
+ },
+ "mood_state": "Happy",
+ "position": "B6",
+ "port_position": "A7"
+ },
+ {
+ "mood_state": "Angry",
+ "position": "D4"
+ }
+ ],
+ "destroyed_structures": {
+ "cities": 2
+ },
+ "units": [
+ {
+ "position": "E5",
+ "unit_type": "Infantry",
+ "id": 4
+ },
+ {
+ "position": "D4",
+ "unit_type": {
+ "Leader": "Leonidas"
+ },
+ "id": 6
+ },
+ {
+ "position": "D4",
+ "unit_type": "Infantry",
+ "id": 8
+ },
+ {
+ "position": "C5",
+ "unit_type": "Ship",
+ "id": 9
+ },
+ {
+ "position": "C5",
+ "unit_type": "Ship",
+ "id": 10
+ }
+ ],
+ "civilization": "Greece",
+ "available_leaders": [
+ "Alexander",
+ "Pericles"
+ ],
+ "recruited_leaders": [
+ "Leonidas"
+ ],
+ "advances": [
+ "AbsolutePower",
+ "Astronomy",
+ "Bartering",
+ "Currency",
+ "Draft",
+ "Farming",
+ "Fishing",
+ "ForcedLabor",
+ "Irrigation",
+ "Math",
+ "Medicine",
+ "Mining",
+ "Nationalism",
+ "Navigation",
+ "PublicEducation",
+ "Sanitation",
+ "SteelWeapons",
+ "Storage",
+ "Tactics",
+ "Taxes",
+ "Totalitarianism",
+ "TradeRoutes",
+ "Writing"
+ ],
+ "incident_tokens": 1,
+ "completed_objectives": [
+ {
+ "card": 26,
+ "name": "Expansionist"
+ },
+ {
+ "card": 21,
+ "name": "Trade Focus"
+ }
+ ],
+ "special_victory_points": [
+ {
+ "points": 4,
+ "origin": {
+ "Incident": 31
+ },
+ "attribution": "Events"
+ }
+ ],
+ "action_cards": [
+ 0,
+ 0,
+ 0
+ ],
+ "objective_cards": [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0
+ ],
+ "next_unit_id": 11
+ },
+ {
+ "id": 2,
+ "civilization": "Barbarians",
+ "next_unit_id": 9
+ },
+ {
+ "id": 3,
+ "civilization": "Pirates",
+ "next_unit_id": 0
+ }
+ ],
+ "map": {
+ "tiles": [
+ [
+ "A3",
+ "Water"
+ ],
+ [
+ "A5",
+ "Forest"
+ ],
+ [
+ "A7",
+ "Water"
+ ],
+ [
+ "B2",
+ "Fertile"
+ ],
+ [
+ "B3",
+ "Mountain"
+ ],
+ [
+ "B4",
+ "Forest"
+ ],
+ [
+ "B5",
+ "Water"
+ ],
+ [
+ "B6",
+ "Fertile"
+ ],
+ [
+ "B7",
+ "Water"
+ ],
+ [
+ "C2",
+ "Barren"
+ ],
+ [
+ "C3",
+ "Barren"
+ ],
+ [
+ "C4",
+ "Fertile"
+ ],
+ [
+ "C5",
+ "Water"
+ ],
+ [
+ "C6",
+ "Mountain"
+ ],
+ [
+ "C7",
+ "Forest"
+ ],
+ [
+ "C8",
+ "Mountain"
+ ],
+ [
+ "D1",
+ "Barren"
+ ],
+ [
+ "D2",
+ "Fertile"
+ ],
+ [
+ "D3",
+ "Fertile"
+ ],
+ [
+ "D4",
+ "Forest"
+ ],
+ [
+ "D5",
+ "Fertile"
+ ],
+ [
+ "D6",
+ "Fertile"
+ ],
+ [
+ "D7",
+ "Fertile"
+ ],
+ [
+ "D8",
+ "Barren"
+ ],
+ [
+ "E2",
+ "Mountain"
+ ],
+ [
+ "E3",
+ "Fertile"
+ ],
+ [
+ "E4",
+ "Fertile"
+ ],
+ [
+ "E5",
+ "Barren"
+ ],
+ [
+ "E6",
+ "Forest"
+ ],
+ [
+ "E7",
+ "Fertile"
+ ],
+ [
+ "E8",
+ "Forest"
+ ],
+ [
+ "F2",
+ {
+ "Exhausted": "Mountain"
+ }
+ ],
+ [
+ "F3",
+ "Mountain"
+ ],
+ [
+ "F4",
+ "Water"
+ ],
+ [
+ "F5",
+ {
+ "Exhausted": "Fertile"
+ }
+ ],
+ [
+ "F6",
+ {
+ "Exhausted": "Forest"
+ }
+ ],
+ [
+ "F7",
+ "Forest"
+ ],
+ [
+ "G3",
+ "Water"
+ ],
+ [
+ "G5",
+ "Forest"
+ ],
+ [
+ "G7",
+ "Water"
+ ]
+ ]
+ },
+ "starting_player_index": 1,
+ "current_player_index": 0,
+ "log": [
+ {
+ "age": 6,
+ "rounds": [
+ {
+ "round": 3,
+ "turns": [
+ {
+ "turn_type": {
+ "Player": 0
+ }
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "board_history": {
+ "id": "egypt-collect-queue",
+ "frames": []
+ },
+ "log_index": 0,
+ "undo_limit": 0,
+ "actions_left": 1,
+ "round": 3,
+ "age": 6,
+ "messages": [],
+ "dice_roll_log": [
+ 6,
+ 4,
+ 8,
+ 2,
+ 6,
+ 3,
+ 9,
+ 5,
+ 6,
+ 5,
+ 6,
+ 7,
+ 9,
+ 2,
+ 5,
+ 6,
+ 2,
+ 10,
+ 7,
+ 10,
+ 6,
+ 1,
+ 3,
+ 9,
+ 9,
+ 11,
+ 2,
+ 9,
+ 4,
+ 1,
+ 8,
+ 2,
+ 0,
+ 4,
+ 6,
+ 0,
+ 11,
+ 3,
+ 5,
+ 8
+ ],
+ "wonders_left": [
+ "GreatLighthouse",
+ "GreatStatue",
+ "GreatLibrary",
+ "GreatWall",
+ "GreatGardens",
+ "Colosseum"
+ ],
+ "action_cards_left": [
+ 19,
+ 9,
+ 22,
+ 42,
+ 2,
+ 12,
+ 20,
+ 40,
+ 16,
+ 33,
+ 38,
+ 27,
+ 18,
+ 6,
+ 25,
+ 1,
+ 13,
+ 31,
+ 36,
+ 34,
+ 32,
+ 28,
+ 10,
+ 30,
+ 29,
+ 17,
+ 37,
+ 5
+ ],
+ "action_cards_discarded": [
+ 3,
+ 7,
+ 26,
+ 121,
+ 8,
+ 4,
+ 41,
+ 39,
+ 35,
+ 11
+ ],
+ "objective_cards_left": [
+ 23,
+ 20,
+ 11,
+ 3,
+ 29,
+ 37,
+ 5,
+ 31,
+ 1,
+ 6,
+ 4,
+ 38,
+ 30,
+ 2,
+ 33,
+ 7,
+ 12,
+ 13,
+ 16,
+ 9,
+ 27,
+ 34,
+ 22,
+ 8
+ ],
+ "incidents_left": [
+ 16,
+ 5,
+ 55,
+ 42,
+ 12,
+ 54,
+ 10,
+ 23,
+ 4,
+ 19,
+ 22,
+ 33,
+ 32,
+ 28,
+ 7,
+ 24,
+ 50,
+ 48,
+ 43,
+ 18,
+ 37,
+ 34,
+ 29,
+ 56,
+ 46,
+ 45,
+ 26,
+ 58,
+ 51,
+ 40,
+ 41,
+ 1,
+ 25,
+ 49,
+ 8,
+ 3,
+ 2,
+ 39,
+ 44,
+ 20,
+ 6,
+ 57,
+ 53,
+ 15,
+ 13
+ ],
+ "incidents_discarded": [
+ 27,
+ 11,
+ 35,
+ 38,
+ 36,
+ 52,
+ 30,
+ 14,
+ 17,
+ 9
+ ]
+}
diff --git a/web-client/scripts/release-engine-check.mjs b/web-client/scripts/release-engine-check.mjs
index 870db6e1..30238d74 100644
--- a/web-client/scripts/release-engine-check.mjs
+++ b/web-client/scripts/release-engine-check.mjs
@@ -7,7 +7,15 @@ const diagnostics=inspectEngine(engine);assert(diagnostics.compatible);
let raw=await engine.init(2,[],{},'release-check-2026-10-18',{});
const seat=engine.currentPlayer(raw);
assert.equal(typeof seat,'number');
-for(let i=0;i<2;i++) raw=engine.move(raw,JSON.stringify({Playing:'EndTurn'}),engine.currentPlayer(raw));
+assert.equal(typeof engine.timeIncrements,'function');
+assert(Array.isArray(engine.timeIncrements(raw)),'Clock hook must return a JS array');
+assert.deepEqual(engine.timeIncrements(raw),[0,0]);
+for(let i=0;i<2;i++) {
+ const actor=engine.currentPlayer(raw), expected=engine.timeIncrements(raw);
+ expected[actor]++;
+ raw=engine.move(raw,JSON.stringify({Playing:'EndTurn'}),actor);
+ assert.deepEqual(engine.timeIncrements(raw),expected,'A control handoff earns exactly one credit');
+}
assert.equal(engine.replay(raw,{}),engine.replay(raw,{}),'Replay must be deterministic');
const scenarios=[];
for(const player of [0,1,undefined]) {
@@ -23,16 +31,21 @@ for(const player of [0,1,undefined]) {
}
}
// Account setting revisions do not append game history or award another turn.
-const before=engine.logLength(raw);
+const before=engine.logLength(raw), clockBeforeSettings=engine.timeIncrements(raw);
for(let n=0;n<100;n++)raw=engine.setPlayerSettings(raw,0,{skipRazeCity:n%2===0});
assert.equal(engine.logLength(raw),before);
+assert.deepEqual(engine.timeIncrements(raw),clockBeforeSettings);
let loop=await engine.init(2,[],{},'release-undo-check',{});
const loopSeat=engine.currentPlayer(loop), city=JSON.parse(loop).players[loopSeat].cities[0].position;
const collect=JSON.stringify({Playing:{Collect:{city_position:city,collections:[{position:city,pile:{food:1},times:1}],action_type:'Collect'}}});
let firstSize;
for(let n=0;n<100;n++) {
loop=engine.move(loop,collect,loopSeat);
+ assert.deepEqual(engine.timeIncrements(loop),[0,0],'Deterministic collection earns no clock time');
loop=engine.move(loop,JSON.stringify('Undo'),loopSeat);
+ loop=engine.move(loop,JSON.stringify('Redo'),loopSeat);
+ loop=engine.move(loop,JSON.stringify('Undo'),loopSeat);
+ assert.deepEqual(engine.timeIncrements(loop),[0,0],'Undo/Redo cannot farm clock time');
if(n===0)firstSize=loop.length;
assert.equal(loop.length,firstSize,'Collect/undo must not grow the save');
}
diff --git a/web-client/scripts/tactics-choices-smoke.mjs b/web-client/scripts/tactics-choices-smoke.mjs
index 5028245a..0d64d9f9 100644
--- a/web-client/scripts/tactics-choices-smoke.mjs
+++ b/web-client/scripts/tactics-choices-smoke.mjs
@@ -76,6 +76,7 @@ try {
);
const panel = page.getByRole('region', { name: 'Tactics', exact: true });
await panel.waitFor();
+ assert.equal(await panel.getByRole('status').innerText(), 'Opponent is not playing a tactics card.');
const peltasts = panel.getByRole('button', { name: 'Select Peltasts', exact: true });
await peltasts.waitFor();
assert.match(await peltasts.innerText(), /Roll a die for each of your Army units/);
diff --git a/web-client/scripts/timing-check.mjs b/web-client/scripts/timing-check.mjs
new file mode 100644
index 00000000..45bf917f
--- /dev/null
+++ b/web-client/scripts/timing-check.mjs
@@ -0,0 +1,91 @@
+// Run after build:bridge: node scripts/timing-check.mjs
+// Test real WASM exports: the protocol needs a JS array, not a JSON string,
+// Uint32Array or bigint[]. Both move and tryMove must obey the same policy.
+import assert from 'node:assert/strict';
+import {createRequire} from 'node:module';
+import {readFile} from 'node:fs/promises';
+const engine = createRequire(import.meta.url)('../.engine/server.js');
+const fixture = name => readFile(new URL(`../../server/tests/test_games/${name}.json`, import.meta.url), 'utf8');
+const move = (raw, player, action, method = 'move') => engine[method](raw, JSON.stringify(action), player);
+function credits(raw, expected) {
+ const actual = engine.timeIncrements(raw);
+ assert(Array.isArray(actual), 'timeIncrements must return an actual JS array');
+ assert(actual.every(value => Number.isSafeInteger(value) && value >= 0));
+ assert.deepEqual(actual, expected);
+}
+assert.equal(typeof engine.timeIncrements, 'function');
+
+for (const method of ['move', 'tryMove']) {
+ let raw = await fixture('advances/collect_free_economy');
+ credits(raw, [0, 0]);
+ const data = JSON.parse(raw);
+ data.time_increments = [11, 5];
+ raw = JSON.stringify(data);
+ const collect = {Playing: {Collect: {city_position: 'C2', collections: [{position: 'B1', pile: {ore: 1}, times: 1}], action_type: 'Collect'}}};
+ for (let n = 0; n < 20; n++) {
+ raw = move(raw, 0, collect, method);
+ credits(raw, [11, 5]);
+ raw = move(raw, 0, 'Undo', method);
+ credits(raw, [11, 5]);
+ raw = move(raw, 0, 'Redo', method);
+ credits(raw, [11, 5]);
+ raw = move(raw, 0, 'Undo', method);
+ credits(raw, [11, 5]);
+ }
+ raw = move(raw, 0, {Playing: 'EndTurn'}, method);
+ credits(raw, [12, 5]);
+
+ raw = await fixture('action_cards/spy');
+ const rng = JSON.parse(raw).rng;
+ raw = move(raw, 0, {Playing: {ActionCard: 7}}, method);
+ credits(raw, [0, 0]);
+ raw = move(raw, 0, {Response: {Payment: [{culture_tokens: 1}]}}, method);
+ credits(raw, [1, 0]);
+ assert.equal(JSON.parse(raw).rng, rng, 'Spy reveals information without RNG changes');
+ const declined = move(raw, 0, {Response: {SelectHandCards: []}}, method);
+ credits(declined, [1, 0]);
+ raw = move(raw, 0, {Response: {SelectHandCards: [{ActionCard: 1}, {ActionCard: 2}]}}, method);
+ credits(raw, [2, 0]);
+
+ raw = await fixture('movement/explore_resolution');
+ raw = move(raw, 1, {Movement: {Move: {units: [0], destination: 'D6'}}}, method);
+ credits(raw, [0, 1]);
+ raw = move(raw, 1, {Response: {ExploreResolution: 3}}, method);
+ credits(raw, [0, 1]);
+ raw = move(raw, 1, 'Undo', method);
+ credits(raw, [0, 1]);
+
+ raw = await fixture('base/same_player_undo');
+ raw = move(raw, 0, {Playing: {Construct: {city_position: 'C2', city_piece: 'Observatory', payment: {food: 1, wood: 1, ore: 1}}}}, method);
+ credits(raw, [1, 0]);
+
+ const trade = JSON.parse(await fixture('action_cards/tech_trade'));
+ trade.round = 2;
+ trade.players[0].advances.push('Irrigation');
+ raw = move(JSON.stringify(trade), 0, {Playing: {ActionCard: 39}}, method);
+ credits(raw, [1, 0]);
+ const {key} = JSON.parse(engine.webPlanning(raw, 0));
+ for (const waiting of [true, false, true, false]) {
+ raw = move(raw, 0, {QueueMoves: {key, actions: [{Playing: 'EndTurn'}], waiting}}, method);
+ credits(raw, [1, 0]);
+ }
+ raw = move(raw, 1, {Response: {SelectAdvance: 'Fishing'}}, method);
+ credits(raw, [2, 1]); // Responder's handoff + queued owner's EndTurn.
+
+ raw = await engine.init(2, [], {civilization: 'DraftThree'}, 'timing-js-draft', {});
+ const offers = JSON.parse(raw).civilization_draft.offers;
+ credits(raw, [0, 0]);
+ for (const choice of offers[0]) {
+ raw = move(raw, 0, {ChooseCivilization: choice}, method);
+ credits(raw, [1, 0]);
+ }
+ raw = move(raw, 1, {ChooseCivilization: offers[1][0]}, method);
+ credits(raw, [1, 1]);
+ for (let n = 0; n < 5; n++) {
+ raw = engine.setPlayerSettings(raw, 0, {skipRazeCity: n % 2 === 0, keepGovernment: n % 2 !== 0});
+ credits(raw, [1, 1]);
+ }
+ credits(engine.replay(raw, {}), [1, 1]);
+ for (const viewer of [0, 1, undefined]) credits(engine.stripSecret(raw, viewer), [1, 1]);
+}
+console.log('Clock increments: JS array contract, move/tryMove, undo/redo, reveals, handoffs, queues, draft and settings passed');
diff --git a/web-client/scripts/wonder-payment-perf.mjs b/web-client/scripts/wonder-payment-perf.mjs
new file mode 100644
index 00000000..21fe25a1
--- /dev/null
+++ b/web-client/scripts/wonder-payment-perf.mjs
@@ -0,0 +1,58 @@
+// Run after building the engine bridge:
+// node scripts/wonder-payment-perf.mjs
+// Optional slow-machine override: WONDER_PAYMENT_BUDGET_MS=500 node ...
+// Uses local fixtures only: no network calls or live-game moves.
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { createRequire } from 'node:module';
+import { performance } from 'node:perf_hooks';
+
+const engine = createRequire(import.meta.url)('../.engine/server.js');
+const original = JSON.parse(await readFile(new URL('../../server/tests/test_games/wonders/colosseum.json', import.meta.url), 'utf8'));
+const npcs = JSON.parse(await engine.init(2, [], {}, 'wonder-payment-perf', {})).players.slice(2);
+const budget = Number(process.env.WONDER_PAYMENT_BUDGET_MS ?? 250);
+const construct = JSON.stringify({ Playing: { WonderCard: 'Colosseum' } });
+const cases = [
+ { name: 'ordinary gold', civilization: 'Greece', stock: { food: 3, wood: 4, ore: 5, gold: 2, culture_tokens: 5 }, choices: 10 },
+ { name: 'Architecture, no mood', civilization: 'Egypt', stock: { food: 3, wood: 4, ore: 5, gold: 2, culture_tokens: 5 }, choices: 10 },
+ { name: 'Architecture, late game', civilization: 'Egypt', stock: { food: 7, wood: 7, ore: 7, ideas: 5, gold: 7, mood_tokens: 7, culture_tokens: 7 }, choices: null },
+];
+let slow = false;
+for (const fixture of cases) {
+ const game = structuredClone(original);
+ game.players.push(...structuredClone(npcs));
+ game.players[0].civilization = fixture.civilization;
+ game.players[0].resources = fixture.stock;
+ const raw = engine.stripSecret(JSON.stringify(game), 0);
+ const timings = {};
+ const time = (name, fn) => {
+ const start = performance.now();
+ const value = fn();
+ timings[name] = Number((performance.now() - start).toFixed(2));
+ return value;
+ };
+ const before = JSON.parse(time('availability', () => engine.webView(raw, 0)));
+ assert(before.wonderCards[0].action, 'The wonder is constructible');
+ const after = time('construct', () => engine.tryMove(raw, construct, 0));
+ const view = JSON.parse(time('paymentView', () => engine.webView(after, 0)));
+ const field = view.decision.fields[0];
+ assert.equal(field.name, 'Pay to build wonder');
+ assert.equal(field.choices?.length ?? null, fixture.choices);
+ const query = JSON.parse(time('paymentQuery', () => engine.webQuery(after, 0, JSON.stringify({ kind: 'decision', values: [], payments: [field.initial] }))));
+ assert(query.action, 'The initial payment is valid before spending');
+ time('cachedStateView', () => engine.webView(after, 0));
+ assert.deepEqual(JSON.parse(after).players[0].resources, fixture.stock, 'Opening the payment has not spent resources');
+ if (fixture.choices === null) {
+ // Large spaces must still allow legal gold + mood + culture mixes through
+ // direct selectors; the display-list limit must never become a rules limit.
+ const payment = { food: 1, wood: 2, ore: 3, gold: 4, mood_tokens: 4, culture_tokens: 3 };
+ const selected = JSON.parse(time('mixedQuery', () => engine.webQuery(after, 0, JSON.stringify({ kind: 'decision', values: [], payments: [payment] }))));
+ assert(selected.action);
+ const paid = JSON.parse(engine.tryMove(after, JSON.stringify(selected.action), 0));
+ assert(paid.players[0].cities.some((city) => city.city_pieces?.wonders?.includes('Colosseum')));
+ for (const [resource, amount] of Object.entries(payment)) assert.equal(paid.players[0].resources[resource] ?? 0, fixture.stock[resource] - amount);
+ }
+ console.log(`${fixture.name}: ${JSON.stringify(timings)} ms`);
+ slow ||= timings.paymentView > budget || timings.cachedStateView > budget;
+}
+assert(!slow, `Wonder payment view exceeded ${budget} ms; investigate before raising the budget`);
diff --git a/web-client/src/DecisionPanel.svelte b/web-client/src/DecisionPanel.svelte
index e4315a35..364ada1a 100644
--- a/web-client/src/DecisionPanel.svelte
+++ b/web-client/src/DecisionPanel.svelte
@@ -22,7 +22,7 @@
import UnitPicker, { type UnitChoice } from './UnitPicker.svelte';
import StructurePicker, { type StructureChoice } from './StructurePicker.svelte';
import { researchPresentation } from './research';
- import { canCancelAbility, mapDecisionOptions } from './decision-controls';
+ import { canCancelAbility, mapDecisionOptions, opponentTacticsLabel } from './decision-controls';
import { steelWeaponsBenefit } from './active-combat';
let {
controller,
@@ -33,6 +33,7 @@
const session = $derived(controller.session);
const panelId = $props.id();
const selected = $derived($session.decisionSelection);
+ const opponentTactics = $derived(opponentTacticsLabel(decision));
const tribalStopChoice = $derived(decision.name === 'Tribal Allies' && decision.description === 'Select armies to stop · 1 food total');
const razeChoice = $derived(decision.name === 'Raze city');
const firstPlayerChoice = $derived(decision.name === 'Determine First Player');
@@ -287,6 +288,9 @@
text={description.replaceAll('Status Phase', 'End of age').replaceAll('status phase', 'end of age')}
/>
{/if}
+ {#if opponentTactics}
+ {opponentTactics}
+
{/if}
{#if decision.options.length}
{#if decision.tacticsSelection}
@@ -519,6 +523,18 @@