From 3253a4b7012d7e2d2edf0d68fbc41c8e03be33da Mon Sep 17 00:00:00 2001 From: coyotte508 Date: Wed, 25 Nov 2026 00:09:23 +0000 Subject: [PATCH] Move only unmoved barbarian units --- scripts/barbarian-movement.test.cjs | 170 ++++++++ server/src/action_card.rs | 4 + server/src/barbarians.rs | 43 +- server/src/barbarians_tests.rs | 111 +++++ .../src/content/action_cards/mercenaries.rs | 41 +- server/src/game.rs | 1 + server/src/game_data.rs | 5 + server/src/game_setup.rs | 1 + server/src/log.rs | 2 + server/src/replay.rs | 9 + server/src/undo.rs | 3 +- server/tests/architect_replay_tests.rs | 24 ++ server/tests/barbarian_movement_tests.rs | 397 ++++++++++++++++++ server/tests/common/mod.rs | 9 + server/tests/test_games/base/new_game.json | 1 + web-client/package.json | 2 +- web-client/src/prediction.test.ts | 1 + web-client/src/prediction.ts | 1 + 18 files changed, 808 insertions(+), 17 deletions(-) create mode 100644 scripts/barbarian-movement.test.cjs create mode 100644 server/tests/barbarian_movement_tests.rs diff --git a/scripts/barbarian-movement.test.cjs b/scripts/barbarian-movement.test.cjs new file mode 100644 index 00000000..f09117ad --- /dev/null +++ b/scripts/barbarian-movement.test.cjs @@ -0,0 +1,170 @@ +// Synthetic public WASM captures for Barbarian movement fixes; no production saves. +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { test } = require('node:test'); + +const engine = require(process.env.CLASH_WASM || '../web-client/.engine/server.js'); +const move = (g, a, player = 0) => + JSON.parse(engine.tryMove(JSON.stringify(g), JSON.stringify(a), player)); + +const loadFixture = (rel) => + JSON.parse( + fs.readFileSync( + path.join(__dirname, '..', 'server', 'tests', 'test_games', rel), + 'utf8', + ), + ); + +const barbUnitsAt = (g, pos) => + g.players + .find((p) => p.civilization === 'Barbarians') + .units.filter((u) => u.position === pos); + +function setupMergingIncident(boundary) { + const g = loadFixture('incidents/barbarians_move.json'); + if (boundary === undefined) delete g.barbarian_movement_from; + else g.barbarian_movement_from = boundary; + g.players[1].units = []; + g.players[0].cities = [ + { position: 'A1', mood_state: 'Happy' }, + { position: 'C2', mood_state: 'Happy' }, + ]; + g.players[0].units = []; + const barb = g.players.find((p) => p.civilization === 'Barbarians'); + barb.cities = []; + barb.units = [ + { id: 10, position: 'A3', unit_type: 'Cavalry' }, + { id: 20, position: 'B2', unit_type: 'Infantry' }, + ]; + barb.next_unit_id = 21; + return g; +} + +test('merging Barbarian armies moves only unmoved units under new boundary and preserves legacy', () => { + let g = setupMergingIncident(0); + g = move(g, { Response: { SelectAdvance: 'Storage' } }); + g = move(g, { Response: { SelectPositions: ['A3'] } }); + assert.deepEqual( + barbUnitsAt(g, 'B2').map((u) => u.id), + [10], + 'already-moved Cavalry stays at B2', + ); + assert.deepEqual( + barbUnitsAt(g, 'C2').map((u) => u.id), + [20], + 'only unmoved Infantry advances to C2', + ); + + let legacy = setupMergingIncident(999999); + legacy = move(legacy, { Response: { SelectAdvance: 'Storage' } }); + legacy = move(legacy, { Response: { SelectPositions: ['A3'] } }); + assert.deepEqual(barbUnitsAt(legacy, 'B2'), []); + assert.deepEqual( + barbUnitsAt(legacy, 'C2') + .map((u) => u.id) + .sort((a, b) => a - b), + [10, 20], + ); +}); + +test('Barbarians move incident enforces stack limit 4 on destination choices', () => { + const g0 = loadFixture('incidents/barbarians_move.json'); + g0.barbarian_movement_from = 0; + g0.players[1].units = []; + g0.players[1].cities = []; + g0.players[0].cities = [ + { position: 'A1', mood_state: 'Happy' }, + { position: 'C1', mood_state: 'Happy' }, + ]; + g0.players[0].units = []; + const barb = g0.players.find((p) => p.civilization === 'Barbarians'); + barb.cities = []; + barb.units = [ + { id: 1, position: 'B2', unit_type: 'Cavalry' }, + { id: 2, position: 'B2', unit_type: 'Cavalry' }, + { id: 3, position: 'B1', unit_type: 'Infantry' }, + { id: 4, position: 'B1', unit_type: 'Infantry' }, + { id: 5, position: 'B1', unit_type: 'Infantry' }, + { id: 6, position: 'C2', unit_type: 'Infantry' }, + { id: 7, position: 'C2', unit_type: 'Infantry' }, + ]; + barb.next_unit_id = 8; + + let g = move(g0, { Response: { SelectAdvance: 'Storage' } }); + g = move(g, { Response: { SelectPositions: ['B2'] } }); + assert.equal(barbUnitsAt(g, 'B2').length, 0); + assert.equal(barbUnitsAt(g, 'C2').length, 4); + assert.equal(barbUnitsAt(g, 'B1').length, 3); +}); + +test('Mercenaries moving first army onto second does not move first army twice', () => { + const setupMerc = (boundary) => { + const g = loadFixture('action_cards/mercenaries.json'); + g.barbarian_movement_from = boundary; + g.players[1].units = []; + g.players[0].units = g.players[0].units.filter((u) => u.position !== 'B2'); + const barb = g.players.find((p) => p.civilization === 'Barbarians'); + barb.cities = []; + barb.units = [ + { id: 10, position: 'A3', unit_type: 'Cavalry' }, + { id: 11, position: 'A3', unit_type: 'Cavalry' }, + { id: 20, position: 'B3', unit_type: 'Infantry' }, + { id: 21, position: 'B3', unit_type: 'Infantry' }, + { id: 30, position: 'B2', unit_type: 'Elephant' }, + { id: 31, position: 'B2', unit_type: 'Elephant' }, + ]; + barb.next_unit_id = 32; + return g; + }; + + let g = move(setupMerc(0), { Playing: { ActionCard: 13 } }); + g = move(g, { Response: { SelectPositions: ['A3', 'B3'] } }); + g = move(g, { Response: { Payment: [{ ore: 2 }] } }); + g = move(g, { Response: { SelectPositions: ['A3'] } }); + g = move(g, { Response: { SelectPositions: ['B3'] } }); + g = move(g, { Response: { SelectPositions: ['B2'] } }); + assert.equal((g.events || []).length, 0); + assert.deepEqual( + barbUnitsAt(g, 'B3') + .map((u) => u.id) + .sort((a, b) => a - b), + [10, 11], + ); + assert.deepEqual( + barbUnitsAt(g, 'B2') + .map((u) => u.id) + .sort((a, b) => a - b), + [20, 21, 30, 31], + ); + + let legacy = move(setupMerc(999999), { Playing: { ActionCard: 13 } }); + legacy = move(legacy, { Response: { SelectPositions: ['A3', 'B3'] } }); + legacy = move(legacy, { Response: { Payment: [{ ore: 2 }] } }); + legacy = move(legacy, { Response: { SelectPositions: ['A3'] } }); + legacy = move(legacy, { Response: { SelectPositions: ['B3'] } }); + assert.equal(barbUnitsAt(legacy, 'B3').length, 0); + assert.equal(barbUnitsAt(legacy, 'A3').length, 4); +}); + +test('upgraded save stamps barbarian_movement_from and preserves it across undo/redo', () => { + let g = setupMergingIncident(undefined); + assert.equal(g.barbarian_movement_from, undefined); + g = move(g, { Response: { SelectAdvance: 'Storage' } }); + const boundary = g.barbarian_movement_from; + assert.equal(typeof boundary, 'number'); + g = move(g, { Response: { SelectPositions: ['A3'] } }); + assert.equal(g.barbarian_movement_from, boundary); + assert.deepEqual( + barbUnitsAt(g, 'B2').map((u) => u.id), + [10], + ); + const undone = move(g, 'Undo'); + assert.equal(undone.barbarian_movement_from, boundary); + const redone = move(undone, 'Redo'); + assert.equal(redone.barbarian_movement_from, boundary); + assert.deepEqual( + barbUnitsAt(redone, 'B2').map((u) => u.id), + [10], + ); +}); diff --git a/server/src/action_card.rs b/server/src/action_card.rs index dd16eef3..dbc03d4d 100644 --- a/server/src/action_card.rs +++ b/server/src/action_card.rs @@ -370,6 +370,9 @@ pub struct ActionCardInfo { #[serde(skip_serializing_if = "Vec::is_empty")] pub selected_positions: Vec, #[serde(default)] + #[serde(skip_serializing_if = "Vec::is_empty")] + pub moved_units: Vec, + #[serde(default)] #[serde(skip_serializing_if = "Option::is_none")] pub selected_player: Option, #[serde(default)] @@ -390,6 +393,7 @@ impl ActionCardInfo { id, selected_position: None, selected_positions: Vec::new(), + moved_units: Vec::new(), selected_player: None, selected_advance: None, answer: None, diff --git a/server/src/barbarians.rs b/server/src/barbarians.rs index 74192d49..635356f8 100644 --- a/server/src/barbarians.rs +++ b/server/src/barbarians.rs @@ -17,7 +17,7 @@ use crate::player_events::{IncidentInfo, IncidentTarget, PersistentEvent, Persis use crate::position::Position; use crate::resource::ResourceType; use crate::resource_pile::ResourcePile; -use crate::unit::{UnitType, Units}; +use crate::unit::{Unit, UnitType, Units}; use itertools::Itertools; use serde::{Deserialize, Serialize}; @@ -314,21 +314,44 @@ pub(crate) fn barbarians_move(mut builder: IncidentBuilder) -> IncidentBuilder { ) } +pub(crate) fn corrected_barbarian_movement(game: &Game) -> bool { + game.barbarian_movement_from + .is_some_and(|from| crate::game_api::log_length(game) >= from) +} + +fn unmoved_barbarian_units<'a>( + game: &'a Game, + state: &BarbariansEventState, + pos: Position, +) -> Vec<&'a Unit> { + get_barbarians_player(game) + .get_units(pos) + .into_iter() + .filter(|u| !state.moved_units.contains(&u.id)) + .collect() +} + pub(crate) fn barbarian_move_destinations( game: &Game, player: usize, state: &BarbariansEventState, army: Position, ) -> Vec { + let corrected = corrected_barbarian_movement(game); + let stack = if corrected { + unmoved_barbarian_units(game, state, army).len() + } else { + get_barbarians_player(game).get_units(army).len() + }; if state.hunnic_tribes { let barb = get_barbarians_player(game); - let size = barb.get_units(army).len(); army.neighbors() .into_iter() - .filter(|to| game.map.is_land(*to) && barb.get_units(*to).len() + size <= STACK_LIMIT) + .filter(|to| game.map.is_land(*to) && barb.get_units(*to).len() + stack <= STACK_LIMIT) .collect() } else { - barbarian_march_steps(game, game.player(player), army, 0) + let stack_size = if corrected { stack } else { 0 }; + barbarian_march_steps(game, game.player(player), army, stack_size) } } @@ -375,10 +398,14 @@ fn execute_barbarian_move( .take() .expect("selected position should exist"); let to = s.choice[0]; - let ids = get_barbarians_player(game).get_units(from); - let units: Vec = ids.iter().map(|u| u.id).collect(); - state.moved_units.extend(units.iter()); - let unit_types = ids.iter().map(|u| u.unit_type).collect::(); + let moving = if corrected_barbarian_movement(game) { + unmoved_barbarian_units(game, state, from) + } else { + get_barbarians_player(game).get_units(from) + }; + let units: Vec = moving.iter().map(|u| u.id).collect(); + let unit_types = moving.iter().map(|u| u.unit_type).collect::(); + state.moved_units.extend(units.iter().copied()); s.log( game, &format!( diff --git a/server/src/barbarians_tests.rs b/server/src/barbarians_tests.rs index 0f32668f..2b87f896 100644 --- a/server/src/barbarians_tests.rs +++ b/server/src/barbarians_tests.rs @@ -191,3 +191,114 @@ fn insufficient_infantry_supply_keeps_the_city_choice() { assert!(get_barbarians_player(&game).get_units(first).is_empty()); assert_eq!(get_barbarians_player(&game).get_units(second).len(), 1); } + +fn add_barbarian_units(game: &mut Game, pos: Position, units: &[UnitType]) -> Vec { + let player = get_barbarians_player(game).index; + units + .iter() + .map(|unit| { + let id = game.players[player].next_unit_id; + game.players[player].next_unit_id += 1; + game.players[player] + .units + .push(Unit::new(player, pos, *unit, id)); + id + }) + .collect() +} + +#[test] +fn barbarian_move_destinations_respects_stack_limit_and_unmoved_units_in_normal_and_hunnic_modes() { + let mut game = setup(); + game.barbarian_movement_from = Some(0); + // In Odd-Q coordinates, B2=(1,1) is distance 2 from C1=(2,-1) with land steps B1=(1,0) and C2=(2,0). + let a3 = Position::from_offset("A3"); + let b1 = Position::from_offset("B1"); + let b2 = Position::from_offset("B2"); + let b3 = Position::from_offset("B3"); + let c1 = Position::from_offset("C1"); + let c2 = Position::from_offset("C2"); + game.players[1].cities.clear(); + game.players[0].cities = vec![City::new(0, c1)]; + + let moved_on_b2 = add_barbarian_units(&mut game, b2, &[UnitType::Cavalry, UnitType::Cavalry]); + let _unmoved_on_b2 = + add_barbarian_units(&mut game, b2, &[UnitType::Infantry, UnitType::Infantry]); + add_barbarian_units( + &mut game, + b1, + &[UnitType::Infantry, UnitType::Infantry, UnitType::Infantry], + ); + add_barbarian_units(&mut game, c2, &[UnitType::Infantry, UnitType::Infantry]); + + let state = BarbariansEventState { + moved_units: moved_on_b2, + ..BarbariansEventState::new() + }; + // Normal branch: 2 unmoved on B2 + 3 on B1 = 5 > STACK_LIMIT (excluded); 2 + 2 on C2 = 4 (included). + assert_eq!(barbarian_move_destinations(&game, 0, &state, b2), vec![c2]); + + // Legacy boundary preserves stack_size = 0 in the normal branch. + game.barbarian_movement_from = Some(usize::MAX); + let mut legacy_dests = barbarian_move_destinations(&game, 0, &state, b2); + legacy_dests.sort(); + assert_eq!(legacy_dests, vec![b1, c2]); + + // Hunnic Tribes branch: 2 already-moved + 2 unmoved on B2. + let mut hun_game = setup(); + hun_game.barbarian_movement_from = Some(0); + let moved_on_b2 = + add_barbarian_units(&mut hun_game, b2, &[UnitType::Cavalry, UnitType::Cavalry]); + let _unmoved_on_b2 = + add_barbarian_units(&mut hun_game, b2, &[UnitType::Infantry, UnitType::Infantry]); + add_barbarian_units(&mut hun_game, b3, &[UnitType::Infantry, UnitType::Infantry]); + add_barbarian_units( + &mut hun_game, + b1, + &[UnitType::Infantry, UnitType::Infantry, UnitType::Infantry], + ); + let hun_state = BarbariansEventState { + hunnic_tribes: true, + moved_units: moved_on_b2, + ..BarbariansEventState::new() + }; + let dests = barbarian_move_destinations(&hun_game, 0, &hun_state, b2); + assert!(dests.contains(&b3), "2 unmoved + 2 on B3 <= 4"); + assert!(dests.contains(&a3), "2 unmoved + 0 on A3 <= 4"); + assert!(!dests.contains(&b1), "2 unmoved + 3 on B1 = 5 > 4"); + + // Legacy Hunnic Tribes counted all 4 units on B2, excluding B3 (4 + 2 > 4). + hun_game.barbarian_movement_from = Some(usize::MAX); + let legacy_hun = barbarian_move_destinations(&hun_game, 0, &hun_state, b2); + assert!(!legacy_hun.contains(&b3)); + assert!(legacy_hun.contains(&a3)); +} + +#[test] +fn map_guide_matches_corrected_barbarian_move_destinations() { + let mut game = setup(); + game.barbarian_movement_from = Some(0); + let b1 = Position::from_offset("B1"); + let b2 = Position::from_offset("B2"); + let c1 = Position::from_offset("C1"); + let c2 = Position::from_offset("C2"); + game.players[1].cities.clear(); + game.players[0].cities = vec![City::new(0, c1)]; + add_barbarian_units(&mut game, b2, &[UnitType::Infantry, UnitType::Infantry]); + add_barbarian_units( + &mut game, + b1, + &[UnitType::Infantry, UnitType::Infantry, UnitType::Infantry], + ); + add_barbarian_units(&mut game, c2, &[UnitType::Infantry, UnitType::Infantry]); + + let guide = map_guide(&game, 0); + let b2_moves: Vec<&str> = guide["moves"] + .as_array() + .expect("moves array") + .iter() + .filter(|m| m["from"] == "B2") + .map(|m| m["to"].as_str().expect("destination string")) + .collect(); + assert_eq!(b2_moves, vec!["C2"]); +} diff --git a/server/src/content/action_cards/mercenaries.rs b/server/src/content/action_cards/mercenaries.rs index c1005c88..e961b529 100644 --- a/server/src/content/action_cards/mercenaries.rs +++ b/server/src/content/action_cards/mercenaries.rs @@ -1,6 +1,8 @@ use crate::ability_initializer::AbilityInitializerSetup; -use crate::action_card::{ActionCard, ActionCardBuilder}; -use crate::barbarians::{barbarian_reinforcement, get_barbarians_player}; +use crate::action_card::{ActionCard, ActionCardBuilder, ActionCardInfo}; +use crate::barbarians::{ + barbarian_reinforcement, corrected_barbarian_movement, get_barbarians_player, +}; use crate::combat::move_with_possible_combat; use crate::consts::STACK_LIMIT; use crate::content::action_cards::inspiration::player_positions; @@ -101,11 +103,20 @@ fn move_army(b: ActionCardBuilder, i: i32) -> ActionCardBuilder { .add_position_request( |e| &mut e.play_action_card, src_prio, - |_game, _player, a| { + |game, _player, a| { a.selected_position = None; + let choices = if corrected_barbarian_movement(game) { + a.selected_positions + .iter() + .copied() + .filter(|&pos| !unmoved_mercenary_units(game, a, pos).is_empty()) + .collect_vec() + } else { + a.selected_positions.clone() + }; Some(PositionRequest::new( - a.selected_positions.clone(), + choices, 1..=1, "Select Barbarian army to move", )) @@ -123,7 +134,10 @@ fn move_army(b: ActionCardBuilder, i: i32) -> ActionCardBuilder { |game, _player, a| { let from = a.selected_position?; let barbarian = get_barbarians_player(game); - let units = barbarian.get_units(from).iter().map(|u| u.id).collect_vec(); + let units = unmoved_mercenary_units(game, a, from); + if corrected_barbarian_movement(game) && units.is_empty() { + return None; + } let destinations = from .neighbors() @@ -148,11 +162,13 @@ fn move_army(b: ActionCardBuilder, i: i32) -> ActionCardBuilder { ); let from = a.selected_position.expect("position not found"); + let units = unmoved_mercenary_units(game, a, from); + if corrected_barbarian_movement(game) { + a.moved_units.extend(units.iter().copied()); + } let b = get_barbarians_player(game); let barbarian = b.index; - let units = b.get_units(from).iter().map(|u| u.id).collect_vec(); - let m = MoveUnits::new(units, to, None, ResourcePile::empty()); s.player() .add_log_entry(game, ActionLogEntry::move_units(b, &m)); @@ -174,6 +190,17 @@ fn move_army(b: ActionCardBuilder, i: i32) -> ActionCardBuilder { ) } +fn unmoved_mercenary_units(game: &Game, a: &ActionCardInfo, pos: Position) -> Vec { + let barbarian = get_barbarians_player(game); + let corrected = corrected_barbarian_movement(game); + barbarian + .get_units(pos) + .into_iter() + .filter(|u| !corrected || !a.moved_units.contains(&u.id)) + .map(|u| u.id) + .collect_vec() +} + fn barbarian_army_positions_in_range2( game: &Game, player: &Player, diff --git a/server/src/game.rs b/server/src/game.rs index dc0aa535..4b24f7f5 100644 --- a/server/src/game.rs +++ b/server/src/game.rs @@ -160,6 +160,7 @@ pub struct Game { pub great_architect_action_cost_from: Option, pub aggressor_eligibility_from: Option, pub provinces_from: Option, + pub barbarian_movement_from: Option, pub home_layout: crate::map::HomeLayout, pub version: u16, // JSON schema version pub state: GameState, diff --git a/server/src/game_data.rs b/server/src/game_data.rs index fa724824..b4407775 100644 --- a/server/src/game_data.rs +++ b/server/src/game_data.rs @@ -47,6 +47,8 @@ pub struct GameData { aggressor_eligibility_from: Option, #[serde(default, skip_serializing_if = "Option::is_none")] provinces_from: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + barbarian_movement_from: Option, #[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")] home_layout: crate::map::HomeLayout, #[serde(default)] @@ -174,6 +176,7 @@ pub fn from_data(data: GameData, mut cache: Cache, context: GameContext) -> Game great_architect_action_cost_from: data.great_architect_action_cost_from, aggressor_eligibility_from: data.aggressor_eligibility_from, provinces_from: data.provinces_from, + barbarian_movement_from: data.barbarian_movement_from, home_layout: data.home_layout, state: data.state, players: Vec::new(), @@ -241,6 +244,7 @@ pub fn data(game: Game) -> GameData { great_architect_action_cost_from: game.great_architect_action_cost_from, aggressor_eligibility_from: game.aggressor_eligibility_from, provinces_from: game.provinces_from, + barbarian_movement_from: game.barbarian_movement_from, home_layout: game.home_layout, state: game.state, events: game.events, @@ -294,6 +298,7 @@ pub fn cloned_data(game: &Game) -> GameData { great_architect_action_cost_from: game.great_architect_action_cost_from, aggressor_eligibility_from: game.aggressor_eligibility_from, provinces_from: game.provinces_from, + barbarian_movement_from: game.barbarian_movement_from, home_layout: game.home_layout, state: game.state.clone(), events: game.events.clone(), diff --git a/server/src/game_setup.rs b/server/src/game_setup.rs index 9dd6cf44..2be1a8b4 100644 --- a/server/src/game_setup.rs +++ b/server/src/game_setup.rs @@ -210,6 +210,7 @@ pub fn setup_game_with_cache(setup: &GameSetup, cache: Cache) -> Game { great_architect_action_cost_from: Some(0), aggressor_eligibility_from: Some(0), provinces_from: Some(0), + barbarian_movement_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 197cede3..c544fe5d 100644 --- a/server/src/log.rs +++ b/server/src/log.rs @@ -457,6 +457,7 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) { } game.aggressor_eligibility_from.get_or_insert(next); game.provinces_from.get_or_insert(next); + game.barbarian_movement_from.get_or_insert(next); let active_events = game.events.len(); let player = game.active_player(); let origin = action_origin(&item, game.player(player)).clone(); @@ -473,6 +474,7 @@ pub(crate) fn add_log_action(game: &mut Game, item: Action) { game.aggressor_eligibility_from = game.aggressor_eligibility_from.map(|from| from.min(next)); game.provinces_from = game.provinces_from.map(|from| from.min(next)); + game.barbarian_movement_from = game.barbarian_movement_from.map(|from| from.min(next)); } let l = &mut current_turn_log_mut(game).actions; remove_redo_actions(l, i); diff --git a/server/src/replay.rs b/server/src/replay.rs index 87bafb74..48bf3805 100644 --- a/server/src/replay.rs +++ b/server/src/replay.rs @@ -22,6 +22,8 @@ pub struct ReplayGameData { aggressor_eligibility_from: Option, #[serde(default, skip_serializing_if = "Option::is_none")] provinces_from: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + barbarian_movement_from: Option, #[serde(default, skip_serializing_if = "crate::map::HomeLayout::is_legacy")] home_layout: crate::map::HomeLayout, log: Vec, @@ -152,6 +154,10 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { data.provinces_from .unwrap_or(actions.len().saturating_add(1)), ); + game.barbarian_movement_from = Some( + data.barbarian_movement_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. @@ -227,6 +233,9 @@ pub fn replay(data: ReplayGameData, to: Option) -> Result { game.provinces_from = game .provinces_from .map(|from| from.min(to.saturating_add(1))); + game.barbarian_movement_from = game + .barbarian_movement_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 ad4682d8..058b7f46 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; 12] = [ +const IGNORE_PATHS: [&str; 13] = [ "/calendar_knowledge", "/log/", "/log_index", @@ -21,6 +21,7 @@ const IGNORE_PATHS: [&str; 12] = [ "/great_architect_action_cost_from", "/aggressor_eligibility_from", "/provinces_from", + "/barbarian_movement_from", ]; pub(crate) fn clean_patch(mut patch: Vec) -> Vec { diff --git a/server/tests/architect_replay_tests.rs b/server/tests/architect_replay_tests.rs index 59b4df0d..3de6d06b 100644 --- a/server/tests/architect_replay_tests.rs +++ b/server/tests/architect_replay_tests.rs @@ -132,6 +132,30 @@ fn independent_provinces_boundary_survives_full_partial_and_new_history_replay() } } +#[test] +fn independent_barbarian_movement_boundary_survives_full_partial_and_new_history_replay() { + let fixture = fixture(); + let before = fixture["before"].as_u64().unwrap() as usize; + for boundary in [0, before, before + 4] { + let mut history = fixture["history"].clone(); + history["barbarian_movement_from"] = json!(boundary); + let partial = replay( + serde_json::from_value(history.clone()).unwrap(), + Some(before), + ) + .unwrap(); + assert_eq!( + partial.barbarian_movement_from, + Some(boundary.min(before + 1)) + ); + let full = replay(serde_json::from_value(history).unwrap(), None).unwrap(); + assert_eq!(full.barbarian_movement_from, Some(boundary)); + let saved = serde_json::to_value(full.cloned_data()).unwrap(); + let replayed = replay(serde_json::from_value(saved).unwrap(), None).unwrap(); + assert_eq!(replayed.barbarian_movement_from, Some(boundary)); + } +} + #[test] fn architect_redo_keeps_recorded_cost_policy_but_replacing_future_charges() { let fixture = fixture(); diff --git a/server/tests/barbarian_movement_tests.rs b/server/tests/barbarian_movement_tests.rs new file mode 100644 index 00000000..73da9bca --- /dev/null +++ b/server/tests/barbarian_movement_tests.rs @@ -0,0 +1,397 @@ +use server::action::Action; +use server::advance::Advance; +use server::barbarians::get_barbarians_player; +use server::cache::Cache; +use server::city::City; +use server::content::persistent_events::{ + EventResponse, PersistentEventRequest, PersistentEventType, +}; +use server::game::{Game, GameContext}; +use server::game_api; +use server::game_data::GameData; +use server::playing_actions::PlayingAction; +use server::position::Position; +use server::resource_pile::ResourcePile; +use server::unit::{Unit, UnitType}; + +fn load_game(json: &str, boundary: Option) -> Game { + let data: GameData = serde_json::from_str(json).expect("valid fixture"); + let cache = Cache::new(&data.options); + let mut game = Game::from_data(data, cache, GameContext::Play); + game.barbarian_movement_from = boundary; + game +} + +fn reload(game: &Game) -> Game { + let json = serde_json::to_string(&game.cloned_data()).expect("serialize game"); + let data: GameData = serde_json::from_str(&json).expect("deserialize game"); + let cache = Cache::new(&data.options); + Game::from_data(data, cache, GameContext::Play) +} + +fn add_barbarian_unit(game: &mut Game, pos: Position, unit_type: UnitType) -> u32 { + let barb = get_barbarians_player(game).index; + let id = game.players[barb].next_unit_id; + game.players[barb].next_unit_id += 1; + game.players[barb] + .units + .push(Unit::new(barb, pos, unit_type, id)); + id +} + +fn respond(game: Game, response: EventResponse) -> Game { + let player = game.active_player(); + game_api::execute(game, Action::Response(response), player) +} + +fn last_action_logs(game: &Game) -> Vec { + game.log + .last() + .unwrap() + .rounds + .last() + .unwrap() + .turns + .last() + .unwrap() + .actions + .last() + .unwrap() + .items + .iter() + .filter_map(|item| match &item.entry { + server::log::ActionLogEntry::Text(text) => Some(text.clone()), + _ => None, + }) + .collect() +} + +fn setup_merging_barbarians(boundary: Option) -> (Game, u32, u32) { + let mut game = load_game( + include_str!("test_games/incidents/barbarians_move.json"), + boundary, + ); + let a3 = Position::from_offset("A3"); + let b2 = Position::from_offset("B2"); + let c2 = Position::from_offset("C2"); + // Remove P1's Sulla so StopBarbarianMovement does not interrupt the incident. + game.players[1].units.clear(); + // Keep P0's two cities (A1, C2) as plain size-1 cities (no Fortress) so Storage triggers + // incident #28 (Barbarians move) and B2 -> C2 captures C2 cleanly without combat. + // In Odd-Q coordinates, B2 is distance 1 from C2 (and distance 2 from A1), + // and A3 is distance 2 from C2 via B2 alone. + let a1 = Position::from_offset("A1"); + game.players[0].cities = vec![City::new(0, a1), City::new(0, c2)]; + game.players[0] + .units + .retain(|u| u.position != c2 && u.position != b2); + let barb = get_barbarians_player(&game).index; + game.players[barb].cities.clear(); + game.players[barb].units.clear(); + let cav_id = add_barbarian_unit(&mut game, a3, UnitType::Cavalry); + let inf_id = add_barbarian_unit(&mut game, b2, UnitType::Infantry); + (game, cav_id, inf_id) +} + +#[test] +fn merging_barbarian_armies_only_moves_unmoved_units_and_leaves_already_moved_behind() { + let a3 = Position::from_offset("A3"); + let b2 = Position::from_offset("B2"); + let c2 = Position::from_offset("C2"); + + // Corrected behavior (new game boundary = Some(0)): + let (game, cav_id, inf_id) = setup_merging_barbarians(Some(0)); + let mut game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + // Both A3 and B2 are movable; select A3 first. + // A3 has only destination B2 (auto-moves A3 -> B2), then B2 has only unmoved Infantry + // and only destination C2 (auto-moves B2 -> C2). + game = respond(game, EventResponse::SelectPositions(vec![a3])); + let barb = get_barbarians_player(&game); + assert_eq!( + barb.get_units(b2).iter().map(|u| u.id).collect::>(), + vec![cav_id], + "already-moved Cavalry must remain at intermediate tile B2" + ); + assert_eq!( + barb.get_units(c2).iter().map(|u| u.id).collect::>(), + vec![inf_id], + "only unmoved Infantry should advance from B2 to C2" + ); + let logs = last_action_logs(&game); + assert!( + logs.iter() + .any(|l| l.contains("Barbarians move from B2 to C2: 1 infantry")), + "expected B2 -> C2 move log to list only 1 infantry, got: {logs:?}" + ); + assert!( + !logs + .iter() + .any(|l| l.contains("B2 to C2") && l.contains("cavalry")), + "B2 -> C2 move log must not mention already-moved cavalry: {logs:?}" + ); + + // Legacy boundary preserves historical double-move for deterministic replay of old games. + let (legacy, cav_id, inf_id) = setup_merging_barbarians(Some(usize::MAX)); + let mut legacy = respond(legacy, EventResponse::SelectAdvance(Advance::Storage)); + legacy = respond(legacy, EventResponse::SelectPositions(vec![a3])); + let barb = get_barbarians_player(&legacy); + assert!(barb.get_units(b2).is_empty()); + let mut c2_ids: Vec = barb.get_units(c2).iter().map(|u| u.id).collect(); + c2_ids.sort(); + assert_eq!(c2_ids, vec![cav_id, inf_id]); +} + +#[test] +fn merging_barbarian_armies_combat_attackers_exclude_already_moved_units() { + let a3 = Position::from_offset("A3"); + let b2 = Position::from_offset("B2"); + let c2 = Position::from_offset("C2"); + + let (mut game, cav_id, inf_id) = setup_merging_barbarians(Some(0)); + // Put a defending unit in C2 so B2 -> C2 starts combat. + let defender_id = game.players[0].next_unit_id; + game.players[0].next_unit_id += 1; + game.players[0] + .units + .push(Unit::new(0, c2, UnitType::Infantry, defender_id)); + + let mut game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + game = respond(game, EventResponse::SelectPositions(vec![a3])); + + // Combat at C2 must only have inf_id as attacker (cav_id stayed at B2). + let barb = get_barbarians_player(&game); + assert_eq!( + barb.get_units(b2).iter().map(|u| u.id).collect::>(), + vec![cav_id] + ); + if let Some(combat) = game.events.iter().find_map(|e| match &e.event_type { + PersistentEventType::CombatStart(c) => Some(c), + _ => None, + }) { + assert_eq!(combat.attackers, vec![inf_id]); + } +} + +#[test] +fn stopped_barbarian_units_in_moved_units_do_not_move_with_unmoved_units_on_same_tile() { + let b1 = Position::from_offset("B1"); + let b2 = Position::from_offset("B2"); + let c2 = Position::from_offset("C2"); + + let mut game = load_game( + include_str!("test_games/incidents/barbarians_move.json"), + Some(0), + ); + game.players[1].units.clear(); + // Place P0's two cities at B1 and C2 (both range 1 from B2), so B2 pauses for destination. + game.players[0].cities = vec![City::new(0, b1), City::new(0, c2)]; + game.players[0].units.clear(); + let barb = get_barbarians_player(&game).index; + game.players[barb].cities.clear(); + game.players[barb].units.clear(); + let stopped_cav = add_barbarian_unit(&mut game, b2, UnitType::Cavalry); + let active_inf = add_barbarian_unit(&mut game, b2, UnitType::Infantry); + + let mut game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + // Mark stopped_cav as already stopped in state.moved_units while active_inf remains unmoved. + for event in &mut game.events { + if let PersistentEventType::Incident(i) = &mut event.event_type + && let Some(state) = &mut i.barbarians + { + state.moved_units.push(stopped_cav); + } + } + // B2 is paused waiting for destination choice (B1 or C2); pick C2. + game = respond(game, EventResponse::SelectPositions(vec![c2])); + + let barb = get_barbarians_player(&game); + assert_eq!( + barb.get_units(b2).iter().map(|u| u.id).collect::>(), + vec![stopped_cav], + "stopped unit in moved_units must remain at B2" + ); + assert_eq!( + barb.get_units(c2).iter().map(|u| u.id).collect::>(), + vec![active_inf], + "unmoved unit must advance to C2" + ); +} + +#[test] +fn barbarian_move_incident_enforces_stack_limit_in_destination_choices() { + let a1 = Position::from_offset("A1"); + let b1 = Position::from_offset("B1"); + let b2 = Position::from_offset("B2"); + let c1 = Position::from_offset("C1"); + let c2 = Position::from_offset("C2"); + + let mut game = load_game( + include_str!("test_games/incidents/barbarians_move.json"), + Some(0), + ); + game.players[1].units.clear(); + game.players[1].cities.clear(); + // P0 has 2 cities (A1, C1); B2 is range 2 from C1 via land steps B1 and C2. + game.players[0].cities = vec![City::new(0, a1), City::new(0, c1)]; + game.players[0].units.clear(); + let barb = get_barbarians_player(&game).index; + game.players[barb].cities.clear(); + game.players[barb].units.clear(); + // 2 units on B2, 3 on B1 (2+3=5 > 4 -> invalid), 2 on C2 (2+2=4 -> valid). + add_barbarian_unit(&mut game, b2, UnitType::Cavalry); + add_barbarian_unit(&mut game, b2, UnitType::Cavalry); + for _ in 0..3 { + add_barbarian_unit(&mut game, b1, UnitType::Infantry); + } + for _ in 0..2 { + add_barbarian_unit(&mut game, c2, UnitType::Infantry); + } + + // Trigger incident #28; B2, B1, C2 are all movable (B1/C2 are range 1 from C1/A1). + let mut game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + // Choose B2 to move first. Because B1 would overflow STACK_LIMIT (5 > 4), + // C2 is the ONLY legal destination for B2, so B2 moves automatically to C2! + game = respond(game, EventResponse::SelectPositions(vec![b2])); + + let barb = get_barbarians_player(&game); + assert_eq!(barb.get_units(b2).len(), 0); + assert_eq!( + barb.get_units(c2).len(), + 4, + "B2's 2 Cavalry must merge onto C2 (total 4), never overflowing B1" + ); + assert_eq!(barb.get_units(b1).len(), 3); +} + +#[test] +fn mercenaries_moving_first_army_onto_second_does_not_move_first_army_twice_and_survives_reload() { + let a3 = Position::from_offset("A3"); + let b2 = Position::from_offset("B2"); + let b3 = Position::from_offset("B3"); + + // Set up Mercenaries with 2 Cavalry at A3, 2 Infantry at B3, 2 Elephants at B2. + let setup_merc = |boundary: Option| { + let mut game = load_game( + include_str!("test_games/action_cards/mercenaries.json"), + boundary, + ); + game.players[1].units.clear(); + game.players[0].units.retain(|u| u.position != b2); + let barb = get_barbarians_player(&game).index; + game.players[barb].cities.clear(); + game.players[barb].units.clear(); + let cav1 = add_barbarian_unit(&mut game, a3, UnitType::Cavalry); + let cav2 = add_barbarian_unit(&mut game, a3, UnitType::Cavalry); + let inf1 = add_barbarian_unit(&mut game, b3, UnitType::Infantry); + let inf2 = add_barbarian_unit(&mut game, b3, UnitType::Infantry); + let ele1 = add_barbarian_unit(&mut game, b2, UnitType::Elephant); + let ele2 = add_barbarian_unit(&mut game, b2, UnitType::Elephant); + (game, [cav1, cav2], [inf1, inf2], [ele1, ele2]) + }; + + // Corrected behavior: + let (game, cavs, infs, eles) = setup_merc(Some(0)); + let mut game = game_api::execute(game, Action::Playing(PlayingAction::ActionCard(13)), 0); + // Select A3 and B3. + game = respond(game, EventResponse::SelectPositions(vec![a3, b3])); + // Pay 2 ore. + game = respond(game, EventResponse::Payment(vec![ResourcePile::ore(2)])); + // Pick A3 first, move onto B3 (merging 2 Cavalry onto 2 Infantry -> 4 on B3). + game = respond(game, EventResponse::SelectPositions(vec![a3])); + game = respond(game, EventResponse::SelectPositions(vec![b3])); + // Save & reload mid-Mercenaries to verify moved_units persists across serialization! + game = reload(&game); + // Next prompt must be selecting destination for B3 (auto-selected as sole remaining army), + // and B2 MUST be an allowed destination because only B3's 2 unmoved Infantry move (2 + 2 <= 4). + let choices = match &game.current_event_handler().unwrap().request { + PersistentEventRequest::SelectPositions(r) => r.choices.clone(), + other => panic!("expected SelectPositions for B3 destination, got {other:?}"), + }; + assert!( + choices.contains(&b2), + "B2 must be legal for B3's 2 unmoved Infantry (2+2<=4), choices: {choices:?}" + ); + assert!(choices.contains(&a3)); + game = respond(game, EventResponse::SelectPositions(vec![b2])); + assert!(game.events.is_empty()); + + let barb = get_barbarians_player(&game); + let mut b3_ids: Vec = barb.get_units(b3).iter().map(|u| u.id).collect(); + b3_ids.sort(); + assert_eq!( + b3_ids, + cavs.to_vec(), + "already-moved Cavalry must remain on B3" + ); + let mut b2_ids: Vec = barb.get_units(b2).iter().map(|u| u.id).collect(); + b2_ids.sort(); + let mut expected_b2 = vec![infs[0], infs[1], eles[0], eles[1]]; + expected_b2.sort(); + assert_eq!( + b2_ids, expected_b2, + "only B3's unmoved Infantry should join B2's Elephants" + ); + + // Legacy boundary preserves legacy Mercenaries behavior (moves all 4 units on B3 to A3, + // excluding B2 because 4 + 2 > 4 -> A3 is auto-selected as the sole destination!). + let (legacy, _cavs, _infs, _eles) = setup_merc(Some(usize::MAX)); + let mut legacy = game_api::execute(legacy, Action::Playing(PlayingAction::ActionCard(13)), 0); + legacy = respond(legacy, EventResponse::SelectPositions(vec![a3, b3])); + legacy = respond(legacy, EventResponse::Payment(vec![ResourcePile::ore(2)])); + legacy = respond(legacy, EventResponse::SelectPositions(vec![a3])); + legacy = respond(legacy, EventResponse::SelectPositions(vec![b3])); + let barb = get_barbarians_player(&legacy); + assert!(barb.get_units(b3).is_empty()); + assert_eq!(barb.get_units(a3).len(), 4); +} + +#[test] +fn barbarian_movement_boundary_upgrade_undo_redo_and_branch() { + let a3 = Position::from_offset("A3"); + let b2 = Position::from_offset("B2"); + let c2 = Position::from_offset("C2"); + + // Upgraded save (barbarian_movement_from: None) enables corrected movement on next action. + let (game, cav_id, inf_id) = setup_merging_barbarians(None); + assert_eq!(game.barbarian_movement_from, None); + let expected_boundary = game_api::log_length(&game) + 1; + let game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + assert_eq!(game.barbarian_movement_from, Some(expected_boundary)); + let after_move = respond(game, EventResponse::SelectPositions(vec![a3])); + assert_eq!(after_move.barbarian_movement_from, Some(expected_boundary)); + let barb = get_barbarians_player(&after_move); + assert_eq!( + barb.get_units(b2).iter().map(|u| u.id).collect::>(), + vec![cav_id] + ); + assert_eq!( + barb.get_units(c2).iter().map(|u| u.id).collect::>(), + vec![inf_id] + ); + + // Undo and redo preserve the boundary. + let undone = game_api::execute(after_move, Action::Undo, 0); + assert_eq!(undone.barbarian_movement_from, Some(expected_boundary)); + let redone = game_api::execute(undone, Action::Redo, 0); + assert_eq!(redone.barbarian_movement_from, Some(expected_boundary)); + assert_eq!( + get_barbarians_player(&redone) + .get_units(b2) + .iter() + .map(|u| u.id) + .collect::>(), + vec![cav_id] + ); + + // Branching after undo clamps a future legacy boundary to the new branch action. + let (game, _, _) = setup_merging_barbarians(Some(usize::MAX)); + let game = respond(game, EventResponse::SelectAdvance(Advance::Storage)); + let game = respond(game, EventResponse::SelectPositions(vec![a3])); + assert_eq!(game.barbarian_movement_from, Some(usize::MAX)); + let undone = game_api::execute(game, Action::Undo, 0); + assert_eq!(undone.barbarian_movement_from, Some(usize::MAX)); + // Branch by choosing B2 first instead of redoing A3. + let branch_boundary = game_api::log_length(&undone) + 1; + let branched = respond(undone, EventResponse::SelectPositions(vec![b2])); + assert_eq!(branched.barbarian_movement_from, Some(branch_boundary)); +} diff --git a/server/tests/common/mod.rs b/server/tests/common/mod.rs index bbfb22b5..d371c01b 100644 --- a/server/tests/common/mod.rs +++ b/server/tests/common/mod.rs @@ -161,6 +161,12 @@ fn clean_json(expected: &str) -> String { if value["provinces_from"] == serde_json::json!(usize::MAX) { value.as_object_mut().unwrap().remove("provinces_from"); } + if value["barbarian_movement_from"] == serde_json::json!(usize::MAX) { + value + .as_object_mut() + .unwrap() + .remove("barbarian_movement_from"); + } // Only public action-log items qualify, never arbitrary arrays or game state. if let Some(ages) = value .get_mut("log") @@ -499,6 +505,9 @@ pub fn load_game(path: &GamePath) -> Game { if game.provinces_from.is_none() { game.provinces_from = Some(usize::MAX); } + if game.barbarian_movement_from.is_none() { + game.barbarian_movement_from = Some(usize::MAX); + } if update_expected() { write_result(&to_json(&game), path); } diff --git a/server/tests/test_games/base/new_game.json b/server/tests/test_games/base/new_game.json index 6a1b015f..80a4aa1a 100644 --- a/server/tests/test_games/base/new_game.json +++ b/server/tests/test_games/base/new_game.json @@ -8,6 +8,7 @@ "great_architect_action_cost_from": 0, "aggressor_eligibility_from": 0, "provinces_from": 0, + "barbarian_movement_from": 0, "home_layout": "ClockwiseV1", "state": "ChooseCivilization", "players": [ diff --git a/web-client/package.json b/web-client/package.json index 857a8cc9..5fc90c86 100644 --- a/web-client/package.json +++ b/web-client/package.json @@ -7,7 +7,7 @@ "dev": "vite --host 127.0.0.1 --port 8643", "build": "vite build", "check": "svelte-check --tsconfig ./tsconfig.json", - "test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs ../scripts/withdrawal.test.cjs ../scripts/viking-cargo.test.cjs ../scripts/aggressor.test.cjs ../scripts/great-architect.test.cjs ../scripts/provinces.test.cjs", + "test": "node --experimental-strip-types --test src/*.test.ts && node --test scripts/publish-gallery.test.mjs scripts/boarding.test.mjs scripts/raiders.test.mjs && npm run test:achievement-assets && npm run test:locales && node scripts/exhausted-movement-check.mjs && CLASH_WASM=\"$PWD/.engine/server.js\" node --test ../scripts/status-phase-battle.test.cjs ../scripts/postcombat-queue.test.cjs ../scripts/tributes.test.cjs ../scripts/withdrawal.test.cjs ../scripts/viking-cargo.test.cjs ../scripts/aggressor.test.cjs ../scripts/great-architect.test.cjs ../scripts/provinces.test.cjs ../scripts/barbarian-movement.test.cjs", "test:boarding": "npm run build:bridge && npm run build && node --test scripts/boarding.test.mjs && node scripts/boarding-smoke.mjs", "test:home-orientation": "npm run build && node scripts/home-orientation-smoke.mjs", "build:achievement-assets": "node scripts/build-achievement-assets.mjs", diff --git a/web-client/src/prediction.test.ts b/web-client/src/prediction.test.ts index 9abbdd63..d9a9c5cb 100644 --- a/web-client/src/prediction.test.ts +++ b/web-client/src/prediction.test.ts @@ -956,6 +956,7 @@ test('predicted undo preserves all independent persisted rule boundaries', () => great_architect_action_cost_from: 5, aggressor_eligibility_from: 1, provinces_from: 1, + barbarian_movement_from: 2, }; const current = { ...previous, diff --git a/web-client/src/prediction.ts b/web-client/src/prediction.ts index 9d22fd69..04d0bace 100644 --- a/web-client/src/prediction.ts +++ b/web-client/src/prediction.ts @@ -201,6 +201,7 @@ export function predictUndo(previous: string, current: string): string | null { 'great_architect_action_cost_from', 'aggressor_eligibility_from', 'provinces_from', + 'barbarian_movement_from', ]) { if (after[field] !== undefined) before[field] = after[field]; else delete before[field];