From 40bda526f560dbf6a7e0084e5f64613982f6766a Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Tue, 17 Nov 2026 22:39:11 +0000 Subject: [PATCH] Use committed asynchronous combat preparation and preserve replay branches --- docs/asynchronous-combat-preparation.md | 65 + server/src/combat.rs | 13 +- server/src/combat_listeners.rs | 97 +- server/src/early_choices.rs | 157 +- server/src/game.rs | 1 + server/src/game_data.rs | 11 +- server/src/game_setup.rs | 1 + server/src/log.rs | 6 + server/src/replay.rs | 13 + server/src/undo.rs | 6 +- server/src/web_view.rs | 10 - server/src/web_view/combat_summary.rs | 15 +- server/tests/combat_preparation_tests.rs | 401 +++ server/tests/common/mod.rs | 13 +- .../legacy_combat_history.expected.json | 483 +++ .../tests/fixtures/legacy_combat_history.json | 3015 +++++++++++++++++ .../tests/fixtures/legacy_combat_history.md | 17 + server/tests/scouts_tests.rs | 1 + server/tests/tactics_queue_tests.rs | 275 -- server/tests/test_games/base/new_game.json | 1 + web-client/docs/viewer-publishing.md | 44 + web-client/package-lock.json | 4 +- web-client/package.json | 2 +- web-client/release/achievement-assets.json | 2 +- web-client/release/engine-package.json | 2 +- web-client/scripts/local-host-smoke.mjs | 94 +- web-client/scripts/preview-scenarios.ts | 2 +- web-client/scripts/tactics-queue-smoke.mjs | 93 - web-client/src/App.svelte | 8 +- web-client/src/DecisionPanel.svelte | 26 +- web-client/src/combat-estimate.test.ts | 3 +- .../src/combat-preparation-engine.test.ts | 165 + web-client/src/localization/da.json | 1 - web-client/src/localization/de.json | 1 - web-client/src/localization/el.json | 1 - web-client/src/localization/en.json | 1 - web-client/src/localization/fa.json | 1 - web-client/src/localization/fr.json | 1 - web-client/src/localization/hi.json | 1 - web-client/src/localization/it.json | 1 - web-client/src/localization/ko.json | 1 - web-client/src/localization/nl.json | 1 - web-client/src/localization/pl.json | 1 - web-client/src/localization/pt-BR.json | 1 - web-client/src/localization/ro.json | 1 - web-client/src/localization/ru.json | 1 - web-client/src/localization/vi.json | 1 - web-client/src/localization/zh-CN.json | 1 - web-client/src/localization/zh-TW.json | 1 - web-client/src/queued-tactics.test.ts | 42 - web-client/src/queued-tactics.ts | 40 - web-client/src/siegecraft.test.ts | 6 +- web-client/src/tactics-queue-engine.test.ts | 68 - 53 files changed, 4472 insertions(+), 747 deletions(-) create mode 100644 docs/asynchronous-combat-preparation.md create mode 100644 server/tests/combat_preparation_tests.rs create mode 100644 server/tests/fixtures/legacy_combat_history.expected.json create mode 100644 server/tests/fixtures/legacy_combat_history.json create mode 100644 server/tests/fixtures/legacy_combat_history.md delete mode 100644 server/tests/tactics_queue_tests.rs delete mode 100644 web-client/scripts/tactics-queue-smoke.mjs create mode 100644 web-client/src/combat-preparation-engine.test.ts delete mode 100644 web-client/src/queued-tactics.test.ts delete mode 100644 web-client/src/queued-tactics.ts delete mode 100644 web-client/src/tactics-queue-engine.test.ts diff --git a/docs/asynchronous-combat-preparation.md b/docs/asynchronous-combat-preparation.md new file mode 100644 index 00000000..585e4a90 --- /dev/null +++ b/docs/asynchronous-combat-preparation.md @@ -0,0 +1,65 @@ +# Asynchronous combat preparation — release preparation + +Prepared for viewer **0.1.221** and engine **0.4.154**. This implements the requested +asynchronous interpretation, **not a claim about an official ruling**. Local +preparation is not publication: matching pushed CI and hosted verification remain +mandatory before calling the release shipped. + +For a new battle, the ordinary decision sequence is: + +1. Attacker's battle-start abilities (including Steel Weapons and Siegecraft). +2. Existing tactics-eligibility and Loyalty steps. +3. Attacker's tactics card or pass. +4. Defender's battle-start abilities, then defender's tactics card or pass. +5. Reveal, card effects (including actual Martyr sacrifice choices), then rolls. + +**Special-case exception:** tactics-eligibility effects and Loyalty still run +before either ordinary tactics selection. In particular, Loyalty may let a third +player supply a Barbarian defender's card first. Moving this after the attacker's +choice would change card eligibility (including Scouts); this implementation preserves +those rules instead of silently redefining them. Subsequent rounds retain their +existing eligibility/Loyalty, attacker tactics, defender tactics, reveal sequence. +Battle-start abilities run once, not each round. + +These are normal committed responses, not editable private queues. The opponent +can know whether a card was played, but its identity remains hidden until reveal. +The existing masking of the matching discard-pile occurrence is retained. +Other early choices still use QueueChoice. Obsolete `/tactics` plans are removed +on load/prune and never automatically consumed. + +## Saved state and history + +`Combat.asynchronous_preparation` selects the new sequence for that battle. +Absence means legacy; an already-open legacy battle finishes in the old order. +`CombatRoundStart.preparation` persists the exact first-round continuation, +including both strengths, across saves and ordinary response handling. Start +ability listeners still receive their original `Combat` payload; their serializer +wraps the resulting combat back into that continuation. + +`asynchronous_combat_from` is a **format/history boundary**, not a release version. +New games start at zero. A legacy live save records the current action index when +its first new battle starts. Historical replay without a boundary uses the old +sequence through the recorded history and enables the new sequence only beyond +that history. With a boundary, replay uses the recorded switch point while +reconstructing. Before returning a playable replay cursor, the boundary is clamped +to its next action: discarded future history must not force new branch battles +into legacy order. Redo preserves the recorded boundary; a fresh action replacing +an undone future clamps it likewise. The boundary is excluded from gameplay undo +patches: undoing a newly branched battle must not resurrect the discarded future's +switch and make redo run it as legacy. Already-open battles retain their own mode. +Historical +golden fixtures explicitly select the legacy path; focused preparation tests +exercise the new one. No old recorded responses are reordered. + +## Local preview + +The existing “Tactics · Steel Weapons” scenario starts at Rome's Steel Weapons +payment. Confirming immediately opens Rome's normal Tactics panel; only after +playing/passing does Greece become active. Restart scenario returns to Rome's +payment. The map/layout code is unchanged. + +The frozen synthetic 217-action fixture in `server/tests/fixtures/legacy_combat_history.json` +was independently replayed by production engine 0.4.153. Its expected state is +checked through actual `engine.replay`, not by merely applying responses to a +mutated battle fixture. Native tests also cover full-save and partial-history +branches, branch replay, and undo/redo switch handling. diff --git a/server/src/combat.rs b/server/src/combat.rs index d803a6bd..e97683f5 100644 --- a/server/src/combat.rs +++ b/server/src/combat.rs @@ -49,6 +49,8 @@ pub enum CombatRetreatState { #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub struct Combat { + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub asynchronous_preparation: bool, pub attackers: Vec, pub retreat: CombatRetreatState, #[serde(default)] @@ -61,6 +63,7 @@ impl Combat { #[must_use] pub fn new(attackers: Vec, can_retreat: bool, stats: CombatStats) -> Self { Self { + asynchronous_preparation: false, attackers, modifiers: vec![], retreat: if can_retreat { @@ -219,7 +222,11 @@ pub fn initiate_combat( &attackers, None, ); - let combat = Combat::new(attackers, can_retreat, stats); + let mut combat = Combat::new(attackers, can_retreat, stats); + // Persist the history boundary, rather than reinterpret old logged responses. + let index = crate::game_api::log_length(game); + let from = *game.asynchronous_combat_from.get_or_insert(index); + combat.asynchronous_preparation = index >= from; log_round(game, &combat); start_combat(game, combat); } @@ -261,6 +268,10 @@ pub(crate) fn log_round(game: &mut Game, c: &Combat) { pub(crate) fn start_combat(game: &mut Game, combat: Combat) { stop_current_move(game); + if combat.asynchronous_preparation { + combat_loop(game, CombatRoundStart::new(combat)); + return; + } let Some(c) = game.trigger_persistent_event( &combat.players(), diff --git a/server/src/combat_listeners.rs b/server/src/combat_listeners.rs index f3c2de79..ccdc1218 100644 --- a/server/src/combat_listeners.rs +++ b/server/src/combat_listeners.rs @@ -84,8 +84,20 @@ impl CombatEventPhase { } } +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] +pub enum PreparationStep { + AttackerAbilities, + Eligibility, + Loyalty, + AttackerTactics, + DefenderAbilities, + DefenderTactics, +} + #[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub struct CombatRoundStart { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preparation: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub displaced_unit: Option, pub combat: Combat, @@ -103,6 +115,8 @@ impl CombatRoundStart { #[must_use] pub fn new(combat: Combat) -> Self { Self { + preparation: (combat.asynchronous_preparation && combat.first_round()) + .then_some(PreparationStep::AttackerAbilities), combat, displaced_unit: None, attacker_strength: CombatStrength::new(), @@ -277,8 +291,11 @@ const ROUND_START_TYPES: &[CombatEventPhase; 5] = &[ pub(crate) fn combat_round_start( game: &mut Game, - start: CombatRoundStart, + mut start: CombatRoundStart, ) -> Option { + if start.preparation.is_some() { + start = prepare_first_round(game, start)?; + } event_with_tactics( game, start, @@ -299,6 +316,84 @@ pub(crate) fn combat_round_start( ) } +// Start listeners still receive Combat; the serialized continuation contains the +// entire round, including the attacker's hidden selection while the defender pays. +fn prepare_first_round(game: &mut Game, mut round: CombatRoundStart) -> Option { + use PreparationStep::*; + while let Some(step) = round.preparation.clone() { + match step { + AttackerAbilities | DefenderAbilities => { + let player = if step == AttackerAbilities { + round.combat.attacker() + } else { + round.combat.defender() + }; + let saved = round.clone(); + round.combat = game.trigger_persistent_event( + &[player], + |e| &mut e.combat_start, + round.combat.clone(), + move |combat| { + let mut continuation = saved.clone(); + continuation.combat = combat; + PersistentEventType::CombatRoundStart(continuation) + }, + )?; + } + Eligibility => { + round = game.trigger_persistent_event( + &round.combat.players(), + |e| &mut e.combat_round_start_allow_tactics, + round, + PersistentEventType::CombatRoundStart, + )?; + } + Loyalty => { + if let Some(player) = + crate::content::civilizations::celts::loyalty_controller(game, &round.combat) + { + round = game.trigger_persistent_event( + &[player], + |e| &mut e.loyalty, + round, + PersistentEventType::CombatRoundStart, + )?; + } + } + AttackerTactics | DefenderTactics => { + let player = if step == AttackerTactics { + round.combat.attacker() + } else { + round.combat.defender() + }; + round = game.trigger_persistent_event( + &[player], + |e| &mut e.combat_round_start, + round, + PersistentEventType::CombatRoundStart, + )?; + } + } + round.preparation = match step { + AttackerAbilities => Some(Eligibility), + Eligibility => Some(Loyalty), + Loyalty => Some(AttackerTactics), + AttackerTactics => Some(DefenderAbilities), + DefenderAbilities => Some(DefenderTactics), + DefenderTactics => None, + }; + round.phase = match round.preparation { + Some(AttackerAbilities | Eligibility) => CombatEventPhase::AllowTacticsCard, + Some(Loyalty) => CombatEventPhase::Loyalty, + Some(AttackerTactics | DefenderAbilities | DefenderTactics) => { + CombatEventPhase::Default + } + None => CombatEventPhase::RevealTacticsCard, + }; + } + Some(round) +} + const ROUND_END_TYPES: &[CombatEventPhase; 3] = &[ CombatEventPhase::TacticsCard, CombatEventPhase::Default, diff --git a/server/src/early_choices.rs b/server/src/early_choices.rs index f4da2d4a..ebf1760f 100644 --- a/server/src/early_choices.rs +++ b/server/src/early_choices.rs @@ -31,99 +31,6 @@ pub struct Offer { pub selected: Option, } -// A plan belongs to this battle round, not to a transient event phase. -fn tactics_key(game: &Game, combat: &crate::combat::Combat) -> String { - format!( - "{}:{}:{}:{}:{}:{}:{}/tactics", - game.age, - game.round, - game.current_player_index, - game.actions_left, - combat.attacker(), - combat.defender_position(), - combat.stats.round - ) -} - -fn tactics_offer(game: &Game, player: usize) -> Option { - use crate::combat_listeners::{CombatEventPhase, CombatRoundStart}; - let event = game.events.iter().rev().find(|e| { - matches!( - e.event_type, - PersistentEventType::CombatStart(_) | PersistentEventType::CombatRoundStart(_) - ) - })?; - let round = match &event.event_type { - PersistentEventType::CombatStart(c) => CombatRoundStart::new(c.clone()), - PersistentEventType::CombatRoundStart(r) - if matches!( - r.phase, - CombatEventPhase::AllowTacticsCard - | CombatEventPhase::Loyalty - | CombatEventPhase::Default - ) => - { - if r.phase == CombatEventPhase::Default - && (event.players_used.contains(&player) || event.player.index == player) - { - return None; - } - r.clone() - } - _ => return None, - }; - let c = &round.combat; - if !c.players().contains(&player) - || !game - .player(player) - .can_use_advance(crate::advance::Advance::Tactics) - || crate::combat::get_combat_strength(player, &round).deny_tactics_card - || (player == c.defender() - && c.first_round() - && c.modifiers - .contains(&crate::combat::CombatModifier::TrojanHorse)) - { - return None; - } - let mut options = vec![option("No tactics", EventResponse::SelectHandCards(vec![]))]; - for id in game - .player(player) - .action_cards - .iter() - .filter(|id| **id != 0) - { - let card = game.cache.get_action_card(*id); - let Some(tactics) = &card.tactics_card else { - continue; - }; - // Scout's enemy-card requirement is deliberately provisional; never - // inspect a hidden enemy commitment to build an early offer. - if tactics.name == "Scout" - || crate::tactics_card::can_play_tactics_card(game, player, card, &round) - { - options.push(OptionChoice { - label: tactics.name.clone(), - description: tactics.description.clone(), - response: EventResponse::SelectHandCards(vec![HandCard::ActionCard(*id)]), - }); - } - } - if options.len() == 1 { - return None; - } - let key = tactics_key(game, c); - Some(Offer { - selected: game - .early_choices - .iter() - .find(|s| s.player == player && s.key == key) - .map(|s| s.response.clone()), - key, - title: "Tactics".into(), - options, - }) -} - fn scope(game: &Game, index: usize) -> Option { let name = match &game.events.get(index)?.event_type { PersistentEventType::StatusPhase(phase) => format!("status:{phase:?}"), @@ -191,28 +98,8 @@ fn objective_offers(game: &Game, player: usize) -> Vec { } pub fn prune_objectives(game: &mut Game) { - // Navigation and interrupted/skipped rounds must not leave a plan that can - // attach to a later battle at the same location. - let combat_keys: Vec<_> = game - .events - .iter() - .filter_map(|event| match &event.event_type { - PersistentEventType::CombatStart(c) => Some(tactics_key(game, c)), - PersistentEventType::CombatRoundStart(r) - if matches!( - r.phase, - crate::combat_listeners::CombatEventPhase::AllowTacticsCard - | crate::combat_listeners::CombatEventPhase::Loyalty - | crate::combat_listeners::CombatEventPhase::Default - ) => - { - Some(tactics_key(game, &r.combat)) - } - _ => None, - }) - .collect(); - game.early_choices - .retain(|c| !c.key.ends_with("/tactics") || combat_keys.contains(&c.key)); + // Obsolete combat plans must never consume an ordinary response. + game.early_choices.retain(|c| !c.key.ends_with("/tactics")); let invalid: Vec<_> = game .early_choices .iter() @@ -309,9 +196,6 @@ pub fn offers(game: &Game, player: usize) -> Vec { return vec![]; } let mut result = current_offers(game, player); - if let Some(offer) = tactics_offer(game, player) { - result.push(offer); - } if let Some(offer) = advance_offer(game, player) { result.push(offer); } @@ -469,9 +353,7 @@ fn current_offers(game: &Game, player: usize) -> Vec { } pub fn can_save(game: &Game, player: usize, key: &str, response: Option<&EventResponse>) -> bool { - (player != game.active_player() - || key.ends_with("/tactics") - || (game.events.is_empty() && key.contains(":objective:"))) + (player != game.active_player() || (game.events.is_empty() && key.contains(":objective:"))) && offers(game, player).iter().any(|offer| { offer.key == key && response.is_none_or(|r| offer.options.iter().any(|o| &o.response == r)) @@ -506,14 +388,6 @@ pub fn save( } pub fn expire_current_event(game: &mut Game) { - if let Some(PersistentEventType::CombatRoundStart(r)) = - game.events.last().map(|e| &e.event_type) - { - if r.phase == crate::combat_listeners::CombatEventPhase::Default { - let key = tactics_key(game, &r.combat); - game.early_choices.retain(|c| c.key != key); - } - } if game.events.last().is_some_and(|e| { matches!( e.event_type, @@ -552,31 +426,6 @@ pub fn take_ready(game: &mut Game) -> Option { let player = game.active_player(); let event = game.events.last()?; let handler = event.player.handler.as_ref()?; - if let PersistentEventType::CombatRoundStart(r) = &event.event_type { - if r.phase != crate::combat_listeners::CombatEventPhase::Default - || handler.origin - != crate::events::EventOrigin::Advance(crate::advance::Advance::Tactics) - { - return None; - } - let key = tactics_key(game, &r.combat); - let at = game - .early_choices - .iter() - .position(|c| c.player == player && c.key == key)?; - let valid = match (&handler.request, &game.early_choices[at].response) { - ( - PersistentEventRequest::SelectHandCards(request), - EventResponse::SelectHandCards(cards), - ) => { - request.needed.contains(&(cards.len() as u8)) - && cards.iter().all(|c| request.choices.contains(c)) - } - _ => false, - }; - let choice = game.early_choices.remove(at); - return valid.then_some(choice.response); - } let (index, suffix) = match &event.event_type { PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => { (game.events.len() - 1, "first".into()) diff --git a/server/src/game.rs b/server/src/game.rs index 226f3210..8d3e6287 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -155,6 +155,7 @@ pub struct Game { pub cache: Cache, pub context: GameContext, // transient pub options: GameOptions, + pub asynchronous_combat_from: Option, pub version: u16, // JSON schema version pub state: GameState, pub events: Vec, diff --git a/server/src/game_data.rs b/server/src/game_data.rs index 055c5c6f..74263e56 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -37,6 +37,8 @@ pub struct GameData { #[serde(default)] #[serde(skip_serializing_if = "u16::is_zero")] version: u16, + #[serde(default, skip_serializing_if = "Option::is_none")] + asynchronous_combat_from: Option, #[serde(default)] #[serde(skip_serializing_if = "String::is_empty")] seed: String, @@ -134,7 +136,11 @@ pub struct GameData { pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { let mut game = Game { action_plan: data.action_plan, - early_choices: data.early_choices, + early_choices: data + .early_choices + .into_iter() + .filter(|c| !c.key.ends_with("/tactics")) + .collect(), early_choice_update: data.early_choice_update, uncommitted_calendar: data.uncommitted_calendar, calendar_knowledge: data.calendar_knowledge, @@ -143,6 +149,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game { cache, options: data.options, version: data.version, + asynchronous_combat_from: data.asynchronous_combat_from, state: data.state, players: Vec::new(), map: Map::from_data(data.map), @@ -202,6 +209,7 @@ pub fn data(game: Game) -> GameData { GameData { options: game.options, version: game.version, + asynchronous_combat_from: game.asynchronous_combat_from, state: game.state, events: game.events, action_plan: game.action_plan, @@ -247,6 +255,7 @@ pub fn cloned_data(game: &Game) -> GameData { GameData { options: game.options.clone(), version: game.version, + asynchronous_combat_from: game.asynchronous_combat_from, state: game.state.clone(), events: game.events.clone(), action_plan: game.action_plan.clone(), diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index d6123da1..651093de 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -194,6 +194,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { secrets_stripped: false, seed: setup.seed.clone(), context: GameContext::Play, + asynchronous_combat_from: Some(0), version: JSON_SCHEMA_VERSION, options: GameOptions { legacy_undo: None, diff --git a/server/src/log.rs b/server/src/log.rs index 308f0eb3..ed1fca2e 100644 --- a/server/src/log.rs +++ b/server/src/log.rs @@ -452,6 +452,12 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) { let player = game.active_player(); let origin = action_origin(&item, game.player(player)).clone(); let i = game.log_index; + if current_turn_log(game).actions.len() > i { + // A fresh action replaces the undone future. Redo bypasses this path and + // must retain the recorded format boundary for deterministic history. + let next = crate::game_api::log_length(game).saturating_add(1); + game.asynchronous_combat_from = game.asynchronous_combat_from.map(|from| from.min(next)); + } let l = &mut current_turn_log_mut(game).actions; remove_redo_actions(l, i); l.push(ActionLogAction::new(item, player, origin, active_events)); diff --git a/server/src/replay.rs b/server/src/replay.rs index 274bece4..831d0e79 100644 --- a/server/src/replay.rs +++ b/server/src/replay.rs @@ -12,6 +12,8 @@ pub struct ReplayGameData { #[serde(default)] options: GameOptions, seed: String, + #[serde(default)] + asynchronous_combat_from: Option, log: Vec, log_index: usize, // Look-only information boundaries are intentionally absent from the log. @@ -108,6 +110,10 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { builder = builder.assigned_civilizations(civilizations); } let mut game = setup_game(&builder.build()); + game.asynchronous_combat_from = Some( + data.asynchronous_combat_from + .unwrap_or(actions.len().saturating_add(1)), + ); if data.options.civilization == CivSetupOption::DraftThree { // Draft locks are private and absent from the action log; setup turns // record their final choices. Re-deal before locking to preserve the RNG. @@ -152,6 +158,13 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { "Replay target {to} is not a complete action boundary" )); } + // The returned position is playable, not a promise to execute the discarded + // future. Preserve the recorded switch while reconstructing, then enable new + // battles at the first action beyond this cursor. An open battle keeps its + // own persisted preparation mode, so legacy continuations remain legacy. + game.asynchronous_combat_from = game + .asynchronous_combat_from + .map(|from| from.min(to.saturating_add(1))); for player in data.players { game.players[player.id].settings = player.settings; } diff --git a/server/src/undo.rs b/server/src/undo.rs index f8632759..8b4636e9 100644 --- a/server/src/undo.rs +++ b/server/src/undo.rs @@ -5,7 +5,7 @@ use crate::movement::execute_movement_action; use json_patch::{PatchOperation, patch}; use serde_json::Value; -const IGNORE_PATHS: [&str; 7] = [ +const IGNORE_PATHS: [&str; 8] = [ "/calendar_knowledge", "/log/", "/log_index", @@ -13,6 +13,10 @@ const IGNORE_PATHS: [&str; 7] = [ "/early_choice_update", "/action_plan", "/time_increments", + // A format boundary describes retained history, not reversible gameplay. + // Once a new branch replaces old actions, undo must not restore their switch + // point and accidentally make redo execute a newly recorded battle as legacy. + "/asynchronous_combat_from", ]; pub(crate) fn clean_patch(mut patch: Vec) -> Vec { diff --git a/server/src/web_view.rs b/server/src/web_view.rs index 502874e6..3993dce0 100644 --- a/server/src/web_view.rs +++ b/server/src/web_view.rs @@ -344,17 +344,7 @@ pub fn view(game: &Game, seat: Option) -> Value { }).collect::>(); let early_offers: Vec<_> = crate::early_choices::offers(game, seat) .into_iter() - // Combat queues use the same waiting-player surface as other early choices. - // Never offer tactics before this player's combat-start choices (notably - // Steel Weapons) have finished. Keep engine queue authorization separate. .filter(|_| seat != active || game.events.is_empty()) - .filter(|o| { - !o.key.ends_with("/tactics") - || !game.events.iter().any(|event| { - matches!(event.event_type, PersistentEventType::CombatStart(_)) - && !event.players_used.contains(&seat) - }) - }) .collect(); let early_advance = early_offers.iter().find(|o| o.key.ends_with("/advance")); let early_advance_choices: Vec<_> = early_advance diff --git a/server/src/web_view/combat_summary.rs b/server/src/web_view/combat_summary.rs index 038cdf37..81f65e4b 100644 --- a/server/src/web_view/combat_summary.rs +++ b/server/src/web_view/combat_summary.rs @@ -51,9 +51,18 @@ pub(super) fn describe(game: &Game) -> Value { activated.modifiers.push(modifier); let bonus = strength(game, &activated, player).extra_combat_value - s.extra_combat_value; - let pending = game.events.iter().any(|event| { - matches!(event.event_type, PersistentEventType::CombatStart(_)) - && !event.players_used.contains(&player) + let pending = game.events.iter().any(|event| match &event.event_type { + PersistentEventType::CombatStart(_) => !event.players_used.contains(&player), + PersistentEventType::CombatRoundStart(round) => { + use crate::combat_listeners::PreparationStep; + if player == c.attacker() { + round.preparation == Some(PreparationStep::AttackerAbilities) + } else { + round.preparation.is_some() + && round.preparation != Some(PreparationStep::DefenderTactics) + } + } + _ => false, }); inactive.push(if pending { format!("Steel Weapons pending: +{bonus} value if activated") diff --git a/server/tests/combat_preparation_tests.rs b/server/tests/combat_preparation_tests.rs new file mode 100644 index 00000000..ba982478 --- /dev/null +++ b/server/tests/combat_preparation_tests.rs @@ -0,0 +1,401 @@ +use serde_json::{Value, json}; +use server::{ + board_history, + cache::Cache, + early_choices, + game::{Game, GameContext}, + game_data::GameData, +}; + +fn load(value: Value) -> Game { + let data: GameData = serde_json::from_value(value).unwrap(); + let cache = Cache::new(&data.options); + Game::from_data(data, cache, GameContext::Play) +} +fn data(game: &Game) -> Value { + serde_json::to_value(game.cloned_data()).unwrap() +} +fn play(game: Game, player: usize, action: Value) -> Game { + board_history::execute(game, serde_json::from_value(action).unwrap(), player).unwrap() +} +fn battle() -> Game { + let mut v: Value = + serde_json::from_str(include_str!("test_games/tactics_cards/peltasts.json")).unwrap(); + for p in [0, 1] { + v["players"][p]["advances"] + .as_array_mut() + .unwrap() + .push(json!("SteelWeapons")); + } + v["players"][0]["action_cards"] = json!([3, 6, 11]); + v["players"][1]["action_cards"] = json!([4, 7, 23]); + play( + load(v), + 0, + json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}), + ) +} +fn steel(g: Game, p: usize) -> Game { + play(g, p, json!({"Response":{"Payment":[{"ore":1}]}})) +} +fn tactics(g: Game, p: usize, card: Option) -> Game { + let cards: Vec<_> = card + .into_iter() + .map(|id| json!({"ActionCard":id})) + .collect(); + play(g, p, json!({"Response":{"SelectHandCards":cards}})) +} +fn request(g: &Game) -> Value { + serde_json::to_value(&g.current_event_handler().unwrap().request).unwrap() +} +#[test] +fn attacker_finishes_before_defender_and_reload_keeps_hidden_card() { + let g = battle(); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("Payment").is_some()); + assert!( + early_choices::offers(&g, 0) + .iter() + .all(|o| !o.key.ends_with("/tactics")) + ); + let g = steel(load(data(&g)), 0); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectHandCards").is_some()); + let g = tactics(load(data(&g)), 0, Some(3)); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("Payment").is_some()); + assert!(!g.player(0).action_cards.contains(&3)); + let hidden = data(&server::game_api::strip_secret(g.clone(), Some(1))); + assert_eq!( + hidden["events"][0]["event_type"]["CombatRoundStart"]["attacker_strength"]["tactics_card"], + json!(0) + ); + assert!( + !hidden["action_cards_discarded"] + .as_array() + .is_some_and(|cards| cards.contains(&json!(3))) + ); + let g = steel(load(data(&g)), 1); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("SelectHandCards").is_some()); + let g = tactics(load(data(&g)), 1, Some(4)); + assert!(!g.player(1).action_cards.contains(&4)); +} +#[test] +fn skipping_is_an_ordinary_committed_response() { + let g = tactics(steel(battle(), 0), 0, None); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("Payment").is_some()); + assert!(g.player(0).action_cards.contains(&3)); + let _ = tactics(steel(g, 1), 1, None); +} +#[test] +fn obsolete_combat_plans_are_discarded_but_other_plans_survive_load() { + let mut v = data(&battle()); + v["early_choices"] = json!([ + {"player":0,"key":"old/tactics","response":{"SelectHandCards":[]}}, + {"player":1,"key":"1:status/advance","response":{"SelectAdvance":"Fishing"}} + ]); + let g = load(v); + assert_eq!(g.early_choices.len(), 1); + assert_eq!(g.early_choices[0].key, "1:status/advance"); + assert!(!early_choices::can_save(&g, 0, "old/tactics", None)); +} +#[test] +fn legacy_battle_continuation_keeps_both_payments_before_tactics() { + let mut v = data(&battle()); + let round = v["events"][0]["event_type"]["CombatRoundStart"].clone(); + let mut combat = round["combat"].clone(); + combat + .as_object_mut() + .unwrap() + .remove("asynchronous_preparation"); + v["events"][0]["event_type"] = json!({"CombatStart":combat}); + let g = steel(load(v), 0); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("Payment").is_some()); + let g = steel(g, 1); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectHandCards").is_some()); +} + +fn fixture(name: &str) -> Value { + serde_json::from_str(&std::fs::read_to_string(format!("tests/test_games/{name}.json")).unwrap()) + .unwrap() +} +fn attack(v: Value) -> Game { + play( + load(v), + 0, + json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}), + ) +} +#[test] +fn no_steel_and_free_metallurgy_do_not_add_a_payment_step() { + for metallurgy in [false, true] { + let mut v = fixture("tactics_cards/peltasts"); + v["players"][1]["action_cards"] = json!([4]); + if metallurgy { + v["players"][0]["advances"] + .as_array_mut() + .unwrap() + .extend([json!("SteelWeapons"), json!("Metallurgy")]); + } + let g = attack(v); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectHandCards").is_some()); + if metallurgy { + let round = &data(&g)["events"][0]["event_type"]["CombatRoundStart"]; + assert!( + round["combat"]["modifiers"] + .as_array() + .unwrap() + .contains(&json!("SteelWeaponsAttacker")) + ); + } + let g = tactics(g, 0, None); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("SelectHandCards").is_some()); + } +} +#[test] +fn siegecraft_stays_before_attacker_card_and_defender_steel() { + let mut v = fixture("tactics_cards/peltasts"); + v["players"][0]["advances"] + .as_array_mut() + .unwrap() + .extend([json!("SteelWeapons"), json!("Siegecraft")]); + v["players"][1]["advances"] + .as_array_mut() + .unwrap() + .push(json!("SteelWeapons")); + v["players"][1]["cities"][0]["city_pieces"] = json!({"fortress":1}); + let g = steel(attack(v), 0); + assert_eq!(g.active_player(), 0); + assert_eq!(request(&g)["Payment"].as_array().unwrap().len(), 2); + let g = play( + load(data(&g)), + 0, + json!({"Response":{"Payment":[{"wood":2},{"ore":2}]}}), + ); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectHandCards").is_some()); + let g = tactics(g, 0, None); + assert_eq!(g.active_player(), 1); + assert_eq!(request(&g)["Payment"].as_array().unwrap().len(), 1); +} +#[test] +fn naval_steel_is_not_offered_and_martyr_still_requires_sacrifice_after_both_cards() { + let mut v = fixture("tactics_cards/martyr"); + for p in [0, 1] { + v["players"][p]["advances"] + .as_array_mut() + .unwrap() + .push(json!("SteelWeapons")); + } + let g = play( + load(v), + 0, + json!({"Movement":{"Move":{"units":[7,8],"destination":"D2","payment":{}}}}), + ); + assert!(request(&g).get("SelectHandCards").is_some()); + let g = tactics(g, 0, Some(6)); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("SelectHandCards").is_some()); + let g = tactics(g, 1, Some(24)); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectUnits").is_some()); + let g = play(load(data(&g)), 0, json!({"Response":{"SelectUnits":[7]}})); + assert!(request(&g).get("SelectUnits").is_some()); + let _ = play(g, 0, json!({"Response":{"SelectUnits":[2]}})); +} +#[test] +fn replay_format_boundary_is_explicit_and_absent_in_historical_records() { + let g = server::game_api::init( + 2, + "combat-replay-format".into(), + server::game::GameOptions::default(), + ); + let player = g.active_player(); + let g = play(g, player, json!({"Playing":"EndTurn"})); + let mut v = data(&g); + let replayed = + server::replay::replay(serde_json::from_value(v.clone()).unwrap(), None).unwrap(); + assert_eq!(replayed.asynchronous_combat_from, Some(0)); + v.as_object_mut() + .unwrap() + .remove("asynchronous_combat_from"); + let legacy = server::replay::replay(serde_json::from_value(v).unwrap(), None).unwrap(); + assert!(legacy.asynchronous_combat_from.unwrap() > server::game_api::log_length(&legacy)); +} + +#[test] +fn own_payment_undo_redo_is_deterministic_but_committed_tactics_cannot_be_revised() { + let start = battle(); + let paid = steel(start, 0); + assert!(paid.can_undo()); + let before = data(&paid); + let undone = play(paid, 0, json!("Undo")); + assert_eq!(undone.active_player(), 0); + assert!(request(&undone).get("Payment").is_some()); + let redone = play(undone, 0, json!("Redo")); + for field in ["players", "events", "rng", "asynchronous_combat_from"] { + assert_eq!(data(&redone)[field], before[field], "{field}"); + } + let committed = tactics(redone, 0, Some(3)); + assert!(!committed.can_undo()); + let rejected = server::action::try_execute_action( + committed, + serde_json::from_value(json!({"Response":{"SelectHandCards":[]}})).unwrap(), + 0, + ); + assert!(rejected.is_err()); +} + +#[test] +fn later_rounds_do_not_repeat_battle_start_payments() { + let mut g = battle(); + g.dice_roll_outcomes = vec![0; 40]; + let g = tactics(steel(tactics(steel(g, 0), 0, None), 1), 1, None); + assert!(request(&g).get("BoolRequest").is_some(), "{}", request(&g)); + let g = play(g, 0, json!({"Response":{"Bool":false}})); + assert_eq!(g.active_player(), 0); + assert!(request(&g).get("SelectHandCards").is_some()); + let round = &data(&g)["events"][0]["event_type"]["CombatRoundStart"]; + assert_eq!(round["combat"]["stats"]["round"], json!(2)); + assert_eq!(round["preparation"], Value::Null); + assert_eq!(round["combat"]["modifiers"].as_array().unwrap().len(), 2); + let g = tactics(g, 0, None); + assert_eq!(g.active_player(), 1); + assert!(request(&g).get("SelectHandCards").is_some()); +} + +fn historical_replay(to: usize) -> Game { + server::replay::replay( + serde_json::from_str(include_str!("fixtures/legacy_combat_history.json")).unwrap(), + Some(to), + ) + .unwrap() +} +#[test] +fn historical_combat_replay_branches_enable_new_battles() { + // Generated from a seeded game using legacy sequencing, not a mutated board + // fixture. Includes completed battles and an open human-vs-human battle. + let open = historical_replay(217); + let expected: Value = + serde_json::from_str(include_str!("fixtures/legacy_combat_history.expected.json")).unwrap(); + for (key, value) in expected.as_object().unwrap() { + assert_eq!(&data(&open)[key], value, "0.4.153 compatibility: {key}"); + } + let round = &data(&open)["events"][0]["event_type"]["CombatRoundStart"]; + assert_eq!(round["combat"]["asynchronous_preparation"], Value::Null); + assert_eq!(open.asynchronous_combat_from, Some(218)); + let before = historical_replay(216); + assert_eq!(before.asynchronous_combat_from, Some(217)); + let next = play( + before, + 0, + json!({"Movement":{"Move":{"destination":"E5","units":[3]}}}), + ); + let round = &data(&next)["events"][0]["event_type"]["CombatRoundStart"]; + assert_eq!(round["combat"]["asynchronous_preparation"], json!(true)); + // The newly recorded switch survives replay of the branched history. + let again = server::replay::replay(serde_json::from_value(data(&next)).unwrap(), None).unwrap(); + assert_eq!(data(&again)["events"], data(&next)["events"]); + let continued = tactics(open, 1, None); + assert!( + continued.events.is_empty(), + "legacy battle finishes normally" + ); + + // Full replay of a legacy save ending before the next battle is playable too. + let mut saved: Value = + serde_json::from_str(include_str!("fixtures/legacy_combat_history.json")).unwrap(); + let turn = saved["log"].as_array_mut().unwrap().last_mut().unwrap()["rounds"] + .as_array_mut() + .unwrap() + .last_mut() + .unwrap()["turns"] + .as_array_mut() + .unwrap() + .last_mut() + .unwrap(); + turn["actions"].as_array_mut().unwrap().pop(); + saved["log_index"] = json!(saved["log_index"].as_u64().unwrap() - 1); + let full = server::replay::replay(serde_json::from_value(saved).unwrap(), None).unwrap(); + let next = play( + full, + 0, + json!({"Movement":{"Move":{"destination":"E5","units":[3]}}}), + ); + assert_eq!( + data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"], + json!(true) + ); + + // A branch earlier than the original history's switch cannot inherit it. + let earlier = historical_replay(167); + let next = play( + earlier, + 1, + json!({"Movement":{"Move":{"destination":"F7","units":[1]}}}), + ); + assert_eq!( + data(&next)["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"], + json!(true) + ); +} + +#[test] +fn undo_redo_preserves_history_boundary_but_replacing_future_clamps_it() { + let mut g = server::game_api::init(2, "combat-undo-boundary".into(), Default::default()); + g.asynchronous_combat_from = Some(100); + let player = g.active_player(); + let action = json!({"Playing":{"Advance":{"advance":"Storage","payment":{"food":2}}}}); + let paid = play(g, player, action.clone()); + let undone = play(paid, player, json!("Undo")); + assert_eq!(undone.asynchronous_combat_from, Some(100)); + let redone = play(undone, player, json!("Redo")); + assert_eq!(redone.asynchronous_combat_from, Some(100)); + let undone = play(redone, player, json!("Undo")); + let next = server::game_api::log_length(&undone) + 1; + let branched = play(undone, player, action); + assert_eq!(branched.asynchronous_combat_from, Some(next)); + let undone = play(branched, player, json!("Undo")); + assert_eq!(undone.asynchronous_combat_from, Some(next)); + let redone = play(undone, player, json!("Redo")); + assert_eq!(redone.asynchronous_combat_from, Some(next)); +} + +#[test] +fn undo_redo_of_a_branched_battle_keeps_new_preparation() { + let mut v = fixture("tactics_cards/peltasts"); + v["asynchronous_combat_from"] = json!(100); + for p in [0, 1] { + v["players"][p]["advances"] + .as_array_mut() + .unwrap() + .push(json!("SteelWeapons")); + } + let action = json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}); + let legacy = play(load(v), 0, action.clone()); + assert!( + data(&legacy)["events"][0]["event_type"] + .get("CombatStart") + .is_some() + ); + let undone = play(legacy, 0, json!("Undo")); + let branch = play(undone, 0, action); + let expected = data(&branch); + assert_eq!( + expected["events"][0]["event_type"]["CombatRoundStart"]["combat"]["asynchronous_preparation"], + json!(true) + ); + let undone = play(branch, 0, json!("Undo")); + let redone = play(undone, 0, json!("Redo")); + assert_eq!(data(&redone)["events"], expected["events"]); + assert_eq!( + data(&redone)["asynchronous_combat_from"], + expected["asynchronous_combat_from"] + ); +} diff --git a/server/tests/common/mod.rs b/server/tests/common/mod.rs index dca2ac8e..bb2b3b25 100644 --- a/server/tests/common/mod.rs +++ b/server/tests/common/mod.rs @@ -140,6 +140,12 @@ fn clean_json(expected: &str) -> String { // those records intact and compare all gameplay/log data except this new // redundant arithmetic, covered explicitly by hit-reporting regressions. let mut value: serde_json::Value = serde_json::from_str(expected).unwrap(); + if value["asynchronous_combat_from"] == serde_json::json!(usize::MAX) { + value + .as_object_mut() + .unwrap() + .remove("asynchronous_combat_from"); + } // Only public action-log items qualify, never arbitrary arrays or game state. if let Some(ages) = value .get_mut("log") @@ -463,7 +469,12 @@ pub fn load_game(path: &GamePath) -> Game { let game_data: GameData = serde_json::from_str(&read_game_str(path)) .unwrap_or_else(|e| panic!("the game file should be deserializable {path}: {e}",)); let cache = Cache::new(&game_data.options); - let game = Game::from_data(game_data, cache, GameContext::Play); + let mut game = Game::from_data(game_data, cache, GameContext::Play); + // These golden histories record the legacy battle response order. Exercise + // that compatibility path; new sequencing has dedicated preparation tests. + if game.asynchronous_combat_from.is_none() { + game.asynchronous_combat_from = Some(usize::MAX); + } if update_expected() { write_result(&to_json(&game), path); } diff --git a/server/tests/fixtures/legacy_combat_history.expected.json b/server/tests/fixtures/legacy_combat_history.expected.json new file mode 100644 index 00000000..a70ad525 --- /dev/null +++ b/server/tests/fixtures/legacy_combat_history.expected.json @@ -0,0 +1,483 @@ +{ + "players": [ + { + "id": 0, + "resources": { + "wood": 4, + "mood_tokens": 3, + "culture_tokens": 2 + }, + "resource_limit": { + "food": 2, + "wood": 7, + "ore": 7, + "ideas": 7, + "gold": 7 + }, + "cities": [ + { + "city_pieces": { + "market": 0 + }, + "mood_state": "Angry", + "position": "D2" + }, + { + "city_pieces": { + "market": 1 + }, + "mood_state": "Neutral", + "position": "D4" + } + ], + "units": [ + { + "position": "D5", + "unit_type": "Elephant", + "movement_restrictions": [ + "Battle" + ], + "id": 3 + }, + { + "position": "E2", + "unit_type": "Infantry", + "id": 5 + } + ], + "civilization": "Phoenicia", + "available_leaders": [ + "Ithobaal", + "Hiram", + "Pygmalion" + ], + "advances": [ + "Bartering", + "Currency", + "Farming", + "Fishing", + "FreeEducation", + "Husbandry", + "Irrigation", + "Mining", + "Myths", + "Navigation", + "Priesthood", + "Roads", + "StateReligion", + "Tactics", + "Writing" + ], + "incident_tokens": 1, + "next_unit_id": 6 + }, + { + "id": 1, + "resources": { + "wood": 5, + "culture_tokens": 1 + }, + "resource_limit": { + "food": 7, + "wood": 7, + "ore": 7, + "ideas": 7, + "gold": 7 + }, + "cities": [ + { + "mood_state": "Angry", + "position": "D7" + }, + { + "mood_state": "Happy", + "position": "E5" + }, + { + "mood_state": "Neutral", + "position": "F7" + } + ], + "units": [ + { + "position": "E5", + "unit_type": "Settler", + "id": 3 + }, + { + "position": "E5", + "unit_type": "Infantry", + "id": 4 + }, + { + "position": "D7", + "unit_type": "Settler", + "id": 5 + } + ], + "civilization": "India", + "available_leaders": [ + "SriGupta", + "Ashoka", + "Akbar" + ], + "advances": [ + "Arts", + "Cartography", + "Engineering", + "Farming", + "Fishing", + "Math", + "Mining", + "Navigation", + "Roads", + "Sanitation", + "Storage", + "Tactics", + "Writing" + ], + "incident_tokens": 2, + "completed_objectives": [ + { + "card": 13, + "name": "Wood Supplies" + }, + { + "card": 16, + "name": "Goal Focused" + } + ], + "wonder_cards": [ + "Colosseum" + ], + "action_cards": [ + 33, + 9, + 30, + 12 + ], + "objective_cards": [ + 17, + 15, + 19, + 4 + ], + "next_unit_id": 6 + }, + { + "id": 2, + "cities": [ + { + "mood_state": "Neutral", + "position": "B2" + }, + { + "mood_state": "Angry", + "position": "B3" + } + ], + "units": [ + { + "position": "E8", + "unit_type": "Infantry", + "id": 1 + }, + { + "position": "C3", + "unit_type": "Elephant", + "id": 2 + }, + { + "position": "C3", + "unit_type": "Infantry", + "id": 4 + }, + { + "position": "C3", + "unit_type": "Infantry", + "id": 5 + }, + { + "position": "B2", + "unit_type": "Infantry", + "id": 6 + }, + { + "position": "B3", + "unit_type": "Infantry", + "id": 7 + } + ], + "civilization": "Barbarians", + "next_unit_id": 8 + }, + { + "id": 3, + "civilization": "Pirates", + "next_unit_id": 0 + } + ], + "events": [ + { + "event_type": { + "CombatRoundStart": { + "combat": { + "attackers": [ + 3 + ], + "retreat": "CanRetreat", + "stats": { + "round": 1, + "battleground": "City", + "attacker": { + "position": "D5", + "player": 0, + "present": { + "elephants": 1 + } + }, + "defender": { + "position": "E5", + "player": 1, + "present": { + "settlers": 1, + "infantry": 1 + } + }, + "city_mood": "Happy" + } + }, + "attacker_strength": {}, + "defender_strength": {} + } + }, + "players_used": [ + 0 + ], + "player": 1, + "last_priority_used": 0, + "handler": { + "priority": 0, + "request": { + "SelectHandCards": { + "choices": [ + { + "ActionCard": 9 + }, + { + "ActionCard": 12 + }, + { + "ActionCard": 30 + }, + { + "ActionCard": 33 + } + ], + "needed": { + "start": 0, + "end": 1 + }, + "description": "Play Tactics Card" + } + }, + "origin": { + "Advance": "Tactics" + } + } + } + ], + "rng": "222724077733091596346276912534125779896", + "map": { + "tiles": [ + [ + "A3", + "Water" + ], + [ + "A5", + "Fertile" + ], + [ + "A7", + "Unexplored" + ], + [ + "B2", + "Fertile" + ], + [ + "B3", + "Mountain" + ], + [ + "B4", + "Fertile" + ], + [ + "B5", + "Forest" + ], + [ + "B6", + "Unexplored" + ], + [ + "B7", + "Unexplored" + ], + [ + "C2", + "Forest" + ], + [ + "C3", + "Barren" + ], + [ + "C4", + "Water" + ], + [ + "C5", + "Fertile" + ], + [ + "C6", + "Forest" + ], + [ + "C7", + "Unexplored" + ], + [ + "C8", + "Mountain" + ], + [ + "D1", + "Water" + ], + [ + "D2", + "Fertile" + ], + [ + "D3", + "Mountain" + ], + [ + "D4", + "Mountain" + ], + [ + "D5", + "Fertile" + ], + [ + "D6", + "Water" + ], + [ + "D7", + "Fertile" + ], + [ + "D8", + "Barren" + ], + [ + "E2", + "Mountain" + ], + [ + "E3", + "Forest" + ], + [ + "E4", + "Fertile" + ], + [ + "E5", + "Fertile" + ], + [ + "E6", + "Barren" + ], + [ + "E7", + { + "Exhausted": "Fertile" + } + ], + [ + "E8", + "Forest" + ], + [ + "F2", + "Water" + ], + [ + "F3", + "Fertile" + ], + [ + "F4", + "Forest" + ], + [ + "F5", + "Forest" + ], + [ + "F6", + "Barren" + ], + [ + "F7", + "Fertile" + ], + [ + "G3", + "Water" + ], + [ + "G5", + "Water" + ], + [ + "G7", + "Water" + ] + ], + "unexplored_blocks": [ + { + "position": { + "top_tile": "B6", + "rotation": 0 + }, + "block": { + "terrain": [ + "Water", + "Fertile", + "Fertile", + "Barren" + ] + } + } + ] + }, + "state": { + "Movement": { + "movement_actions_left": 2, + "moved_units": [ + 3 + ] + } + }, + "actions_left": 2, + "current_player_index": 0 +} diff --git a/server/tests/fixtures/legacy_combat_history.json b/server/tests/fixtures/legacy_combat_history.json new file mode 100644 index 00000000..e5f848af --- /dev/null +++ b/server/tests/fixtures/legacy_combat_history.json @@ -0,0 +1,3015 @@ +{ + "seed": "historical-combat-0", + "log": [ + { + "age": 0, + "rounds": [ + { + "round": 0, + "turns": [ + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + } + ], + "turn_type": { + "Setup": { + "civilization": "Phoenicia", + "player": 0 + } + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + } + ], + "turn_type": { + "Setup": { + "civilization": "India", + "player": 1 + } + } + } + ] + } + ] + }, + { + "age": 1, + "rounds": [ + { + "round": 1, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E7", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Sanitation", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "F6", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Advance": { + "advance": "Bartering", + "payment": { + "food": 2 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 14 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + } + ] + }, + { + "round": 2, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + }, + { + "pile": { + "food": 1 + }, + "position": "E7", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "F5", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Arts", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "C3", + "units": [ + 0 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Fishing", + "payment": { + "food": 2 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "B3", + "units": [ + 0 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + } + ] + }, + { + "round": 3, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "E8", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "E5", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "D5", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "E2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Irrigation", + "payment": { + "gold": 2 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "B4", + "units": [ + 0 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ExploreResolution": 0 + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "turn_type": { + "StatusPhase": "CompleteObjectives" + } + }, + { + "actions": [ + { + "action": { + "Response": { + "SelectAdvance": "Engineering" + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [ + "B2" + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectUnitType": "Elephant" + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectAdvance": "Navigation" + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "FreeAdvance" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "DrawCards" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "RazeSize1City" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "ChangeGovernmentType" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Response": { + "SelectPlayer": 0 + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DetermineFirstPlayer" + } + } + ] + } + ] + }, + { + "age": 2, + "rounds": [ + { + "round": 1, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "B3", + "units": [ + 0 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "FoundCity": { + "settler": 0 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ActionCard": 10 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E5", + "units": [ + 0 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "FoundCity": { + "settler": 0 + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "IncreaseHappiness": { + "action_type": "IncreaseHappiness", + "happiness_increases": [ + [ + "E5", + 1 + ] + ], + "payment": { + "mood_tokens": 1 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 2, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Recruit": { + "city_position": "B3", + "payment": { + "food": 1, + "ore": 1 + }, + "units": { + "infantry": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "E2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Construct": { + "city_piece": "Market", + "city_position": "D2", + "payment": { + "gold": 1, + "ore": 1, + "wood": 1 + }, + "port_position": null + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "C8", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "E8", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + }, + { + "pile": { + "ore": 1 + }, + "position": "C8", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "D7", + "payment": { + "food": 1, + "ore": 1 + }, + "units": { + "infantry": 1 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 3, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "B3", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "A3", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "B3", + "payment": { + "food": 1, + "gold": 1 + }, + "units": { + "infantry": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Custom": { + "action": "EndDiplomaticRelations" + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "C8", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "E5", + "collections": [ + { + "pile": { + "wood": 1 + }, + "position": "F4", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "F5", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "turn_type": { + "StatusPhase": "CompleteObjectives" + } + }, + { + "actions": [ + { + "action": { + "Response": { + "SelectAdvance": "Myths" + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectAdvance": "Writing" + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "FreeAdvance" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DrawCards" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "RazeSize1City" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "ChangeGovernmentType" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + }, + { + "action": { + "Response": { + "SelectPlayer": 1 + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DetermineFirstPlayer" + } + } + ] + } + ] + }, + { + "age": 3, + "rounds": [ + { + "round": 1, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "wood": 1 + }, + "position": "E8", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "E5", + "collections": [ + { + "pile": { + "wood": 1 + }, + "position": "F4", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "F5", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "ActionCard": 32 + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 16 + }, + { + "ObjectiveCard": 37 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "E2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "B3", + "collections": [ + { + "pile": { + "ore": 1 + }, + "position": "B3", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "IncreaseHappiness": { + "action_type": "IncreaseHappiness", + "happiness_increases": [ + [ + "D2", + 2 + ] + ], + "payment": { + "mood_tokens": 4 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ActionCard": 6 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + } + ] + }, + { + "round": 2, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Storage", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "E5", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "E5", + "times": 1 + }, + { + "pile": { + "food": 1 + }, + "position": "D5", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + }, + { + "pile": { + "ore": 1 + }, + "position": "E2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "D2", + "payment": { + "food": 1, + "gold": 1 + }, + "units": { + "elephants": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + }, + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + } + ] + }, + { + "round": 3, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Advance": { + "advance": "Tactics", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [ + "E8" + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "ActionCard": 123 + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "E7", + "units": [ + 1 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Advance": { + "advance": "StateReligion", + "payment": { + "food": 1, + "gold": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "ActionCard": 121 + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 5 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 13 + } + ] + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "CompleteObjectives" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Response": { + "SelectAdvance": "Fishing" + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectAdvance": "Roads" + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "FreeAdvance" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "DrawCards" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "RazeSize1City" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "ChangeGovernmentType" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Response": { + "SelectPlayer": 0 + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DetermineFirstPlayer" + } + } + ] + } + ] + }, + { + "age": 4, + "rounds": [ + { + "round": 1, + "turns": [ + { + "actions": [ + { + "action": { + "Playing": { + "Advance": { + "advance": "Currency", + "payment": { + "ideas": 2 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Priesthood", + "payment": { + "food": 1, + "gold": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [ + "B2" + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [ + "C3" + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 36 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Recruit": { + "city_position": "E5", + "payment": { + "mood_tokens": 1 + }, + "units": { + "settlers": 1 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "D4", + "units": [ + 2 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "ExploreResolution": 0 + } + }, + "player": 1 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "ActionCard": 39 + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectAdvance": "Roads" + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectAdvance": "Tactics" + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 2, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "D4", + "payment": { + "food": 1, + "ore": 1 + }, + "units": [ + 3, + 4 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "FoundCity": { + "settler": 4 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "D2", + "payment": { + "gold": 1, + "ore": 1 + }, + "units": { + "infantry": 1 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "ActionCard": 11 + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ActionCard": 119 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "F6", + "units": [ + 1 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "E5", + "payment": { + "food": 1, + "mood_tokens": 1, + "ore": 1 + }, + "units": { + "infantry": 1, + "settlers": 1 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D7", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "D7", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 3, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E3", + "units": [ + 5 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Husbandry", + "payment": { + "ideas": 2 + } + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "D2", + "collections": [ + { + "pile": { + "wood": 1 + }, + "position": "C2", + "times": 1 + } + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "F7", + "units": [ + 1 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ActionCard": 41 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "E6", + "payment": { + "food": 1, + "ore": 1 + }, + "units": [ + 3, + 4 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "E5", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "E5", + "times": 1 + }, + { + "pile": { + "food": 1 + }, + "position": "D5", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + }, + { + "actions": [ + { + "action": { + "Response": { + "SelectHandCards": [ + { + "ObjectiveCard": 16 + } + ] + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "CompleteObjectives" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + }, + { + "action": { + "Response": { + "SelectAdvance": "FreeEducation" + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectAdvance": "Math" + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "FreeAdvance" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DrawCards" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "SelectPositions": [] + } + }, + "player": 1 + } + ], + "turn_type": { + "StatusPhase": "RazeSize1City" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "ChangeGovernmentType" + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 0 + }, + { + "action": { + "Response": { + "SelectPlayer": 0 + } + }, + "player": 0 + } + ], + "turn_type": { + "StatusPhase": "DetermineFirstPlayer" + } + } + ] + } + ] + }, + { + "age": 5, + "rounds": [ + { + "round": 1, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E2", + "units": [ + 5 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 0 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "D2", + "payment": { + "gold": 1, + "ore": 1 + }, + "units": [ + 5 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 0 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "C5", + "units": [ + 3 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "ActionCard": 28 + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Custom": { + "action": "Bartering" + } + } + }, + "player": 0 + }, + { + "action": { + "Response": { + "ResourceReward": { + "gold": 1 + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": "StartTurn", + "player": 1 + }, + { + "action": { + "Playing": { + "Collect": { + "action_type": "Collect", + "city_position": "E5", + "collections": [ + { + "pile": { + "food": 1 + }, + "position": "E5", + "times": 1 + }, + { + "pile": { + "food": 1 + }, + "position": "D5", + "times": 1 + } + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "E5", + "units": [ + 3, + 4 + ] + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "ActionCard": 15 + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "InfluenceCultureAttempt": { + "action_type": { + "Special": { + "Modifier": "ArtsInfluenceCultureAttempt" + } + }, + "selected_structure": { + "position": "F7", + "structure": "CityCenter" + } + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 2, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E2", + "units": [ + 5 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 0 + }, + { + "action": { + "Movement": { + "Move": { + "destination": "D5", + "units": [ + 3 + ] + } + } + }, + "player": 0 + }, + { + "action": { + "Movement": "Stop" + }, + "player": 0 + }, + { + "action": { + "Playing": { + "Construct": { + "city_piece": "Market", + "city_position": "D4", + "payment": { + "gold": 2, + "wood": 1 + }, + "port_position": null + } + } + }, + "player": 0 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + }, + { + "actions": [ + { + "action": { + "Playing": { + "Advance": { + "advance": "Cartography", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "SelectPositions": [ + "E7" + ] + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "ResourceReward": { + "mood_tokens": 1 + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Advance": { + "advance": "Navigation", + "payment": { + "food": 2 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "Recruit": { + "city_position": "D7", + "payment": { + "mood_tokens": 1 + }, + "units": { + "settlers": 1 + } + } + } + }, + "player": 1 + }, + { + "action": { + "Playing": { + "InfluenceCultureAttempt": { + "action_type": { + "Special": { + "Modifier": "ArtsInfluenceCultureAttempt" + } + }, + "selected_structure": { + "position": "D4", + "structure": { + "Building": "Market" + } + } + } + } + }, + "player": 1 + }, + { + "action": { + "Response": { + "Payment": [ + { + "culture_tokens": 1 + } + ] + } + }, + "player": 1 + }, + { + "action": { + "Playing": "EndTurn" + }, + "player": 1 + } + ], + "turn_type": { + "Player": 1 + } + } + ] + }, + { + "round": 3, + "turns": [ + { + "actions": [ + { + "action": { + "Movement": { + "Move": { + "destination": "E5", + "units": [ + 3 + ] + } + } + }, + "player": 0 + } + ], + "turn_type": { + "Player": 0 + } + } + ] + } + ] + } + ], + "log_index": 1, + "players": [ + { + "id": 0, + "civilization": "Phoenicia" + }, + { + "id": 1, + "civilization": "India" + }, + { + "id": 2, + "civilization": "Barbarians" + }, + { + "id": 3, + "civilization": "Pirates" + } + ] +} diff --git a/server/tests/fixtures/legacy_combat_history.md b/server/tests/fixtures/legacy_combat_history.md new file mode 100644 index 00000000..e8c479ea --- /dev/null +++ b/server/tests/fixtures/legacy_combat_history.md @@ -0,0 +1,17 @@ +# Legacy combat replay regression + +Synthetic seeded game (`historical-combat-0`), generated locally with legal AI +choices and legacy combat sequencing; no production game or player data. +`legacy_combat_history.json` contains only replay input: setup metadata and 217 +ordinary recorded actions. It includes completed battles and a pending battle at +217. Cursor 167 precedes another battle; cursor 216 precedes the final battle. + +The history was independently replayed with the frozen, downloaded production +engine **0.4.153** (tarball SHA-256 +`0f65a03b0610cc8b52b2ce13e12f505bddfb2d680014bf0c5846844e816f9177`). +`legacy_combat_history.expected.json` records its resulting +players, events, RNG, board and turn state. Keep these fixtures frozen rather than +regenerating them with normal golden game snapshots. Tests must reconstruct the +legacy position exactly, finish an open legacy battle normally, and use new +preparation when starting a battle from either a full-save or partial-history +branch. Explicit switches and undo/redo have separate regressions. diff --git a/server/tests/scouts_tests.rs b/server/tests/scouts_tests.rs index d57bcc13..7e708204 100644 --- a/server/tests/scouts_tests.rs +++ b/server/tests/scouts_tests.rs @@ -22,6 +22,7 @@ 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.asynchronous_combat_from = Some(0); game.players[0].action_cards = attacker_cards.to_vec(); game.players[1].action_cards = defender_cards.to_vec(); game diff --git a/server/tests/tactics_queue_tests.rs b/server/tests/tactics_queue_tests.rs deleted file mode 100644 index 058b36f3..00000000 --- a/server/tests/tactics_queue_tests.rs +++ /dev/null @@ -1,275 +0,0 @@ -use serde_json::{Value, json}; -use server::{ - board_history, - cache::Cache, - early_choices, - game::{Game, GameContext}, - game_data::GameData, -}; - -fn load(value: Value) -> Game { - let data: GameData = serde_json::from_value(value).unwrap(); - let cache = Cache::new(&data.options); - Game::from_data(data, cache, GameContext::Play) -} -fn data(game: &Game) -> Value { - serde_json::to_value(game.cloned_data()).unwrap() -} -fn play(game: Game, player: usize, action: Value) -> Game { - board_history::execute(game, serde_json::from_value(action).unwrap(), player).unwrap() -} -fn battle() -> Game { - let mut v: Value = - serde_json::from_str(include_str!("test_games/tactics_cards/peltasts.json")).unwrap(); - for p in [0, 1] { - v["players"][p]["advances"] - .as_array_mut() - .unwrap() - .push(json!("SteelWeapons")); - } - v["players"][0]["action_cards"] = json!([3, 6, 11]); - v["players"][1]["action_cards"] = json!([4, 7, 23]); - play( - load(v), - 0, - json!({"Movement":{"Move":{"units":[0,1,2],"destination":"C1","payment":{}}}}), - ) -} -fn key(g: &Game, p: usize) -> String { - early_choices::offers(g, p) - .into_iter() - .find(|o| o.key.ends_with("/tactics")) - .unwrap() - .key -} -fn queue(g: Game, p: usize, card: Option) -> Game { - let k = key(&g, p); - let cards: Vec = card - .into_iter() - .map(|id| json!({"ActionCard":id})) - .collect(); - play( - g, - p, - json!({"QueueChoice":{"key":k,"response":{"SelectHandCards":cards}}}), - ) -} -fn steel(g: Game, p: usize) -> Game { - play(g, p, json!({"Response":{"Payment":[{"ore":1}]}})) -} - -#[test] -fn private_metadata_edits_leave_payment_hand_rng_history_and_timing_untouched() { - let g = battle(); - let original = data(&g); - let enemy = data(&server::game_api::strip_secret(g.clone(), Some(1))); - let spectator = data(&server::game_api::strip_secret(g.clone(), None)); - let k = key(&g, 0); - let mut g = queue(g, 0, Some(3)); - for card in [None, Some(6), Some(3)] { - g = queue(g, 0, card); - } - assert_eq!( - data(&server::game_api::strip_secret(g.clone(), Some(1))), - enemy - ); - assert_eq!( - data(&server::game_api::strip_secret(g.clone(), None)), - spectator - ); - let mut edited = data(&g); - edited.as_object_mut().unwrap().remove("early_choices"); - edited - .as_object_mut() - .unwrap() - .remove("early_choice_update"); - assert_eq!(edited, original); - assert_eq!(g.active_player(), 0); - g = play(g, 0, json!({"QueueChoice":{"key":k,"response":null}})); - let mut cancelled = data(&g); - cancelled - .as_object_mut() - .unwrap() - .remove("early_choice_update"); - assert_eq!(cancelled, original); -} - -#[test] -fn consume_only_at_real_prompt_once_and_keep_card_facedown_until_other_choice() { - let g = queue(battle(), 0, Some(3)); - let k = key(&g, 0); - let g = steel(g, 0); - assert!(g.player(0).action_cards.contains(&3)); - assert_eq!(g.early_choices.len(), 1); - let g = steel(load(data(&g)), 1); - assert_eq!(g.active_player(), 1); - assert!(!g.player(0).action_cards.contains(&3)); - assert!(g.early_choices.is_empty()); - assert!(g.current_event_handler().is_some()); - let hidden = data(&server::game_api::strip_secret(g.clone(), Some(1))); - assert_eq!( - hidden["events"][0]["event_type"]["CombatRoundStart"]["attacker_strength"]["tactics_card"], - json!(0) - ); - assert!(!early_choices::can_save(&g, 0, &k, None)); - assert!(!early_choices::can_save(&g, 1, &k, None)); // live tactics is not a queued choice - let done = play( - g, - 1, - json!({"Response":{"SelectHandCards":[{"ActionCard":4}]}}), - ); - assert!(done.early_choices.is_empty()); - assert!(!done.player(1).action_cards.contains(&4)); -} - -#[test] -fn both_players_queue_and_automatic_execution_matches_ordinary_responses() { - let g = battle(); - let queued = queue(queue(g.clone(), 0, Some(3)), 1, Some(4)); - let queued = steel(steel(queued, 0), 1); - let normal = steel(steel(g, 0), 1); - let normal = play( - normal, - 0, - json!({"Response":{"SelectHandCards":[{"ActionCard":3}]}}), - ); - let normal = play( - normal, - 1, - json!({"Response":{"SelectHandCards":[{"ActionCard":4}]}}), - ); - for field in [ - "players", - "events", - "rng", - "dice_roll_log", - "log", - "time_increments", - "action_cards_discarded", - ] { - assert_eq!(data(&queued)[field], data(&normal)[field], "{field}"); - } - assert!(queued.early_choices.is_empty()); -} - -#[test] -fn missing_card_and_scout_after_enemy_pass_fall_back_to_real_prompt() { - let mut g = queue(battle(), 0, Some(3)); - g.players[0].action_cards.retain(|c| *c != 3); - let g = steel(steel(g, 0), 1); - assert_eq!(g.active_player(), 0); - assert!(g.early_choices.is_empty()); - let g = queue(queue(battle(), 0, None), 1, Some(23)); - let g = steel(steel(g, 0), 1); - assert_eq!(g.active_player(), 1); - assert!(g.early_choices.is_empty()); - assert!(g.player(1).action_cards.contains(&23)); -} - -#[test] -fn skipped_tactics_ability_expires_instead_of_surviving_battle() { - let mut g = queue(battle(), 1, Some(4)); - if let server::content::persistent_events::PersistentEventType::CombatStart(c) = - &mut g.events[0].event_type - { - c.modifiers - .push(server::combat::CombatModifier::TrojanHorse); - } - let g = queue(g, 0, None); - let g = steel(steel(g, 0), 1); - assert!(g.early_choices.is_empty()); - assert!(g.player(1).action_cards.contains(&4)); -} - -#[test] -fn undoing_battle_start_removes_plan_and_redo_does_not_resurrect_it() { - let g = queue(battle(), 0, Some(3)); - let g = play(g, 0, json!("Undo")); - assert!(g.early_choices.is_empty()); - let g = play(g, 0, json!("Redo")); - assert!(g.early_choices.is_empty()); - assert!(g.player(0).action_cards.contains(&3)); -} - -#[test] -fn hidden_hand_during_seat_switch_never_becomes_an_offer() { - let g = server::game_api::strip_secret(battle(), Some(0)); - assert!( - early_choices::offers(&g, 1) - .iter() - .all(|o| !o.key.ends_with("/tactics")) - ); -} - -#[test] -fn martyr_queue_does_not_choose_sacrifices_or_other_effect_responses() { - let mut g = battle(); - g.players[0].action_cards.push(24); - let g = queue(queue(g, 0, Some(24)), 1, Some(4)); - let g = steel(steel(g, 0), 1); - assert!(g.early_choices.is_empty()); - let handler = g.current_event_handler().unwrap(); - assert!(matches!( - handler.request, - server::content::persistent_events::PersistentEventRequest::SelectUnits(_) - )); - assert_eq!(g.active_player(), 0); -} - -#[test] -fn waiting_defender_can_queue_during_attackers_normal_tactics_prompt() { - let g = steel(steel(battle(), 0), 1); - assert_eq!(g.active_player(), 0); - let k = key(&g, 1); - let g = queue(g, 1, Some(4)); - assert_eq!(g.active_player(), 0); - assert!(g.player(1).action_cards.contains(&4)); - let g = play( - g, - 0, - json!({"Response":{"SelectHandCards":[{"ActionCard":3}]}}), - ); - assert!(g.early_choices.is_empty()); - assert!(!g.player(1).action_cards.contains(&4)); - assert!(!early_choices::can_save(&g, 1, &k, None)); -} - -#[test] -fn viewer_offers_tactics_only_after_own_steel_and_only_while_waiting() { - let offered = |g: &Game, p| { - server::web_view::view(g, Some(p))["earlyChoices"] - .as_array() - .unwrap() - .iter() - .any(|o| o["key"].as_str().unwrap().ends_with("/tactics")) - }; - let g = battle(); - assert!(!offered(&g, 0)); - assert!(!offered(&g, 1)); - let g = steel(g, 0); - assert!(offered(&g, 0)); - assert!(!offered(&g, 1)); - let g = queue(g, 0, Some(3)); - let g = steel(g, 1); - assert!(!offered(&g, 1)); // defender now has the ordinary live tactics request -} - -#[test] -fn stale_round_and_finished_battle_plans_are_pruned() { - let mut g = queue(battle(), 0, Some(3)); - let old_key = key(&g, 0); - if let server::content::persistent_events::PersistentEventType::CombatStart(c) = - &mut g.events[0].event_type - { - c.stats.round += 1; - } - assert_ne!(key(&g, 0), old_key); - early_choices::prune_objectives(&mut g); - assert!(g.early_choices.is_empty()); - assert!(!early_choices::can_save(&g, 0, &old_key, None)); - let mut g = queue(g, 0, Some(3)); - g.events.clear(); - early_choices::prune_objectives(&mut g); - assert!(g.early_choices.is_empty()); - assert!(g.player(0).action_cards.contains(&3)); -} diff --git a/server/tests/test_games/base/new_game.json b/server/tests/test_games/base/new_game.json index 3bcb1eeb..760a162e 100644 --- a/server/tests/test_games/base/new_game.json +++ b/server/tests/test_games/base/new_game.json @@ -3,6 +3,7 @@ "civilization": "ChooseCivilization" }, "version": 2, + "asynchronous_combat_from": 0, "state": "ChooseCivilization", "players": [ { diff --git a/web-client/docs/viewer-publishing.md b/web-client/docs/viewer-publishing.md index 4f6620c5..e982e8d8 100644 --- a/web-client/docs/viewer-publishing.md +++ b/web-client/docs/viewer-publishing.md @@ -1522,3 +1522,47 @@ skips, and four localization-source tests passed. One full native rerun hit the pre-existing random-actions Tributes eligibility rejection; a subsequent complete workspace rerun passed without skipping or changing it. No Tributes rule changes are included. Svelte reports zero errors/warnings. + +# Viewer 0.1.221 / engine 0.4.154 — prepared locally + +Replaces combat tactics queues with committed ordinary preparation: attacker +battle-start abilities and tactics, then defender battle-start abilities and +tactics, then reveal/effects/rolls. Eligibility, Scouts, Loyalty (including a third +player's Barbarian card), Martyr sacrifice and later-round rules are unchanged. +No production moves or save repairs are involved. Other early-choice queues are +retained; obsolete combat plans are pruned and never auto-consumed. + +Old open combats retain legacy order. Historical replay uses its recorded format +boundary (or legacy order when absent), then clamps the boundary to the returned +cursor's next action. This permits new battles on both full and partial replay +branches without reinterpreting old recorded responses. Undo/redo retains the +recorded mode; replacing an undone future starts a new branch. The frozen synthetic +217-action history was independently reconstructed by production engine 0.4.153; +actual engine.replay regression checks compare its board, players, events and RNG. +See `docs/asynchronous-combat-preparation.md` for the exact ordering contract. + +Release preparation includes Rust 1.94.1 formatting/lint/native tests, Svelte, +frontend/localization tests, bridge and production builds, packaged-engine +protocol/replay/privacy checks, and built-viewer combat/payment/forces, tactics, +journal, playback and split-WASM browser regressions. Local-host regression pays +both Steel Weapons choices, commits both normal Tactics choices, checks opponent +and spectator privacy, and asserts actual dice rolls with no combat queue. + +Package-lock version and achievement source-integrity manifest are updated; +artwork is generated only for validation, not published. Gallery, achievements, +other game metadata and game-length labels/order/Standard default must remain +unchanged. No special-rule changes, Fossil refresh or unrelated edits are included. + +**Not yet shipped.** Frozen artifacts and verification evidence are prepared in +`/tmp/release221`. Publish only after the matching source commit is pushed and +both Check and Web viewer CI succeed. Use the supported publisher with the frozen +0.4.154 tarball, then independently compare every hosted viewer asset and engine +byte and run downloaded-engine checks. Do not reuse the 0.1.220 publish script. + +Local verification result: **530 native tests passed, one existing ignored**, +including 13 focused preparation/replay/undo tests. **1,090 frontend tests**, +four gallery tests, 21 achievement tests without artifact-dependent skips, and +four localization-source tests passed. Svelte reports zero errors/warnings; +both 17-language catalogs validate. Rust 1.94.1 Clippy completes with existing +warnings. Six actual-engine preparation tests also run against the extracted +release tarball. No production publication is implied by these local results. diff --git a/web-client/package-lock.json b/web-client/package-lock.json index 2f98f7ef..395bde1f 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.220", + "version": "0.1.221", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@boardgamers/clash-web-client", - "version": "0.1.220", + "version": "0.1.221", "dependencies": { "@boardgamers/protocol": "0.11.0", "lucide-svelte": "^0.577.0", diff --git a/web-client/package.json b/web-client/package.json index ab46e6d2..781f4eb3 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-web-client", - "version": "0.1.220", + "version": "0.1.221", "private": true, "type": "module", "scripts": { diff --git a/web-client/release/achievement-assets.json b/web-client/release/achievement-assets.json index 2c7791e0..0e7ed439 100644 --- a/web-client/release/achievement-assets.json +++ b/web-client/release/achievement-assets.json @@ -13,7 +13,7 @@ "web-client/src/civilization-emblems.ts": "01b0cbf3fa77a8466532ccd73d63c1a3ddc9bbc79fc06ce7224b425322a9c9f0", "web-client/src/civilization-flags.ts": "cd176076bfe05b3059093b80c88596b7ae46b77898695c6c7406cbe1a3a0f78b", "server/src/content/civilizations.rs": "73602f3db506f3dc2dbc6de43d01179440fd3bb034c997ff209336faaef2a332", - "web-client/package-lock.json": "6e1aa90692d42347f0e179bfdeb825efa2726405556ce9d3fa02779104309a4c", + "web-client/package-lock.json": "f198e8d7b6e5cedc731a145c57146ac5db75f70ef6baf4683a066b5b054a07ab", "web-client/node_modules/lucide-svelte/dist/Icon.svelte": "f7b49ab842c143fa680fa8bd9a54a9efdc48c2e2d49fa574bd5ccf8f6cfca5be", "web-client/node_modules/lucide-svelte/dist/defaultAttributes.js": "5b8981c6e3434ae6538716af9e0403554e7708c4087f18d060950a7bef00d96a", "web-client/node_modules/lucide-svelte/LICENSE": "668dcc52803480e0a026b31140a4cae668772663cd764e5991d252eef03f98db" diff --git a/web-client/release/engine-package.json b/web-client/release/engine-package.json index 863290d8..3dd73eaf 100644 --- a/web-client/release/engine-package.json +++ b/web-client/release/engine-package.json @@ -1,6 +1,6 @@ { "name": "@boardgamers/clash-server", - "version": "0.4.153", + "version": "0.4.154", "description": "Clash of Cultures: Monumental edition engine for Boardgamers Space", "license": "MIT", "type": "commonjs", diff --git a/web-client/scripts/local-host-smoke.mjs b/web-client/scripts/local-host-smoke.mjs index 75bee141..c5585caf 100644 --- a/web-client/scripts/local-host-smoke.mjs +++ b/web-client/scripts/local-host-smoke.mjs @@ -9,8 +9,31 @@ const state = async () => { return JSON.parse(data.state); }; try { - const page = await browser.newPage({ viewport: { width: 1400, height: 900 } }); - await page.goto(base); + const testWidth = Number(process.env.CLASH_TEST_WIDTH ?? 1400); + const page = await browser.newPage({ viewport: { width: testWidth, height: 900 } }); + const submitted = []; + page.on('request', (request) => { + if (request.url().endsWith('/api/move') && request.method() === 'POST') { + const body = request.postDataJSON(); + submitted.push(typeof body.move === 'string' ? JSON.parse(body.move) : body.move); + } + }); + if (process.env.VIEWER_URL) { + await page.route('**/bundle/**', async (route) => { + const name = new URL(route.request().url()).pathname.slice('/bundle/'.length); + const response = await fetch(new URL(name, process.env.VIEWER_URL)); + assert(response.ok, name); + await route.fulfill({ + contentType: name.endsWith('.wasm') + ? 'application/wasm' + : name.endsWith('.json') + ? 'application/json' + : 'text/javascript', + body: Buffer.from(await response.arrayBuffer()), + }); + }); + } + await page.goto(`${base}/?built`); await page.locator('#scenario option[value="tactics"]').waitFor({ state: 'attached' }); await page.locator('#scenario').selectOption('tactics'); const steel = page.frameLocator('iframe').getByRole('region', { name: 'Steel Weapons', exact: true }); @@ -36,10 +59,71 @@ try { assert.equal((await state()).players[0].resources.gold, initial.players[0].resources.gold - 1); const game = page.frameLocator('iframe'); const tactics = game.getByRole('region', { name: 'Tactics', exact: true }); + await tactics.waitFor(); + const ownTactics = await state(); + assert.equal(ownTactics.events.at(-1).player, 0); + assert.deepEqual(ownTactics.map, initial.map); + for (const width of [1400, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.screenshot({ path: `/tmp/clash-async-own-tactics-${width}.png` }); + } + await page.setViewportSize({ width: testWidth, height: 900 }); await tactics.getByRole('button', { name: 'Select Routing', exact: true }).click(); - await tactics.getByRole('button', { name: 'Queue tactics', exact: true }).click(); + await tactics.getByRole('button', { name: 'Play tactics', exact: true }).click(); await page.waitForTimeout(300); - assert.equal((await state()).early_choices.length, 1); + const committed = await state(); + assert.equal(committed.early_choices?.length ?? 0, 0); + assert.equal(committed.events.at(-1).player, 1); + assert.equal(committed.events.at(-1).event_type.CombatRoundStart.preparation, 'DefenderAbilities'); + for (const width of [1400, 390]) { + await page.setViewportSize({ width, height: 900 }); + await page.screenshot({ path: `/tmp/clash-async-combat-${width}.png` }); + } + // The attacker has committed, not queued: the other seat and spectator see + // only a played-card marker until both ordinary Tactics responses complete. + for (const seat of ['1', 'spectator']) { + const hidden = JSON.parse((await (await fetch(`${base}/api/state?seat=${seat}`)).json()).state); + assert.equal(hidden.events.at(-1).event_type.CombatRoundStart.attacker_strength.tactics_card, 0); + assert(!hidden.action_cards_discarded?.includes(3)); + assert.equal(hidden.early_choices?.length ?? 0, 0); + } + await page.setViewportSize({ width: testWidth, height: 900 }); + await page.locator('#seat').selectOption('1'); + await steel.waitFor(); + await steel.getByRole('button', { name: 'Gold', exact: false }).click(); + await steel.getByRole('button', { name: 'Confirm', exact: true }).click(); + await tactics.waitFor(); + const defenderPaid = await state(); + assert.equal(defenderPaid.players[1].resources.gold, initial.players[1].resources.gold - 1); + assert.equal(defenderPaid.events.at(-1).player, 1); + assert.equal(await game.getByRole('button', { name: /Queue tactics/ }).count(), 0); + await tactics.getByRole('button', { name: 'Select Peltasts', exact: true }).click(); + await tactics.getByRole('button', { name: 'Play tactics', exact: true }).click(); + await page.waitForFunction(async () => { + const raw = JSON.parse((await (await fetch('/api/state?seat=0')).json()).state); + return raw.log + .flatMap((a) => a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? []))) + .some((a) => a.items?.some((i) => i.CombatRoll)); + }); + const rolled = await state(); + const actions = rolled.log.flatMap((a) => a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? []))); + const rolls = (items) => items.flatMap((a) => a.items ?? []).filter((i) => i.CombatRoll).length; + const initialActions = initial.log.flatMap((a) => + a.rounds.flatMap((r) => r.turns.flatMap((t) => t.actions ?? [])), + ); + assert(rolls(actions) >= rolls(initialActions) + 2, 'both sides actually rolled after the commitments'); + assert.deepEqual( + submitted, + [ + { Response: { Payment: [{ gold: 1 }] } }, + { Response: { SelectHandCards: [{ ActionCard: 3 }] } }, + { Response: { Payment: [{ gold: 1 }] } }, + { Response: { SelectHandCards: [{ ActionCard: 4 }] } }, + ], + 'both normal payments and card responses commit exactly once; no queue action', + ); + assert.equal(rolled.early_choices?.length ?? 0, 0); + await page.locator('#seat').selectOption('0'); await page.locator('#restart-scenario').click(); await steel.waitFor(); const restarted = await state(); @@ -54,7 +138,7 @@ try { !document.querySelector('#restart-scenario')?.disabled, ); console.log( - 'Host select contrast in both themes; Steel fixture selection, payment/restart and fresh-tab restart passed.', + `${testWidth}px: both Steel payments and ordinary Tactics commits, handoff, hidden-card privacy, both dice rolls, no combat queue, host themes and restart passed.`, ); } finally { await browser.close(); diff --git a/web-client/scripts/preview-scenarios.ts b/web-client/scripts/preview-scenarios.ts index 059c4e81..be5621ea 100644 --- a/web-client/scripts/preview-scenarios.ts +++ b/web-client/scripts/preview-scenarios.ts @@ -1,7 +1,7 @@ import { readFileSync } from 'node:fs'; export const previewScenarios = [ - { id: 'tactics', label: 'Tactics · Steel Weapons', note: 'Local engine match. Queue tactics privately, then switch seats to resolve Steel Weapons and play the battle.' }, + { id: 'tactics', label: 'Tactics · Steel Weapons', note: 'Local asynchronous sequence: attacker Steel Weapons and tactics, then defender Steel Weapons and tactics, then reveal.' }, { id: 'advance', label: 'Free advance', note: 'Research lets you save an early choice.' }, { id: 'raze', label: 'Raze city', note: 'Cities lets you save an early choice.' }, { id: 'objectives-before', label: 'Objectives · during turn', note: 'Queue in Objectives now; conditions are checked again before scoring.' }, diff --git a/web-client/scripts/tactics-queue-smoke.mjs b/web-client/scripts/tactics-queue-smoke.mjs deleted file mode 100644 index deb2a333..00000000 --- a/web-client/scripts/tactics-queue-smoke.mjs +++ /dev/null @@ -1,93 +0,0 @@ -import assert from 'node:assert/strict'; -import { chromium } from 'playwright'; -const base = process.env.CLASH_PREVIEW_URL ?? 'http://localhost:8679'; -const browser = await chromium.launch({ - headless: true, - args: ['--no-sandbox', '--use-gl=angle', '--use-angle=swiftshader'], -}); -assert.ok(['localhost', '127.0.0.1'].includes(new URL(base).hostname), 'local preview only'); -const state = async (seat) => await (await fetch(`${base}/api/state?seat=${seat}`)).json(); -try { - for (const [width, height] of [ - [1400, 900], - [390, 740], - [320, 640], - ]) { - await fetch(`${base}/api/scenarios`, { - method: 'POST', - headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ id: 'tactics' }), - }); - const page = await browser.newPage({ viewport: { width, height } }); - const errors = []; - page.on('pageerror', (e) => errors.push(e.message)); - await page.goto(`${base}/?built`); - await page.locator('#seat').selectOption('0'); - const game = page.frameLocator('iframe'); - const panel = game.getByRole('region', { name: 'Steel Weapons', exact: true }); - await panel.waitFor(); - assert.equal(await panel.locator('.tactics-queue').count(), 0); - assert.equal(await game.getByRole('region', { name: 'Choose ahead', exact: true }).count(), 0); - await page.screenshot({ path: `/tmp/clash-tactics-steel-${width}.png` }); - await panel.getByRole('button', { name: 'Gold', exact: false }).click(); - const before = JSON.parse((await state(0)).state); - await panel.getByRole('button', { name: 'Confirm', exact: true }).click(); - await panel.waitFor({ state: 'hidden' }); - const paid = JSON.parse((await state(0)).state); - assert.equal(paid.players[0].resources.gold, before.players[0].resources.gold - 1); - assert.equal(paid.players[0].resources.ore, before.players[0].resources.ore); - const commit = async (name) => { - const response = page.waitForResponse( - (r) => r.url().endsWith('/api/move') && r.request().method() === 'POST', - ); - await choices.getByRole('button', { name, exact: true }).click(); - assert.equal((await response).status(), 200); - }; - const choices = game.getByRole('region', { name: 'Tactics', exact: true }); - await choices.waitFor(); - assert.equal(await game.getByRole('region', { name: 'Choose ahead', exact: true }).count(), 0); - assert(await choices.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)); - await page.screenshot({ path: `/tmp/clash-tactics-queue-${width}.png` }); - await choices.getByRole('button', { name: 'Select Routing', exact: true }).click(); - assert.doesNotMatch(await choices.innerText(), /Discards the selected card/); - await commit('Queue tactics'); - await choices.getByText('Queued', { exact: true }).waitFor(); - const queued = JSON.parse((await state(0)).state); - for (const field of ['players', 'events', 'log', 'log_index', 'board_history', 'time_increments']) - assert.deepEqual(queued[field], paid[field], field); - assert.equal(queued.early_choices.length, 1); - assert.equal(JSON.parse((await state(1)).state).early_choices, undefined); - await choices.getByRole('button', { name: 'Select High Morale', exact: true }).click(); - assert.doesNotMatch(await choices.innerText(), /Discards the selected card/); - await commit('Queue tactics'); - await commit('Cancel queued choice'); - await choices.getByText('Queued', { exact: true }).waitFor({ state: 'hidden' }); - await commit('Skip'); - await choices.getByText('Queued', { exact: true }).waitFor(); - assert.deepEqual(JSON.parse((await state(0)).state).early_choices[0].response, { SelectHandCards: [] }); - await choices.getByRole('button', { name: 'Select Routing', exact: true }).click(); - assert.doesNotMatch(await choices.innerText(), /Discards the selected card/); - await commit('Queue tactics'); - await choices.getByText('Queued', { exact: true }).waitFor(); - await page.locator('#seat').selectOption('1'); - await panel.waitFor({ timeout: 10000 }).catch(async (e) => { - console.log(await page.frames()[1].locator('body').innerText(), errors); - throw e; - }); - await panel.getByRole('button', { name: 'Confirm', exact: true }).click(); - const tactics = game.getByRole('region', { name: 'Tactics', exact: true }); - await tactics.waitFor(); - await tactics.getByRole('button', { name: 'Select Peltasts', exact: true }).click(); - assert.doesNotMatch(await tactics.innerText(), /Discards the selected card/); - assert.equal(await tactics.getByRole('button', { name: 'Play tactics', exact: true }).count(), 1); - assert.equal(await tactics.locator('.tactics-queue').count(), 0, 'current prompt is not a queued choice'); - await page.screenshot({ path: `/tmp/clash-tactics-live-${width}.png` }); - assert.deepEqual(errors, []); - await page.close(); - console.log( - `Steel first, automatic normal tactics queue/edit/cancel, privacy and ordinary live prompt: ${width}px passed`, - ); - } -} finally { - await browser.close(); -} diff --git a/web-client/src/App.svelte b/web-client/src/App.svelte index 8ea639d9..b248f68b 100644 --- a/web-client/src/App.svelte +++ b/web-client/src/App.svelte @@ -102,7 +102,6 @@ import CollectionCapacity from './CollectionCapacity.svelte'; import ContextualCards from './ContextualCards.svelte'; import DecisionPanel from './DecisionPanel.svelte'; - import { queuedTacticsDecision } from './queued-tactics'; import EarlyChoices from './EarlyChoices.svelte'; import EarlyChoiceBadge from './EarlyChoiceBadge.svelte'; import CombatJournal from './CombatJournal.svelte'; @@ -137,14 +136,12 @@ const planningQueue = $derived(!!queueControls?.pending && queueControls.seat === 0); let earlyPanel = $state<'cities' | 'abilities' | 'first' | null>(null); const earlyOffers = $derived(!$session.playback ? $session.view?.earlyChoices ?? [] : []); - const tacticsQueue = $derived(!$session.view?.decision ? earlyOffers.find(o => o.key.endsWith('/tactics')) : undefined); - const queuedTactics = $derived(queuedTacticsDecision($session.view, tacticsQueue)); const earlyAdvance = $derived(earlyOffers.find(o => o.key.endsWith('/advance'))); const earlyFirst = $derived(earlyOffers.filter(o => o.key.endsWith(':first'))); const earlyCities = $derived(earlyOffers.filter(o => o.key.endsWith('/raze'))); const earlyObjectives = $derived(earlyOffers.filter(o => o.key.includes(':objective:'))); const earlyPeople = $derived(earlyOffers.filter(o => o.key.endsWith('/offer'))); - const earlyAbilities = $derived(earlyOffers.filter(o => !o.key.endsWith('/tactics') && !o.key.endsWith('/advance') && !o.key.endsWith('/raze') && !o.key.includes(':objective:') && !o.key.endsWith('/offer') && !o.key.endsWith('/government') && !o.key.endsWith(':first'))); + const earlyAbilities = $derived(earlyOffers.filter(o => !o.key.endsWith('/advance') && !o.key.endsWith('/raze') && !o.key.includes(':objective:') && !o.key.endsWith('/offer') && !o.key.endsWith('/government') && !o.key.endsWith(':first'))); const panelOffers = $derived(earlyPanel === 'cities' ? earlyCities : earlyPanel === 'abilities' ? earlyAbilities : earlyPanel === 'first' ? earlyFirst : []); function openEarly(panel: 'cities' | 'abilities' | 'first') { earlyPanel = earlyPanel === panel ? null : panel; @@ -1898,9 +1895,6 @@ {controller} decision={$session.view.decision} onHighlight={(position) => world?.highlightCoordinate(position)} - />{/key}{:else if queuedTactics && tacticsQueue}{#key `${$session.seat}:${tacticsQueue.key}`} world?.highlightCoordinate(position)} />{/key}{/if} {#if $session.abilitiesOpen && $session.mode === 'overview' && !$session.view?.decision && !choiceDecision && !objectiveDecision} void } = + }: { controller: Controller; decision: Decision; onHighlight: (position: string | null) => void } = $props(); const session = $derived(controller.session); const announcedCard = $derived(pendingActionCard($session.view, decision)); let announcedRulesOpen = $state(false); const panelId = $props.id(); - let queuedSelection = $state(untrack(() => { - const cards = (queue?.selected as {SelectHandCards?: unknown[]} | null)?.SelectHandCards ?? []; - return decision.options.flatMap((o, i) => cards.some(c => JSON.stringify(c) === JSON.stringify(o.value)) ? [i] : []); - })); - const selected = $derived(queue ? queuedSelection : $session.decisionSelection); + const selected = $derived($session.decisionSelection); const opponentTactics = $derived(opponentTacticsLabel(decision)); const resourceChoice = $derived(decision.reward && decision.name === 'Select a resource to gain'); const title = $derived(resourceChoice ? 'Gain resources' : printedCardName(decision.name)); @@ -139,7 +133,6 @@ payments = payments.map((p, j) => (i === j ? payment : p)); } const preview = $derived.by(() => { - if (queue) return { action: {QueueChoice: {key: queue.key, response: {SelectHandCards: selected.map(i => decision.options[i].value)}}} as Move, error: '' }; try { return { ...controller.query<{ action: Move }>({ @@ -175,8 +168,7 @@ return [...groups.values()].sort((a,b)=>a.order-b.order); }); function toggle(i: number) { - if (queue) queuedSelection = selected.includes(i) ? [] : [i]; - else controller.selectDecisionOption(i); + controller.selectDecisionOption(i); } onDestroy(() => onHighlight(null)); @@ -511,7 +503,7 @@ Always keep cities in future ages {/if} - {#if !queue && (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action} + {#if (decision.tacticsSelection || decision.name === 'Siegecraft') && preview.action} {/if}