Fix Great Wall and Celtic recruitment/spawning; release engine 0.4.127

This commit is contained in:
coyotte508 2026-11-02 16:55:46 +00:00
commit 51282aca11
15 changed files with 1555 additions and 36 deletions

View file

@ -25,6 +25,10 @@ use serde::{Deserialize, Serialize};
#[path = "barbarians_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "barbarians_spawn_tests.rs"]
mod spawn_tests;
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
pub struct BarbariansMoveRequest {
pub from: Position,
@ -619,7 +623,9 @@ fn is_base_barbarian_spawn_pos(game: &Game, pos: Position, player: &Player) -> b
game.map.get(pos).is_some_and(|t| {
t.is_land() && !matches!(t, Terrain::Barren) && !matches!(t, Terrain::Exhausted(_))
}) && !anything_present(game, pos)
&& cities_in_land_range(game, |p| p.index != player.index, pos, 1).is_empty()
// "Other players' cities" excludes game-controlled Barbarian settlements.
&& cities_in_land_range(game, |p| p.is_human() && p.index != player.index, pos, 1)
.is_empty()
}
fn anything_present(game: &Game, pos: Position) -> bool {

View file

@ -0,0 +1,263 @@
use super::*;
use crate::action::{Action, execute_action};
use crate::advance::{Advance, AdvanceAction};
use crate::cache::Cache;
use crate::content::custom_actions::{CustomAction, CustomActionType};
use crate::content::persistent_events::{EventResponse, PersistentEventRequest};
use crate::game::GameContext;
use crate::game_data::GameData;
use crate::playing_actions::PlayingAction;
use crate::unit::Unit;
use crate::web_view;
use serde_json::json;
fn pos(value: &str) -> Position {
Position::from_offset(value)
}
fn positions(values: &[&str]) -> Vec<Position> {
values.iter().map(|v| pos(v)).collect()
}
fn fixture() -> Game {
// Sanitized public board at history cursor 173 of the reported Celts/Maya game.
// Only terrain, cities, and units are restored; this is NOT a full historical
// save. Advances/resources/log/deck are synthetic, with player 0 and one action
// left so the reported Tribal Allies placement can be exercised directly.
// No names, hidden hands, source log, or history are retained in the fixture.
let data: GameData = serde_json::from_str(include_str!(
"../tests/fixtures/tribal_allies_public_board.json"
))
.unwrap();
let cache = Cache::new(&data.options);
Game::from_data(data, cache, GameContext::Play)
}
fn choices(game: &Game) -> Vec<Position> {
let mut result = possible_barbarians_spawns(game, game.player(0));
result.sort();
result
}
fn placement_choices(game: &Game) -> Vec<Position> {
let PersistentEventRequest::SelectPositions(request) =
&game.current_event_handler().unwrap().request
else {
panic!("expected Barbarian placement decision");
};
assert_eq!(request.needed, 1..=1);
let mut result = request.choices.clone();
result.sort();
result
}
fn tribal_allies(game: Game) -> Game {
execute_action(
game,
Action::Playing(PlayingAction::Custom(CustomAction::new(
CustomActionType::TribalAllies,
None,
))),
0,
)
}
fn choose(game: Game, response: EventResponse) -> Game {
execute_action(game, Action::Response(response), 0)
}
fn place_and_reinforce(game: Game, target: Position) -> Game {
let game = choose(game, EventResponse::SelectPositions(vec![target]));
let barbarian = get_barbarians_player(&game);
assert!(barbarian.cities.iter().any(|c| c.position == target));
assert_eq!(barbarian.get_units(target).len(), 1);
assert_eq!(barbarian.get_units(target)[0].unit_type, UnitType::Infantry);
assert!(placement_choices(&game).contains(&target));
let game = choose(game, EventResponse::SelectPositions(vec![target]));
let game = choose(game, EventResponse::SelectUnitType(UnitType::Cavalry));
assert!(game.events.is_empty());
assert_eq!(
get_barbarians_player(&game)
.get_units(target)
.iter()
.map(|u| u.unit_type)
.collect::<Vec<_>>(),
vec![UnitType::Infantry, UnitType::Cavalry]
);
game
}
#[test]
fn reported_board_allows_npc_neighbors_but_not_other_human_city_neighbors() {
let game = fixture();
assert_eq!(game.map.get(pos("B4")), Some(&Terrain::Fertile));
for (target, settlement) in [("B4", "A5"), ("C3", "D3")] {
assert_eq!(pos(target).distance(pos(settlement)), 1);
assert!(!anything_present(&game, pos(target)));
assert!(
get_barbarians_player(&game)
.cities
.iter()
.any(|c| c.position == pos(settlement))
);
}
assert_eq!(pos("C5").distance(pos("C6")), 1);
assert!(!anything_present(&game, pos("C5")));
assert!(
game.player(1)
.cities
.iter()
.any(|c| c.position == pos("C6"))
);
assert!(
game.map.tiles.keys().all(|&p| {
!is_base_barbarian_spawn_pos(&game, p, game.player(0))
|| !cities_in_land_range(&game, |p| p.index == 0, p, 1).is_empty()
|| steps_towards_land_range2_cites(&game, game.player(0), p).is_empty()
}),
"this board must exercise the adjacent fallback, not distance-two priority"
);
assert_eq!(choices(&game), positions(&["B4", "C2", "C3", "E2"]));
}
#[test]
fn tribal_allies_offers_and_places_both_previously_excluded_tiles_after_reload() {
for target in [pos("B4"), pos("C3")] {
let game = fixture();
let resources = game.player(0).resources.clone();
let game = tribal_allies(game);
assert_eq!(
placement_choices(&game),
positions(&["B4", "C2", "C3", "E2"])
);
// The real web decision query accepts the new choices, but not the empty
// plains at C5 bordering the other human's C6 city.
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":[target]})).is_ok());
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":["C5"]})).is_err());
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
let game = place_and_reinforce(game, target);
assert_eq!(game.actions_left, 0);
assert_eq!(game.player(0).resources, resources);
}
}
#[test]
fn ordinary_incident_uses_the_same_spawn_choices_and_placement_rules() {
let game = execute_action(
fixture(),
Action::Playing(PlayingAction::Advance(AdvanceAction::new(
Advance::Storage,
ResourcePile::ideas(2),
))),
0,
);
assert!(matches!(
game.current_event().event_type,
PersistentEventType::Incident(_)
));
assert_eq!(
placement_choices(&game),
placement_choices(&tribal_allies(fixture()))
);
assert_eq!(
placement_choices(&game),
positions(&["B4", "C2", "C3", "E2"])
);
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":["C5"]})).is_err());
let game = place_and_reinforce(game, pos("B4"));
assert_eq!(game.actions_left, 0);
}
#[test]
fn fortresses_neither_block_fallback_nor_enable_spawning_next_to_other_humans() {
for own_fortress in [false, true] {
for other_fortress in [false, true] {
let mut game = fixture();
game.player_mut(0).get_city_mut(pos("C4")).pieces.fortress = own_fortress.then_some(0);
game.player_mut(1).get_city_mut(pos("C6")).pieces.fortress =
other_fortress.then_some(1);
assert_eq!(choices(&game), positions(&["B4", "C2", "C3", "E2"]));
assert_eq!(
placement_choices(&tribal_allies(game)),
positions(&["B4", "C2", "C3", "E2"])
);
}
}
}
#[test]
fn distance_two_has_priority_even_next_to_barbarians_and_falls_back_when_blocked() {
let mut game = fixture();
// B1 is two land steps from D2 via C2, but is not adjacent to any own city.
game.map.tiles.insert(pos("B1"), Terrain::Fertile);
game.map.tiles.insert(pos("A1"), Terrain::Fertile);
let barbarian = get_barbarians_player(&game).index;
game.player_mut(barbarian)
.cities
.push(City::new(barbarian, pos("A1")));
assert_eq!(pos("B1").distance(pos("D2")), 2);
assert_eq!(pos("B1").distance(pos("A1")), 1);
assert_eq!(choices(&game), positions(&["B1"]));
// Same geometry, but a human city must disqualify B1 and restore fallback.
game.player_mut(barbarian)
.cities
.retain(|c| c.position != pos("A1"));
game.player_mut(1).cities.push(City::new(1, pos("A1")));
assert_eq!(choices(&game), positions(&["B4", "C2", "C3", "E2"]));
}
#[test]
fn distance_two_still_requires_a_land_path() {
let mut game = fixture();
game.map.tiles.insert(pos("B1"), Terrain::Fertile);
assert_eq!(choices(&game), positions(&["B1"]));
game.map.tiles.insert(pos("C2"), Terrain::Water);
assert!(steps_towards_land_range2_cites(&game, game.player(0), pos("B1")).is_empty());
assert_eq!(choices(&game), positions(&["B4", "C3", "E2"]));
}
#[test]
fn spawn_destination_still_excludes_cities_and_units_of_every_faction() {
let target = pos("B4");
for player in 0..fixture().players.len() {
let mut game = fixture();
assert!(choices(&game).contains(&target));
let owner = game.player_mut(player);
owner.units.push(Unit::new(
player,
target,
UnitType::Settler,
owner.next_unit_id,
));
assert!(!choices(&game).contains(&target), "unit owner {player}");
let mut game = fixture();
game.player_mut(player)
.cities
.push(City::new(player, target));
assert!(!choices(&game).contains(&target), "city owner {player}");
}
}
#[test]
fn spawn_destination_still_requires_revealed_non_barren_non_exhausted_land() {
let target = pos("B4");
for (terrain, allowed) in [
(Terrain::Fertile, true),
(Terrain::Forest, true),
(Terrain::Mountain, true),
(Terrain::Barren, false),
(Terrain::Water, false),
(Terrain::Unexplored, false),
(Terrain::Exhausted(Box::new(Terrain::Fertile)), false),
(Terrain::Exhausted(Box::new(Terrain::Forest)), false),
(Terrain::Exhausted(Box::new(Terrain::Mountain)), false),
] {
let mut game = fixture();
game.map.tiles.insert(target, terrain);
assert_eq!(choices(&game).contains(&target), allowed);
}
let mut game = fixture();
game.map.tiles.remove(&target);
assert!(!choices(&game).contains(&target));
}

View file

@ -18,11 +18,11 @@ use crate::content::persistent_events::{
use crate::game::Game;
use crate::leader::{Leader, LeaderInfo, leader_position};
use crate::leader_ability::{LeaderAbility, LeaderAbilityBuilder};
use crate::player::gain_unit;
use crate::player::{Player, can_add_army_unit, gain_unit};
use crate::position::Position;
use crate::resource_pile::ResourcePile;
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo, SpecialAdvanceRequirement};
use crate::unit::{UnitType, set_unit_position};
use crate::unit::{UnitType, Units, set_unit_position};
use crate::victory_points::{SpecialVictoryPoints, VictoryPointAttribution};
pub(crate) fn celts() -> Civilization {
@ -224,6 +224,42 @@ fn viriatus() -> LeaderInfo {
}
}).build())
}
fn rapid_recruitment_neighbors(game: &Game, player: usize, city: Position) -> Vec<Position> {
city.neighbors()
.into_iter()
.filter(|pos| game.map.is_land(*pos) && game.enemy_player(player, *pos).is_none())
.collect()
}
/// Extra placement capacity, not a larger stack in the recruiting city. The
/// printed card allows direct deployment, so only the final stacks must fit.
/// A newly recruited/replacement leader cannot provide the post-recruit ability.
pub(crate) fn rapid_recruitment_capacity(
game: &Game,
player: &Player,
units: &Units,
city: Position,
) -> usize {
if units.leader.is_some()
|| player.active_leader() != Some(Leader::Vercingetorix)
|| leader_position(player) != city
{
return 0;
}
rapid_recruitment_neighbors(game, player.index, city)
.into_iter()
.map(|pos| {
crate::content::civilizations::persia::stack_limit(player, pos).saturating_sub(
player
.get_units(pos)
.iter()
.filter(|u| u.is_army_unit())
.count(),
)
})
.sum()
}
fn rapid_recruitment(mut b: LeaderAbilityBuilder) -> LeaderAbilityBuilder {
for i in 0..8u32 {
b = b.add_position_request(
@ -244,20 +280,35 @@ fn rapid_recruitment(mut b: LeaderAbilityBuilder) -> LeaderAbilityBuilder {
.iter()
.filter(|u| u.id >= first && !u.is_ship())
.nth(i as usize)?;
let choices = r
.city_position
.neighbors()
let player = p.get(game);
let choices = rapid_recruitment_neighbors(game, p.index, r.city_position)
.into_iter()
.filter(|pos| {
game.map.is_land(*pos)
&& game.enemy_player(p.index, *pos).is_none()
&& (!unit.is_army_unit()
|| crate::player::can_add_army_unit(p.get(game), *pos))
})
.filter(|pos| !unit.is_army_unit() || can_add_army_unit(player, *pos))
.collect();
// New units are staged in the city while placement is pending.
// Keeping this one is legal only if the remaining recruits can
// still remove all overflow; previously kept units stay put.
let remaining_army = player
.units
.iter()
.filter(|u| u.id >= first && !u.is_ship())
.skip(i as usize + 1)
.filter(|u| u.is_army_unit())
.count();
let city_army = player
.get_units(r.city_position)
.iter()
.filter(|u| u.is_army_unit())
.count();
let must_deploy = unit.is_army_unit()
&& city_army
> crate::content::civilizations::persia::stack_limit(
player,
r.city_position,
) + remaining_army;
Some(PositionRequest::new(
choices,
0..=1,
u8::from(must_deploy)..=1,
&format!(
"Rapid Recruitment · Deploy {} #{} beside the city",
unit.unit_type.name(game),
@ -276,6 +327,8 @@ fn rapid_recruitment(mut b: LeaderAbilityBuilder) -> LeaderAbilityBuilder {
.nth(i as usize)
.unwrap()
.id;
// Placement is not movement: do not apply terrain entry
// restrictions, movement costs, or mark this unit as moved.
set_unit_position(s.player_index, id, *pos, game);
s.log(game, &format!("Deployed unit #{} at {pos}", id + 1));
}

View file

@ -60,8 +60,8 @@ fn great_wall() -> WonderInfo {
&& c.defender_city(game)
.is_some_and(|c| c.mood_state == MoodState::Happy)
{
s.defender_strength.extra_combat_value -= 2;
s.defender_strength
s.attacker_strength.extra_combat_value -= 2;
s.attacker_strength
.roll_log
.push("Great Wall gives -2 combat value in the first round".to_string());
}

View file

@ -449,19 +449,24 @@ fn recruit_cost_options_excluding(
{
return Err("Too many units".to_string());
}
let city_stack_limit = if units.leader == Some(crate::leader::Leader::Xerxes) {
5
} else {
crate::content::civilizations::persia::stack_limit(player, city_position)
};
let deployment_capacity = crate::content::civilizations::celts::rapid_recruitment_capacity(
game,
player,
units,
city_position,
);
if player
.get_units(city_position)
.iter()
.filter(|unit| unit.is_army_unit())
.count() as u8
+ units.amount()
- units.settlers
- units.ships
> if units.leader == Some(crate::leader::Leader::Xerxes) {
5
} else {
crate::content::civilizations::persia::stack_limit(player, city_position) as u8
}
.count()
+ usize::from(units.amount() - units.settlers - units.ships)
> city_stack_limit + deployment_capacity
{
return Err("Too many units in stack".to_string());
}
@ -477,5 +482,8 @@ fn recruit_cost_options_excluding(
fn is_cavalry_province_city(player: &Player, city: Position, game: &Game) -> bool {
player.has_special_advance(SpecialAdvance::Provinces)
&& game.map.revealed_distance(capital_city_position(game, player), city).is_some_and(|distance| distance >= 3)
&& game
.map
.revealed_distance(capital_city_position(game, player), city)
.is_some_and(|distance| distance >= 3)
}

View file

@ -0,0 +1,447 @@
{
"state": "Playing",
"players": [
{
"id": 0,
"civilization": "Celts",
"cities": [
{
"city_pieces": {
"temple": 0
},
"mood_state": "Happy",
"position": "D2"
},
{
"city_pieces": {
"fortress": 0
},
"mood_state": "Happy",
"activations": 1,
"position": "C4"
},
{
"mood_state": "Angry",
"position": "B3"
}
],
"units": [
{
"position": "C4",
"unit_type": "Infantry",
"movement_restrictions": [
"Forest"
],
"id": 1
},
{
"position": "C4",
"unit_type": "Infantry",
"movement_restrictions": [
"Forest"
],
"id": 2
},
{
"position": "C4",
"unit_type": {
"Leader": "Vercingetorix"
},
"id": 3
},
{
"position": "C4",
"unit_type": "Settler",
"id": 4
},
{
"position": "C4",
"unit_type": "Settler",
"id": 5
},
{
"position": "D5",
"unit_type": "Infantry",
"movement_restrictions": [
"Mountain"
],
"id": 6
},
{
"position": "C4",
"unit_type": "Settler",
"id": 7
},
{
"position": "D5",
"unit_type": "Infantry",
"movement_restrictions": [
"Mountain"
],
"id": 8
},
{
"position": "C4",
"unit_type": "Settler",
"id": 10
},
{
"position": "B3",
"unit_type": "Infantry",
"movement_restrictions": [
"Battle",
"Fertile"
],
"id": 11
},
{
"position": "C4",
"unit_type": "Infantry",
"id": 12
}
],
"next_unit_id": 13,
"advances": [
"Farming",
"Mining",
"Tactics",
"Draft"
],
"resources": {
"food": 7,
"ideas": 7
},
"resource_limit": {
"food": 7,
"ideas": 7
},
"incident_tokens": 1
},
{
"id": 1,
"civilization": "Maya",
"cities": [
{
"city_pieces": {
"academy": 1,
"market": 1
},
"mood_state": "Happy",
"position": "D7"
},
{
"city_pieces": {
"fortress": 1
},
"mood_state": "Happy",
"position": "C6"
},
{
"city_pieces": {
"academy": 1
},
"mood_state": "Happy",
"position": "E6"
}
],
"units": [
{
"position": "C6",
"unit_type": "Infantry",
"id": 2
},
{
"position": "C6",
"unit_type": "Infantry",
"id": 3
},
{
"position": "C6",
"unit_type": "Infantry",
"id": 4
},
{
"position": "C6",
"unit_type": "Infantry",
"id": 5
}
],
"next_unit_id": 6,
"advances": [
"Farming",
"Mining"
]
},
{
"id": 2,
"civilization": "Barbarians",
"cities": [
{
"mood_state": "Neutral",
"position": "D3"
},
{
"mood_state": "Neutral",
"position": "B7"
},
{
"mood_state": "Neutral",
"position": "A5"
}
],
"units": [
{
"position": "D3",
"unit_type": "Infantry",
"id": 0
},
{
"position": "D3",
"unit_type": "Infantry",
"id": 1
},
{
"position": "C8",
"unit_type": "Infantry",
"id": 2
},
{
"position": "C8",
"unit_type": "Cavalry",
"id": 4
},
{
"position": "B5",
"unit_type": "Infantry",
"id": 5
},
{
"position": "C8",
"unit_type": "Elephant",
"id": 6
},
{
"position": "B7",
"unit_type": "Infantry",
"id": 7
},
{
"position": "A5",
"unit_type": "Infantry",
"id": 8
}
],
"next_unit_id": 9
},
{
"id": 3,
"civilization": "Pirates",
"cities": [],
"units": [
{
"position": "D4",
"unit_type": "Ship",
"id": 0
},
{
"position": "B6",
"unit_type": "Ship",
"id": 1
}
],
"next_unit_id": 2
}
],
"map": {
"tiles": [
[
"A3",
"Water"
],
[
"A5",
"Fertile"
],
[
"A7",
"Barren"
],
[
"B2",
"Water"
],
[
"B3",
"Fertile"
],
[
"B4",
"Fertile"
],
[
"B5",
"Forest"
],
[
"B6",
"Water"
],
[
"B7",
"Fertile"
],
[
"C2",
"Forest"
],
[
"C3",
"Mountain"
],
[
"C4",
"Forest"
],
[
"C5",
"Fertile"
],
[
"C6",
"Fertile"
],
[
"C7",
"Forest"
],
[
"C8",
"Mountain"
],
[
"D1",
"Barren"
],
[
"D2",
"Fertile"
],
[
"D3",
"Forest"
],
[
"D4",
"Water"
],
[
"D5",
"Mountain"
],
[
"D6",
"Forest"
],
[
"D7",
"Fertile"
],
[
"D8",
"Mountain"
],
[
"E2",
"Mountain"
],
[
"E3",
"Unexplored"
],
[
"E4",
"Water"
],
[
"E5",
"Unexplored"
],
[
"E6",
"Mountain"
],
[
"E7",
"Fertile"
],
[
"E8",
"Forest"
],
[
"F2",
"Unexplored"
],
[
"F3",
"Unexplored"
],
[
"F4",
"Unexplored"
],
[
"F5",
"Unexplored"
],
[
"F6",
"Barren"
],
[
"F7",
"Fertile"
],
[
"G3",
"Unexplored"
],
[
"G5",
"Unexplored"
],
[
"G7",
"Water"
]
]
},
"starting_player_index": 0,
"current_player_index": 0,
"log": [
{
"age": 4,
"rounds": [
{
"round": 3,
"turns": [
{
"turn_type": {
"Player": 0
}
}
]
}
]
}
],
"log_index": 0,
"undo_limit": 0,
"actions_left": 1,
"round": 3,
"age": 4,
"messages": [],
"incidents_left": [
10
]
}

View file

@ -0,0 +1,150 @@
use common::{JsonTest, move_action};
use serde_json::Value;
use server::action::Action;
use server::city::MoodState;
use server::content::persistent_events::{EventResponse, PersistentEventType};
use server::game::Game;
use server::game_api::execute;
use server::position::Position;
use server::unit::UnitType;
use server::wonder::Wonder;
mod common;
const WALL_LOG: &str = "Great Wall gives -2 combat value in the first round";
fn setup() -> Game {
let mut game = JsonTest::new("wonders").load_game("great_wall");
// Two infantry on each side; 3/Elephant faces have no matching ability.
// The unmodified rolls are 6 CV each, so -2 changes the number of hits.
for player in &mut game.players[..2] {
player.action_cards.clear();
for unit in &mut player.units {
unit.unit_type = UnitType::Infantry;
}
}
game.dice_roll_outcomes = vec![4; 4];
game
}
fn attack(game: Game) -> Game {
execute(
game,
move_action(vec![0, 1], Position::from_offset("A1")),
1,
)
}
fn rolls(game: &Game) -> Vec<(usize, Value)> {
fn collect(value: &Value, result: &mut Vec<(usize, Value)>) {
if let Some(roll) = value.get("CombatRoll") {
result.push((value["player"].as_u64().unwrap() as usize, roll.clone()));
}
match value {
Value::Array(items) => items.iter().for_each(|item| collect(item, result)),
Value::Object(items) => items.values().for_each(|item| collect(item, result)),
_ => (),
}
}
let mut result = vec![];
collect(&serde_json::to_value(&game.log).unwrap(), &mut result);
result
}
fn assert_first_rolls(game: &Game, penalty: bool) {
let rolls = rolls(game);
assert_eq!(rolls.len(), 2);
for (player, roll) in rolls {
let penalized = penalty && player == 1;
assert_eq!(roll["combat_value"], if penalized { 4 } else { 6 });
assert_eq!(
roll.to_string().contains(WALL_LOG),
penalized,
"the penalty explanation belongs to the attacking player's roll"
);
}
}
#[test]
fn great_wall_penalizes_only_attacker_in_first_round_and_preserves_defender_hits() {
let game = attack(setup());
assert_first_rolls(&game, true);
assert_eq!(
game.player(1).units.len(),
1,
"defender still scores one hit"
);
assert_eq!(
game.player(0).get_units(Position::from_offset("A1")).len(),
2,
"attacker's reduced roll scores no hits"
);
let PersistentEventType::CombatRoundEnd(end) = &game.current_event().event_type else {
panic!("expected retreat decision");
};
assert_eq!(end.combat.stats.round, 1);
// Continue with low dice, ensuring the next round has no Great Wall penalty.
let mut game = game;
game.dice_roll_outcomes = vec![0; 3];
let game = execute(game, Action::Response(EventResponse::Bool(false)), 1);
let rolls = rolls(&game);
assert_eq!(rolls.len(), 4);
for (player, roll) in &rolls[2..] {
assert_eq!(roll["combat_value"], if *player == 1 { 1 } else { 2 });
assert!(!roll.to_string().contains(WALL_LOG));
}
}
#[test]
fn great_wall_does_not_apply_in_neutral_or_angry_cities() {
for mood in [MoodState::Neutral, MoodState::Angry] {
let mut game = setup();
game.player_mut(0)
.get_city_mut(Position::from_offset("A1"))
.mood_state = mood;
assert_first_rolls(&attack(game), false);
}
}
#[test]
fn great_wall_protects_other_happy_cities_not_just_its_own_city() {
let mut game = setup();
let wall_city = Position::from_offset("A1");
let other_city = Position::from_offset("C2");
// Keep the wonder owned and its listener installed, but put its model elsewhere.
game.player_mut(0)
.get_city_mut(wall_city)
.pieces
.wonders
.clear();
game.player_mut(0)
.get_city_mut(other_city)
.pieces
.wonders
.push(Wonder::GreatWall);
assert_first_rolls(&attack(game), true);
}
#[test]
fn great_wall_does_not_protect_an_army_outside_a_city() {
let mut game = setup();
game.player_mut(0)
.get_city_mut(Position::from_offset("A1"))
.position = Position::from_offset("B2");
assert_first_rolls(&attack(game), false);
}
#[test]
fn great_wall_has_no_effect_when_its_owner_attacks() {
let mut game = setup();
game.player_mut(0).cities[0].pieces.wonders.clear();
game.player_mut(1).cities[0]
.pieces
.wonders
.push(Wonder::GreatWall);
let data = game.cloned_data();
let cache = server::cache::Cache::new(&data.options);
let game = Game::from_data(data, cache, server::game::GameContext::Play);
assert_first_rolls(&attack(game), false);
}

View file

@ -339,8 +339,11 @@
"bonus": true
}
],
"combat_value": 14,
"hits": 2
"combat_value": 12,
"hits": 2,
"combat_modifiers": [
"Great Wall gives -2 combat value in the first round"
]
},
"origin": {
"Ability": "Combat"
@ -361,11 +364,8 @@
"bonus": false
}
],
"combat_value": 11,
"hits": 2,
"combat_modifiers": [
"Great Wall gives -2 combat value in the first round"
]
"combat_value": 13,
"hits": 2
},
"origin": {
"Ability": "Combat"
@ -732,4 +732,4 @@
1,
40
]
}
}

View file

@ -0,0 +1,452 @@
use serde_json::{Value, json};
use server::action::{Action, execute_action, try_execute_action};
use server::cache::Cache;
use server::city::{City, MoodState};
use server::content::persistent_events::{EventResponse, PersistentEventRequest};
use server::game::{Game, GameContext, GameState};
use server::game_data::GameData;
use server::leader::Leader;
use server::map::Terrain;
use server::movement::{MoveUnits, MovementAction, MovementRestriction, possible_move_routes};
use server::player::CostTrigger;
use server::playing_actions::PlayingAction;
use server::position::Position;
use server::recruit::{Recruit, recruit_cost_without_replaced};
use server::resource_pile::ResourcePile;
use server::unit::{Unit, UnitType, Units};
use server::web_view;
fn city() -> Position {
Position::from_offset("C3")
}
fn fixture() -> Game {
let mut data: Value =
serde_json::from_str(include_str!("test_games/base/recruit.json")).unwrap();
let p = &mut data["players"][0];
p["civilization"] = json!("Celts");
p["advances"] = json!(["Farming", "Mining", "Tactics"]);
p["available_leaders"] = json!(["Viriatus", "Boudica"]);
p["cities"] = json!([{
"position": city(), "mood_state": "Neutral",
"city_pieces": {"academy": 0, "fortress": 0, "temple": 0}
}]);
p["units"] = json!([
{"id": 0, "position": city(), "unit_type": {"Leader": "Vercingetorix"}},
{"id": 1, "position": city(), "unit_type": "Infantry"},
{"id": 2, "position": city(), "unit_type": "Infantry"},
{"id": 3, "position": city(), "unit_type": "Infantry"}
]);
p["next_unit_id"] = json!(4);
p["resources"] = json!({"food":7,"wood":7,"ore":7,"ideas":7,"gold":7,
"mood_tokens":7,"culture_tokens":7});
p["resource_limit"] = p["resources"].clone();
data["actions_left"] = json!(3);
data["players"][1]["units"] = json!([]);
data["players"][1]["cities"] = json!([{
"position": "H9", "mood_state": "Neutral", "city_pieces": {}
}]);
let data: GameData = serde_json::from_value(data).unwrap();
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
game.map.tiles.clear();
game.map.unexplored_blocks.clear();
game.map.tiles.insert(city(), Terrain::Fertile);
for adjacent in city().neighbors() {
game.map.tiles.insert(adjacent, Terrain::Fertile);
for outer in adjacent.neighbors() {
game.map.tiles.insert(outer, Terrain::Fertile);
}
}
game.map
.tiles
.insert(Position::from_offset("H9"), Terrain::Fertile);
game
}
fn infantry(n: u8) -> Units {
Units::new(0, n, 0, 0, 0, None)
}
fn quote(game: &Game, units: &Units) -> Result<Value, String> {
web_view::query(
game,
0,
json!({"kind":"recruit", "city":city(), "units":units, "replaced":[]}),
)
}
fn recruit(game: Game, units: &Units) -> Game {
let action = serde_json::from_value(quote(&game, units).unwrap()["action"].clone()).unwrap();
execute_action(game, action, 0)
}
fn choose(game: Game, positions: &[Position]) -> Game {
let action = web_view::query(&game, 0, json!({"kind":"decision", "values":positions})).unwrap()
["action"]
.clone();
execute_action(game, serde_json::from_value(action).unwrap(), 0)
}
fn decision(game: &Game) -> Value {
web_view::view(game, Some(0))["decision"].clone()
}
fn count_army(game: &Game, pos: Position) -> usize {
game.player(0)
.get_units(pos)
.iter()
.filter(|u| u.is_army_unit())
.count()
}
fn add_unit(game: &mut Game, player: usize, pos: Position, unit_type: UnitType) {
let p = game.player_mut(player);
p.units
.push(Unit::new(player, pos, unit_type, p.next_unit_id));
p.next_unit_id += 1;
}
#[test]
fn full_city_recruits_city_size_and_view_requires_legal_final_placements() {
let mut game = fixture();
let [mountain, forest, ..] = city().neighbors()[..] else {
unreachable!()
};
game.map.tiles.insert(mountain, Terrain::Mountain);
game.map.tiles.insert(forest, Terrain::Forest);
// The leader's earlier movement must neither prevent nor be cleared by recruitment.
game.player_mut(0).get_unit_mut(0).movement_restrictions = vec![MovementRestriction::Forest];
let view = web_view::view(&game, Some(0));
let offer = view["cityActions"][0]["recruits"]
.as_array()
.unwrap()
.iter()
.find(|r| r["type"] == "Infantry")
.unwrap();
assert_eq!(
offer["reason"],
Value::Null,
"the actual city viewer must offer recruitment"
);
assert!(
recruit_cost_without_replaced(
&game,
game.player(0),
&infantry(4),
city(),
CostTrigger::NoModifiers
)
.is_ok(),
"native and web previews must agree"
);
let resources = game.player(0).resources.clone();
let mut game = recruit(game, &infantry(4));
for target in [mountain, forest, mountain, forest] {
let d = decision(&game);
assert!(
d["description"]
.as_str()
.unwrap()
.starts_with("Rapid Recruitment")
);
assert_eq!(d["min"], 1);
assert!(
d["options"]
.as_array()
.unwrap()
.iter()
.any(|o| o["position"] == json!(target))
);
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":[]})).is_err());
game = choose(game, &[target]);
}
assert!(game.events.is_empty());
assert_eq!(game.state, GameState::Playing);
assert_eq!(
game.actions_left, 2,
"placement consumes no movement action"
);
assert_eq!(game.player(0).get_city(city()).activations, 1);
let mut expected_resources = resources;
expected_resources -= ResourcePile::food(4) + ResourcePile::ore(4);
assert_eq!(game.player(0).resources, expected_resources);
assert_eq!(count_army(&game, city()), 4);
assert_eq!(count_army(&game, mountain), 2);
assert_eq!(count_army(&game, forest), 2);
for id in 0..4 {
assert_eq!(
game.player(0).get_unit(id).position,
city(),
"only new units deploy"
);
}
assert_eq!(
game.player(0).get_unit(0).movement_restrictions,
vec![MovementRestriction::Forest]
);
for id in 4..8 {
assert!(game.player(0).get_unit(id).movement_restrictions.is_empty());
}
}
#[test]
fn terrain_deployment_leaves_units_free_to_move_but_normal_movement_keeps_terrain_rules() {
for terrain in [Terrain::Mountain, Terrain::Forest] {
let mut game = fixture();
let target = city().neighbors()[0];
let onward = target
.neighbors()
.into_iter()
.find(|p| p.distance(city()) == 2)
.unwrap();
game.map.tiles.insert(target, terrain);
game.map.tiles.insert(onward, Terrain::Mountain);
let game = choose(recruit(game, &infantry(1)), &[target]);
assert_eq!(game.state, GameState::Playing);
assert!(game.player(0).get_unit(4).movement_restrictions.is_empty());
let routes = possible_move_routes(game.player(0), &game, &[4], target, None).unwrap();
assert!(routes.iter().any(|r| r.destination == onward));
let movement = web_view::query(&game, 0, json!({"kind":"movement", "units":[4]})).unwrap();
assert!(
movement["destinations"]
.as_array()
.unwrap()
.iter()
.any(|d| d["position"] == json!(onward))
);
let game = execute_action(
game,
Action::Movement(MovementAction::Move(MoveUnits::new(
vec![4],
onward,
None,
ResourcePile::empty(),
))),
0,
);
assert_eq!(game.player(0).get_unit(4).position, onward);
assert!(
game.player(0)
.get_unit(4)
.movement_restrictions
.contains(&MovementRestriction::Mountain)
);
let GameState::Movement(movement) = game.state else {
panic!("ordinary movement must start")
};
assert_eq!(movement.moved_units, vec![4]);
assert_eq!(game.actions_left, 1);
}
}
#[test]
fn keeping_recruits_is_optional_only_while_final_city_stack_can_fit() {
let mut game = fixture();
game.player_mut(0).units.retain(|u| u.id != 3);
let mut game = recruit(game, &infantry(2));
assert_eq!(decision(&game)["min"], 0);
game = choose(game, &[]);
assert_eq!(decision(&game)["min"], 1);
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":[]})).is_err());
game = choose(game, &[city().neighbors()[0]]);
assert!(game.events.is_empty());
assert_eq!(count_army(&game, city()), 4);
assert_eq!(game.player(0).get_unit(4).position, city());
assert_eq!(game.player(0).get_unit(5).position, city().neighbors()[0]);
}
#[test]
fn destinations_exclude_enemy_units_cities_water_unexplored_and_full_armies() {
let mut game = fixture();
let neighbors = city().neighbors();
for _ in 0..4 {
add_unit(&mut game, 0, neighbors[0], UnitType::Infantry);
}
add_unit(&mut game, 1, neighbors[1], UnitType::Settler);
game.player_mut(1).cities.push(City::new(1, neighbors[2]));
game.map.tiles.insert(neighbors[3], Terrain::Water);
game.map.tiles.insert(neighbors[4], Terrain::Unexplored);
// Friendly cities and Settlers are legal; only army units consume stack capacity.
game.player_mut(0).cities.push(City::new(0, neighbors[5]));
for _ in 0..3 {
add_unit(&mut game, 0, neighbors[5], UnitType::Infantry);
}
add_unit(&mut game, 0, neighbors[5], UnitType::Settler);
assert!(quote(&game, &infantry(1)).is_ok());
assert_eq!(
quote(&game, &infantry(2)).unwrap_err(),
"Too many units in stack"
);
// A spare city slot keeps placement optional, so its one legal target is shown.
game.player_mut(0).units.retain(|u| u.id != 3);
let mut game = recruit(game, &infantry(2));
let d = decision(&game);
assert_eq!(d["min"], 0);
assert_eq!(d["options"].as_array().unwrap().len(), 1);
assert_eq!(d["options"][0]["position"], json!(neighbors[5]));
for invalid in neighbors[..5]
.iter()
.copied()
.chain([city(), Position::from_offset("H9")])
{
assert!(web_view::query(&game, 0, json!({"kind":"decision", "values":[invalid]})).is_err());
}
game = choose(game, &[neighbors[5]]);
// The destination is now full; the second unit stays in the city, without a dead-end prompt.
assert!(game.events.is_empty());
assert_eq!(count_army(&game, neighbors[5]), 4);
assert_eq!(count_army(&game, city()), 4);
}
#[test]
fn no_recruitment_overflow_when_all_adjacent_destinations_are_blocked() {
let mut game = fixture();
for pos in city().neighbors() {
game.map.tiles.remove(&pos);
}
assert_eq!(
quote(&game, &infantry(1)).unwrap_err(),
"Too many units in stack"
);
let action = Action::Playing(PlayingAction::Recruit(Recruit::new(
&infantry(1),
city(),
ResourcePile::food(1) + ResourcePile::ore(1),
)));
assert_eq!(
try_execute_action(game, action, 0).err().unwrap(),
"Too many units in stack"
);
}
#[test]
fn settlers_do_not_consume_stack_capacity_or_force_deployment() {
let mut game = fixture();
let target = city().neighbors()[0];
for _ in 0..4 {
add_unit(&mut game, 0, target, UnitType::Infantry);
}
let game = recruit(game, &Units::new(1, 1, 0, 0, 0, None));
let d = decision(&game);
assert_eq!(d["min"], 0);
assert!(
d["options"]
.as_array()
.unwrap()
.iter()
.any(|o| o["position"] == json!(target))
);
let game = choose(game, &[target]);
assert_eq!(decision(&game)["min"], 1);
assert!(
!decision(&game)["options"]
.as_array()
.unwrap()
.iter()
.any(|o| o["position"] == json!(target))
);
let game = choose(game, &[city().neighbors()[1]]);
assert!(game.events.is_empty());
assert_eq!(count_army(&game, target), 4);
assert!(
game.player(0)
.get_units(target)
.iter()
.any(|u| u.is_settler())
);
}
#[test]
fn city_mood_capacity_cost_building_and_activation_rules_remain_unchanged() {
for (mood, limit) in [
(MoodState::Neutral, 4),
(MoodState::Happy, 5),
(MoodState::Angry, 1),
] {
let mut game = fixture();
game.player_mut(0).get_city_mut(city()).mood_state = mood;
assert!(quote(&game, &infantry(limit)).is_ok());
assert_eq!(
quote(&game, &infantry(limit + 1)).unwrap_err(),
"Too many units"
);
}
let mut game = fixture();
assert_eq!(
quote(&game, &Units::new(0, 0, 0, 1, 0, None)).unwrap_err(),
"Missing building: market"
);
game.player_mut(0).resources = ResourcePile::empty();
assert!(quote(&game, &infantry(1)).is_err());
let mut game = fixture();
game.player_mut(0).get_city_mut(city()).angry_activation = true;
assert_eq!(
quote(&game, &infantry(1)).unwrap_err(),
"City cannot be activated"
);
}
#[test]
fn ordinary_recruitment_and_leader_own_recruitment_do_not_gain_adjacent_capacity() {
for leader_elsewhere in [false, true] {
let mut game = fixture();
if leader_elsewhere {
game.player_mut(0).get_unit_mut(0).position = city().neighbors()[0];
add_unit(&mut game, 0, city(), UnitType::Infantry);
} else {
game.player_mut(0).get_unit_mut(0).unit_type = UnitType::Infantry;
}
// Reinitialize listeners as these are setup changes rather than gameplay.
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
assert_eq!(
quote(&game, &infantry(1)).unwrap_err(),
"Too many units in stack"
);
let mut game = game;
game.player_mut(0).units.retain(|u| u.id != 3);
let game = recruit(game, &infantry(1));
assert!(game.events.is_empty());
assert_eq!(count_army(&game, city()), 4);
}
let mut game = fixture();
game.player_mut(0).units.retain(|u| u.id != 0 && u.id != 3);
game.player_mut(0)
.available_leaders
.push(Leader::Vercingetorix);
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
let mut units = infantry(2);
units.leader = Some(Leader::Vercingetorix);
assert_eq!(quote(&game, &units).unwrap_err(), "Too many units in stack");
units.infantry = 1;
let game = recruit(game, &units);
assert!(
game.events.is_empty(),
"the leader's own recruitment must not trigger his ability"
);
assert_eq!(count_army(&game, city()), 4);
// A later action in the same turn does qualify, including with the city now full.
let game = recruit(game, &infantry(1));
assert_eq!(decision(&game)["min"], 1);
let game = choose(game, &[city().neighbors()[0]]);
assert!(game.events.is_empty());
}
#[test]
fn pending_rapid_recruitment_round_trips_without_losing_required_choices() {
let game = recruit(fixture(), &infantry(2));
let game = choose(game, &[city().neighbors()[0]]);
let game = Game::from_data(game.cloned_data(), game.cache.clone(), GameContext::Play);
let handler = game.current_event_handler().unwrap();
let PersistentEventRequest::SelectPositions(request) = &handler.request else {
panic!("pending placement expected")
};
assert_eq!(request.needed, 1..=1);
let game = execute_action(
game,
Action::Response(EventResponse::SelectPositions(vec![city().neighbors()[1]])),
0,
);
assert!(game.events.is_empty());
assert_eq!(count_army(&game, city()), 4);
}

View file

@ -733,3 +733,25 @@ control markers instead of translated labels for mobile panel layout. Verified
938 frontend tests, 3 extraction tests, catalog/placeholder and source checks,
type checks, production build, and desktop/mobile French objective, retry and
Chinese language-switching browser checks. No engine update required.
## Viewer 0.1.191 / engine 0.4.127
Great Wall now applies its first-round -2 combat value to the attacker, not the
owner's defending army, and attributes the modifier to the correct combat log.
Preserve the happy-city condition and automatic defense against Barbarians.
Vercingetorix's Rapid Recruitment accounts for available adjacent deployment
capacity when recruiting from a full city stack. Require enough placements to
leave legal final stacks without changing normal recruitment limits, costs or
leader timing. Direct placement remains distinct from movement, with no terrain
entry restrictions or movement use; newly placed units may subsequently move.
Barbarian spawning excludes adjacency to other human players' cities, not other
Barbarian settlements. The sanitized Celts/Maya board regression now offers B4,
C2, C3 and E2 while correctly excluding C5 beside the Maya city. Preserve normal
distance-two priority, adjacent fallback and terrain/occupancy restrictions for
both Tribal Allies and incident spawning. No live game moves or history edits.
Verified 941 frontend tests, 224 targeted Rust tests, extraction/catalog checks,
type checks and matching engine/viewer builds. Existing unrelated Great Gardens
error-text and Builder Epic-length test expectations remain unchanged.

View file

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

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/clash-web-client",
"version": "0.1.190",
"version": "0.1.191",
"private": true,
"type": "module",
"scripts": {

View file

@ -763,6 +763,47 @@ test('Rapid Recruitment offers direct deployment of each new land unit', async (
);
});
test('Rapid Recruitment recruits city capacity from a full stack and places without movement penalties', async () => {
const g = await setup('Celts', 'Vercingetorix'), index = seat(g), p = g.players[index];
const city = p.cities[0].position;
addAdvance(p, 'Tactics');
p.cities[0].city_pieces = { academy: index, fortress: index, temple: index };
p.cities[0].mood_state = 'Neutral';
for (const tile of g.map.tiles) tile[1] = 'Fertile';
// Read the real placement choices before filling the recruiting city's stack.
const probe = move(g, query(g, { kind: 'recruit', city, units: { infantry: 1 }, replaced: [] }).action);
const [mountain, forest] = view(probe).decision.options.map((o: any) => o.position);
assert.ok(mountain && forest);
g.map.tiles.find(([pos]: string[]) => pos === mountain)[1] = 'Mountain';
g.map.tiles.find(([pos]: string[]) => pos === forest)[1] = 'Forest';
for (let i = 0; i < 3; i++) p.units.push({ id: p.next_unit_id++, position: city, unit_type: 'Infantry' });
const first = p.next_unit_id;
assert.equal(view(g).cityActions.find((c: any) => c.position === city)
.recruits.find((r: any) => r.type === 'Infantry').reason, null);
assert.throws(() => query(g, { kind: 'recruit', city, units: { infantry: 5 }, replaced: [] }), /Too many units/);
let after = move(g, query(g, { kind: 'recruit', city, units: { infantry: 4 }, replaced: [] }).action);
for (const target of [mountain, forest, mountain, forest]) {
const d = view(after).decision;
assert.equal(d.min, 1);
assert.ok(d.options.some((o: any) => o.position === target));
assert.throws(() => query(after, { kind: 'decision', values: [] }));
after = move(after, query(after, { kind: 'decision', values: [target] }).action);
}
assert.ok(!view(after).decision);
assert.equal(after.state, 'Playing');
assert.equal(after.actions_left, g.actions_left - 1);
assert.equal(after.players[index].units.filter((u: any) => u.position === city && u.unit_type !== 'Settler').length, 4);
for (const id of [first, first + 1, first + 2, first + 3]) {
assert.deepEqual(after.players[index].units.find((u: any) => u.id === id).movement_restrictions ?? [], []);
assert.ok(query(after, { kind: 'movement', units: [id] }).destinations.length,
'a recruit deployed on Mountain/Forest can still move normally');
}
const route = query(after, { kind: 'movement', units: [first] }).destinations[0];
const moved = move(after, route.action);
assert.equal(moved.players[index].units.find((u: any) => u.id === first).position, route.position);
assert.equal(moved.actions_left, g.actions_left - 2);
});
function heldCaptives(g: any, index: number, n: number) {
const p = g.players[index],
owner = 1 - index;

View file

@ -0,0 +1,38 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
const engine = createRequire(import.meta.url)('../.engine/server.js');
const fixture = readFileSync(
new URL('../../server/tests/fixtures/tribal_allies_public_board.json', import.meta.url), 'utf8',
);
const move = (state: string, action: unknown) => engine.tryMove(state, JSON.stringify(action), 0);
const query = (state: string, input: unknown) => JSON.parse(engine.webQuery(
engine.stripSecret(state, 0), 0, JSON.stringify(input),
));
const view = (state: string) => JSON.parse(engine.webView(engine.stripSecret(state, 0), 0));
test('Tribal Allies permits Barbarian settlement adjacency but still excludes Maya city adjacency', () => {
// Sanitized board reconstruction, not a full historical state or live-game move.
for (const fortress of [true, false]) {
const game = JSON.parse(fixture);
if (!fortress) delete game.players[0].cities.find((c: any) => c.position === 'C4').city_pieces.fortress;
const pending = move(JSON.stringify(game), { Playing: { Custom: { action: 'TribalAllies' } } });
const decision = view(pending).decision;
assert.match(decision.description, /Place a Barbarian city and Infantry/);
assert.equal(decision.min, 1);
assert.deepEqual(decision.options.map((o: any) => o.position).sort(), ['B4', 'C2', 'C3', 'E2']);
assert.throws(() => query(pending, { kind: 'decision', values: ['C5'] }),
'C5 borders the opposing human city C6');
for (const position of ['B4', 'C3']) {
const placement = query(pending, { kind: 'decision', values: [position] });
const placed = JSON.parse(move(pending, placement.action));
const barbarians = placed.players.find((p: any) => p.civilization === 'Barbarians');
assert.ok(barbarians.cities.some((c: any) => c.position === position));
assert.deepEqual(barbarians.units.filter((u: any) => u.position === position)
.map((u: any) => u.unit_type), ['Infantry']);
assert.equal(placed.actions_left, 0);
}
}
});

View file

@ -1,6 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { printedCardName } from './card-names.ts';
import { officialWonderText, wonderName } from './wonder-names.ts';
const engine = createRequire(import.meta.url)('../.engine/server.js');
@ -48,6 +49,44 @@ test('built wonder effects are public for both players and spectators; private c
}
});
test('Great Wall reduces the attacking roll and logs the modifier for the attacker only', async () => {
const npcs = JSON.parse(await engine.init(2, [], {}, 'great-wall-regression', {})).players.slice(2);
for (const mood of ['Happy', 'Neutral', 'Angry']) {
const game = JSON.parse(readFileSync(
new URL('../../server/tests/test_games/wonders/great_wall.json', import.meta.url), 'utf8',
));
for (const npc of npcs)
if (!game.players.some((p: any) => p.civilization === npc.civilization))
game.players.push({ ...npc, id: game.players.length });
for (const player of game.players.slice(0, 2)) {
player.action_cards = [];
for (const unit of player.units) unit.unit_type = 'Infantry';
}
game.players[0].cities[0].mood_state = mood;
game.dice_roll_outcomes = [4, 4, 4, 4]; // Two 3/Elephant faces, no Infantry bonus.
const after = JSON.parse(engine.tryMove(JSON.stringify(game), JSON.stringify({
Movement: { Move: { units: [0, 1], destination: 'A1', payment: {} } },
}), 1));
const rolls: any[] = [];
function collect(value: any) {
if (!value || typeof value !== 'object') return;
if (value.CombatRoll) rolls.push(value);
for (const child of Object.values(value)) collect(child);
}
collect(after.log);
assert.equal(rolls.length, 2);
for (const { player, CombatRoll: roll } of rolls) {
const penalized = mood === 'Happy' && player === 1;
assert.equal(roll.combat_value, penalized ? 4 : 6);
assert.deepEqual(roll.combat_modifiers ?? [], penalized
? ['Great Wall gives -2 combat value in the first round'] : []);
}
assert.equal(after.players[0].units.filter((u: any) => u.position === 'A1').length,
mood === 'Happy' ? 2 : 1);
assert.equal(after.players[1].units.length, 1, 'the defending army keeps its full combat value');
}
});
const json = (g: any) => JSON.stringify(g);
const seatOf = (g: any) => engine.currentPlayer(json(g));
const viewOf = (g: any) => JSON.parse(engine.webView(engine.stripSecret(json(g), seatOf(g)), seatOf(g)));