Apply pinned Rust formatting required by CI

This commit is contained in:
coyotte508 2026-11-02 20:54:13 +00:00
commit deeb023a3d
36 changed files with 840 additions and 250 deletions

View file

@ -293,7 +293,8 @@ pub(crate) trait AbilityInitializerSetup: Sized {
if let Some(mut phase) = game.events.pop() {
if let Some(ref c) = phase.player.handler
&& let Some(ref action) = c.response
&& (c.priority == priority || (c.priority == priority - p.priority_delta && c.origin == p.origin))
&& (c.priority == priority
|| (c.priority == priority - p.priority_delta && c.origin == p.origin))
{
let mut current = phase.clone();
current

View file

@ -37,8 +37,15 @@ pub enum Action {
Playing(PlayingAction),
Movement(MovementAction),
Response(EventResponse),
QueueMoves { key: String, actions: Vec<Action>, waiting: bool },
QueueChoice { key: String, response: Option<EventResponse> },
QueueMoves {
key: String,
actions: Vec<Action>,
waiting: bool,
},
QueueChoice {
key: String,
response: Option<EventResponse>,
},
Undo,
Redo,
#[serde(alias = "Setup")]

View file

@ -432,8 +432,9 @@ pub(crate) fn can_play_civil_card(game: &Game, p: &Player, id: u8) -> Result<(),
return Err("Action card not available".to_string());
}
if id == crate::content::incidents::great_diplomat::DIPLOMAT_ID
+ crate::content::incidents::great_persons::GREAT_PERSON_OFFSET
if id
== crate::content::incidents::great_diplomat::DIPLOMAT_ID
+ crate::content::incidents::great_persons::GREAT_PERSON_OFFSET
&& game.context != crate::game::GameContext::Replay
{
return Err("Custom action cannot be played".into());

View file

@ -299,7 +299,9 @@ pub(crate) fn do_advance(
ActionLogBalance::Gain,
if take_incident_token
&& !crate::content::incidents::trojan::anarchy_replaces_event_marker(
game, player_index, advance,
game,
player_index,
advance,
)
{
ActionLogIncidentToken::Take(t - 1)

View file

@ -118,7 +118,11 @@ impl City {
pub(crate) fn mood_for_city_action(&self, player: &Player) -> MoodState {
let mood = self.effective_mood();
if mood == Angry && player.played_once_per_turn_actions.contains(&SpecialAction::Custom(ForcedLabor)) {
if mood == Angry
&& player
.played_once_per_turn_actions
.contains(&SpecialAction::Custom(ForcedLabor))
{
Neutral
} else {
mood

View file

@ -33,10 +33,16 @@ pub(crate) fn get_all_uncached() -> Vec<ActionCard> {
}
// Reuse each card's actual eligibility rules for read-only research reminders.
pub(crate) fn research_choices(game: &crate::game::Game, player: &crate::player::Player, name: &str) -> Vec<crate::advance::Advance> {
pub(crate) fn research_choices(
game: &crate::game::Game,
player: &crate::player::Player,
name: &str,
) -> Vec<crate::advance::Advance> {
let mut choices = match name {
"Quick Advance" => inspiration::possible_advances(player, game),
"Inspiration" | "Technology Trade" => inspiration::possible_inspiration_advances(game, player),
"Inspiration" | "Technology Trade" => {
inspiration::possible_inspiration_advances(game, player)
}
"Synergies" => synergies::categories_with_2_affordable_advances(player, game),
"New Ideas" => synergies::advances_that_can_be_gained(player, game),
_ => vec![],

View file

@ -117,9 +117,10 @@ pub(crate) fn players_in_range2(game: &Game, player: &Player) -> Vec<usize> {
return false;
}
let other = player_positions(p);
other
.iter()
.any(|pos| my.iter().any(|my_pos| game.map.within_revealed_distance(*my_pos, *pos, 2)))
other.iter().any(|pos| {
my.iter()
.any(|my_pos| game.map.within_revealed_distance(*my_pos, *pos, 2))
})
})
.map(|p| p.index)
.collect()
@ -258,26 +259,47 @@ fn great_ideas(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
#[cfg(test)]
mod range_tests {
use super::*;
use crate::{cache::Cache, game::GameContext, game_data::GameData, map::{Map, Terrain}};
use crate::{
cache::Cache,
game::GameContext,
game_data::GameData,
map::{Map, Terrain},
};
use std::collections::HashMap;
#[test]
fn technology_exchange_and_inspiration_need_a_revealed_route() {
let data: GameData = serde_json::from_str(include_str!("../../../tests/test_games/action_cards/inspiration.json")).unwrap();
let data: GameData = serde_json::from_str(include_str!(
"../../../tests/test_games/action_cards/inspiration.json"
))
.unwrap();
let cache = Cache::new(&data.options);
let mut game = Game::from_data(data, cache, GameContext::Play);
let a = Position::new(0, 0);
let b = Position::new(2, 0);
for (index, player) in game.players.iter_mut().enumerate() {
for city in &mut player.cities { city.position = if index == 0 { a } else { b }; }
for unit in &mut player.units { unit.position = if index == 0 { a } else { b }; }
for city in &mut player.cities {
city.position = if index == 0 { a } else { b };
}
for unit in &mut player.units {
unit.position = if index == 0 { a } else { b };
}
}
game.map = Map::new(HashMap::from([(a, Terrain::Fertile), (b, Terrain::Fertile), (Position::new(1, 0), Terrain::Unexplored)]));
game.map = Map::new(HashMap::from([
(a, Terrain::Fertile),
(b, Terrain::Fertile),
(Position::new(1, 0), Terrain::Unexplored),
]));
assert!(players_in_range2(&game, game.player(0)).is_empty());
game.map.tiles.insert(Position::new(1, 0), Terrain::Water);
assert!(players_in_range2(&game, game.player(0)).contains(&1));
game.map.tiles.insert(Position::new(1, 0), Terrain::Unexplored);
game.map.tiles.extend([(Position::new(0, 1), Terrain::Forest), (Position::new(1, 1), Terrain::Mountain)]);
game.map
.tiles
.insert(Position::new(1, 0), Terrain::Unexplored);
game.map.tiles.extend([
(Position::new(0, 1), Terrain::Forest),
(Position::new(1, 1), Terrain::Mountain),
]);
assert!(players_in_range2(&game, game.player(0)).is_empty());
}
}

View file

@ -12,13 +12,13 @@ use crate::content::custom_actions::CustomActionType;
use crate::content::custom_actions::CustomActionType::Taxes;
use crate::content::persistent_events::{HandCardsRequest, ResourceRewardRequest};
use crate::game::{Game, GameOptions};
use crate::objective_card::discard_objective_card;
use crate::utils::remove_element;
use crate::log::add_start_turn_action_if_needed;
use crate::objective_card::discard_objective_card;
use crate::player_events::{PersistentEvent, PersistentEvents};
use crate::resource::{ResourceType, gain_resources};
use crate::resource_pile::ResourcePile;
use crate::special_advance::SpecialAdvance;
use crate::utils::remove_element;
use itertools::Itertools;
pub(crate) fn economy(options: &GameOptions) -> AdvanceGroupInfo {
@ -66,20 +66,31 @@ fn use_bartering(b: AbilityBuilder) -> AbilityBuilder {
"Select a card from your hand to discard",
))
},
|game, s, _e| {
match s.choice[0] {
HandCard::ActionCard(card) => discard_action_card(
game, s.player_index, card, &s.origin, HandCardLocation::DiscardPile,
),
HandCard::ObjectiveCard(card) => discard_objective_card(
game, s.player_index, card, &s.origin, HandCardLocation::DiscardPile,
),
HandCard::Wonder(wonder) => {
remove_element(&mut game.player_mut(s.player_index).wonder_cards, &wonder)
.expect("wonder card must be in hand");
log_card_transfer(game, &HandCard::Wonder(wonder),
HandCardLocation::Hand(s.player_index), HandCardLocation::DiscardPile, &s.origin);
}
|game, s, _e| match s.choice[0] {
HandCard::ActionCard(card) => discard_action_card(
game,
s.player_index,
card,
&s.origin,
HandCardLocation::DiscardPile,
),
HandCard::ObjectiveCard(card) => discard_objective_card(
game,
s.player_index,
card,
&s.origin,
HandCardLocation::DiscardPile,
),
HandCard::Wonder(wonder) => {
remove_element(&mut game.player_mut(s.player_index).wonder_cards, &wonder)
.expect("wonder card must be in hand");
log_card_transfer(
game,
&HandCard::Wonder(wonder),
HandCardLocation::Hand(s.player_index),
HandCardLocation::DiscardPile,
&s.origin,
);
}
},
)

View file

@ -210,8 +210,12 @@ pub fn find_trade_routes(game: &Game, player: &Player, only_ships: bool) -> Vec<
{
// With equal route counts, human cities preserve the choice of gold.
// Barbarian trade only permits food, so choosing it can force waste.
game.players.iter().filter(|p| p.is_human())
.flat_map(|p| &p.cities).map(|c| c.position).collect()
game.players
.iter()
.filter(|p| p.is_human())
.flat_map(|p| &p.cities)
.map(|c| c.position)
.collect()
} else {
vec![]
};

View file

@ -404,16 +404,29 @@ fn hannibal() -> LeaderInfo {
// Transport capacity is shared within a sea space. Navigator may carry Hanno
// with any eligible ships there, regardless of his internal save-file carrier.
pub(crate) fn navigator_can_move_with(p: &Player, ids: &[u32]) -> bool {
p.units.iter().find(|u| u.unit_type == UnitType::Leader(Leader::Hanno))
.is_some_and(|h| h.carrier_id.is_some() && !ids.is_empty() && ids.iter().all(|id|
p.try_get_unit(*id).is_some_and(|u| u.is_ship() && u.position == h.position)))
p.units
.iter()
.find(|u| u.unit_type == UnitType::Leader(Leader::Hanno))
.is_some_and(|h| {
h.carrier_id.is_some()
&& !ids.is_empty()
&& ids.iter().all(|id| {
p.try_get_unit(*id)
.is_some_and(|u| u.is_ship() && u.position == h.position)
})
})
}
pub(crate) fn prepare_move(game: &mut Game, p: usize, m: &mut MoveUnits) -> Result<(), String> {
if game.player(p).event_info.contains_key("Navigator active")
&& navigator_can_move_with(game.player(p), &m.units)
{
let hanno = game.player(p).units.iter().find(|u| u.unit_type == UnitType::Leader(Leader::Hanno)).unwrap();
let hanno = game
.player(p)
.units
.iter()
.find(|u| u.unit_type == UnitType::Leader(Leader::Hanno))
.unwrap();
let id = hanno.id;
let old = hanno.carrier_id.unwrap();
if !m.units.contains(&old) {

View file

@ -164,8 +164,12 @@ fn ignore_hit_ability<B: AbilityInitializerSetup>(
let player_index = p.index;
let player = p.get(game);
let combat = &e.combat;
if (once_per_battle && combat.modifiers.contains(&CombatModifier::TacticianUsed(player_index)))
|| !filter(combat, combat.role(player_index), game) {
if (once_per_battle
&& combat
.modifiers
.contains(&CombatModifier::TacticianUsed(player_index)))
|| !filter(combat, combat.role(player_index), game)
{
return None;
}
@ -188,7 +192,9 @@ fn ignore_hit_ability<B: AbilityInitializerSetup>(
s.log(game, "Ignore the first hit");
apply_ignore_hit(e, s.player_index, true);
if once_per_battle {
e.combat.modifiers.push(CombatModifier::TacticianUsed(s.player_index));
e.combat
.modifiers
.push(CombatModifier::TacticianUsed(s.player_index));
}
}
},

View file

@ -52,10 +52,12 @@ pub(crate) fn raided_settler(game: &Game, u: &Unit) -> bool {
game.players.iter().any(|enemy| {
enemy.index != p.index
&& enemy.has_special_advance(SpecialAdvance::Raiders)
&& enemy
.units
.iter()
.any(|army| army.is_army_unit() && game.map.within_revealed_distance(army.position, u.position, 2))
&& enemy.units.iter().any(|army| {
army.is_army_unit()
&& game
.map
.within_revealed_distance(army.position, u.position, 2)
})
})
}
pub(crate) fn city_destinations(

View file

@ -81,7 +81,11 @@ fn ithobaal() -> LeaderInfo {
if c.has_leader(role, game)
&& p.cities.iter().any(|city| {
city.pieces.temple.is_some()
&& game.map.within_revealed_distance(city.position, c.defender_position(), 2)
&& game.map.within_revealed_distance(
city.position,
c.defender_position(),
2,
)
})
{
s.extra_combat_value += 2;

View file

@ -364,7 +364,12 @@ pub(crate) fn owner_of_sulla_in_range(position: Position, game: &Game) -> Option
// Check if Sulla is within 2 spaces of the given position
game.players.iter().find_map(|p| {
p.active_leader()
.is_some_and(|l| l == Leader::Sulla && game.map.within_revealed_distance(leader_position(p), position, 2))
.is_some_and(|l| {
l == Leader::Sulla
&& game
.map
.within_revealed_distance(leader_position(p), position, 2)
})
.then_some(p.index)
})
}

View file

@ -161,7 +161,15 @@ pub(crate) fn convert_to_settler_range(
.count()
})
.sum::<usize>() as u8;
let standing = present.iter().filter(|u| u.is_army_unit() && !u.carrier_id.is_some_and(|id| units.iter().any(|ship| ship.id == id))).count() as u8;
let standing = present
.iter()
.filter(|u| {
u.is_army_unit()
&& !u
.carrier_id
.is_some_and(|id| units.iter().any(|ship| ship.id == id))
})
.count() as u8;
let max = units.len() as u8;
(0..=max)
.filter(|&i| can_add(p, carried + standing, i, max - i))
@ -335,7 +343,10 @@ fn ruler_of_the_north() -> LeaderAbility {
move |s, game, (), player| {
let p = player.get(game);
let points = if p.active_leader().is_some_and(|l| l == Leader::Knut) {
game.map.revealed_distance(leader_position(p), capital_city_position(game, p)).unwrap_or(0) as f32 / 2.0
game.map
.revealed_distance(leader_position(p), capital_city_position(game, p))
.unwrap_or(0) as f32
/ 2.0
} else {
0_f32
};
@ -390,7 +401,11 @@ fn new_colonies() -> LeaderAbility {
if game.map.get(to).is_some_and(Terrain::is_unexplored) {
crate::explore::move_to_unexplored_tile(
game, &s.player(), &m.units, start, to,
game,
&s.player(),
&m.units,
start,
to,
);
} else {
move_with_possible_combat(game, s.player_index, &m);
@ -411,7 +426,11 @@ fn unload_positions(game: &Game, p: &Player) -> Vec<Position> {
position
.neighbors()
.into_iter()
.filter(|n| game.map.get(*n).is_some_and(|t| t.is_land() || t.is_unexplored()))
.filter(|n| {
game.map
.get(*n)
.is_some_and(|t| t.is_land() || t.is_unexplored())
})
.collect_vec()
}

View file

@ -158,7 +158,11 @@ fn revolution() -> Incident {
b,
|event| &mut event.incident,
ChangeGovernmentOption::FreeAndMandatory,
|i, p, game| i.active_player == p && i.player.sacrifice & 2 == 0 && can_change_government_for_free(game.player(p), game),
|i, p, game| {
i.active_player == p
&& i.player.sacrifice & 2 == 0
&& can_change_government_for_free(game.player(p), game)
},
|_, _| {}, // don't need to pay
|_| true,
);

View file

@ -100,14 +100,10 @@ fn earthquake(id: u8, name: &str, target: IncidentTarget) -> Incident {
apply_earthquake(game, s, i, &s.origin);
},
)
.add_decrease_mood(
target,
MoodModifier::Decrease,
move |_p, _game, i| {
let c = &i.player.must_reduce_mood;
DecreaseMood::new(c.clone(), c.len() as u8)
},
)
.add_decrease_mood(target, MoodModifier::Decrease, move |_p, _game, i| {
let c = &i.player.must_reduce_mood;
DecreaseMood::new(c.clone(), c.len() as u8)
})
.build()
}

View file

@ -126,7 +126,8 @@ fn incident(
return;
}
// This is the event card itself, not a second physical card.
game.incidents_discarded.retain(|discarded| *discarded != id);
game.incidents_discarded
.retain(|discarded| *discarded != id);
game.player_mut(s.player_index).action_cards.push(card_id);
log_card_transfer(
game,
@ -171,7 +172,10 @@ where
cost,
move |game, player, _| {
eligibility_groups.iter().any(|group| {
game.cache.get_advance_group(*group).advances.iter()
game.cache
.get_advance_group(*group)
.advances
.iter()
.any(|a| player.can_advance_free(a.advance, game))
}) || can_play(game, player)
},

View file

@ -16,12 +16,25 @@ pub(crate) fn sea_blockade() -> Objective {
port location of another player",
)
.status_phase_progress(|game, player| {
let most_ships = game.players.iter()
let most_ships = game
.players
.iter()
.filter(|p| p.is_human() && p.index != player.index)
.flat_map(|p| p.cities.iter().filter_map(|c| c.port_position))
.map(|port| player.units.iter().filter(|u| u.is_ship() && u.position == port).count())
.max().unwrap_or(0);
vec![ObjectiveProgress::new("Ships at an opponent's port", most_ships, 2)]
.map(|port| {
player
.units
.iter()
.filter(|u| u.is_ship() && u.position == port)
.count()
})
.max()
.unwrap_or(0);
vec![ObjectiveProgress::new(
"Ships at an opponent's port",
most_ships,
2,
)]
})
.build()
}
@ -105,7 +118,11 @@ pub(crate) fn colony() -> Objective {
player
.cities
.iter()
.filter_map(|c| game.map.revealed_distance(c.position, home).map(|distance| distance as usize))
.filter_map(|c| {
game.map
.revealed_distance(c.position, home)
.map(|distance| distance as usize)
})
.max()
.unwrap_or(0),
5,
@ -113,7 +130,11 @@ pub(crate) fn colony() -> Objective {
})
.status_phase_check(|game, player| {
let home = capital_city_position(game, player);
if player.cities.iter().any(|c| game.map.revealed_distance(c.position, home).is_some_and(|distance| distance >= 5)) {
if player.cities.iter().any(|c| {
game.map
.revealed_distance(c.position, home)
.is_some_and(|distance| distance >= 5)
}) {
let city_founder_played = last_player_round(game, player.index).iter().any(|a| {
a.items.iter().any(|i| {
if let ActionLogEntry::HandCard {
@ -312,14 +333,24 @@ mod blockade_tests {
use super::*;
#[test]
fn only_ships_together_at_an_opponents_port_count() {
let data = serde_json::from_str::<crate::game_data::GameData>(include_str!("../../../tests/test_games/advances/forced_labor.json")).unwrap();
let data = serde_json::from_str::<crate::game_data::GameData>(include_str!(
"../../../tests/test_games/advances/forced_labor.json"
))
.unwrap();
let cache = crate::cache::Cache::new(&data.options);
let mut game = crate::game::Game::from_data(data, cache, crate::game::GameContext::Play);
let port = game.players[0].cities[1].port_position.unwrap();
let check = sea_blockade().status_phase_check.unwrap();
for p in game.players.iter_mut().skip(1) { for c in &mut p.cities { c.port_position = None; } }
for p in game.players.iter_mut().skip(1) {
for c in &mut p.cities {
c.port_position = None;
}
}
game.players[0].units.truncate(2);
for unit in &mut game.players[0].units { unit.position = port; unit.unit_type = UnitType::Ship; }
for unit in &mut game.players[0].units {
unit.position = port;
unit.unit_type = UnitType::Ship;
}
assert!(!check(&game, game.player(0)), "own port");
game.players[1].cities[0].port_position = Some(port);
assert!(check(&game, game.player(0)), "two ships at enemy port");

View file

@ -322,7 +322,10 @@ pub(crate) fn resolve_influence_roll(
}
if (a.starting_city_position == a.position) || a.prevent_boost {
p.log(game, &format!("Cultural influence failed (rolls {roll_label})"));
p.log(
game,
&format!("Cultural influence failed (rolls {roll_label})"),
);
a.info.execute(game);
attempt_failed(game, player_index, a.position);
return PaymentOptions::free();

View file

@ -1,7 +1,9 @@
//! Private, editable commitments. They never change resolution order or reserve a
//! shared card. Only an ordinary, currently legal response can consume a plan.
use crate::card::HandCard;
use crate::content::persistent_events::{EventResponse, PersistentEventRequest, PersistentEventType};
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest, PersistentEventType,
};
use crate::game::Game;
use crate::resource_pile::ResourcePile;
use crate::status_phase::StatusPhaseState;
@ -39,7 +41,11 @@ fn scope(game: &Game, index: usize) -> Option<String> {
}
fn option(label: impl Into<String>, response: EventResponse) -> OptionChoice {
OptionChoice { label: label.into(), description: String::new(), response }
OptionChoice {
label: label.into(),
description: String::new(),
response,
}
}
fn objective_key(game: &Game, name: &str) -> String {
@ -48,29 +54,67 @@ fn objective_key(game: &Game, name: &str) -> String {
fn objective_offers(game: &Game, player: usize) -> Vec<Offer> {
let p = game.player(player);
let mut names: Vec<_> = p.objective_cards.iter().filter(|id| **id != 0).flat_map(|id|
crate::objective_card::status_phase_completable(game, p, *id)).collect();
names.sort(); names.dedup();
names.into_iter().map(|name| {
let key = objective_key(game, &name);
let mut options = vec![option("Skip", EventResponse::SelectHandCards(vec![]))];
options.extend(p.objective_cards.iter().filter(|id| **id != 0).filter(|id|
crate::objective_card::status_phase_completable(game, p, **id).contains(&name))
.map(|id| option(game.cache.get_objective_card(*id).name(),
EventResponse::SelectHandCards(vec![HandCard::ObjectiveCard(*id)]))));
let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone());
Offer {key, title: name, options, selected}
}).collect()
let mut names: Vec<_> = p
.objective_cards
.iter()
.filter(|id| **id != 0)
.flat_map(|id| crate::objective_card::status_phase_completable(game, p, *id))
.collect();
names.sort();
names.dedup();
names
.into_iter()
.map(|name| {
let key = objective_key(game, &name);
let mut options = vec![option("Skip", EventResponse::SelectHandCards(vec![]))];
options.extend(
p.objective_cards
.iter()
.filter(|id| **id != 0)
.filter(|id| {
crate::objective_card::status_phase_completable(game, p, **id)
.contains(&name)
})
.map(|id| {
option(
game.cache.get_objective_card(*id).name(),
EventResponse::SelectHandCards(vec![HandCard::ObjectiveCard(*id)]),
)
}),
);
let selected = game
.early_choices
.iter()
.find(|c| c.player == player && c.key == key)
.map(|c| c.response.clone());
Offer {
key,
title: name,
options,
selected,
}
})
.collect()
}
pub fn prune_objectives(game: &mut Game) {
let invalid: Vec<_> = game.early_choices.iter().enumerate().filter_map(|(index, choice)| {
if !choice.key.contains(":objective:") { return None; }
let valid = objective_offers(game, choice.player).iter().any(|o| o.key == choice.key
&& o.options.iter().any(|v| v.response == choice.response));
(!valid).then_some(index)
}).collect();
for index in invalid.into_iter().rev() { game.early_choices.remove(index); }
let invalid: Vec<_> = game
.early_choices
.iter()
.enumerate()
.filter_map(|(index, choice)| {
if !choice.key.contains(":objective:") {
return None;
}
let valid = objective_offers(game, choice.player).iter().any(|o| {
o.key == choice.key && o.options.iter().any(|v| v.response == choice.response)
});
(!valid).then_some(index)
})
.collect();
for index in invalid.into_iter().rev() {
game.early_choices.remove(index);
}
}
fn advance_key(game: &Game) -> String {
@ -78,94 +122,204 @@ fn advance_key(game: &Game) -> String {
}
fn advance_offer(game: &Game, player: usize) -> Option<Offer> {
if game.age >= game.options.length.ages() { return None; }
let status = game.events.iter().find_map(|event| match &event.event_type {
PersistentEventType::StatusPhase(phase) => Some((phase, event)),
_ => None,
});
if game.age >= game.options.length.ages() {
return None;
}
let status = game
.events
.iter()
.find_map(|event| match &event.event_type {
PersistentEventType::StatusPhase(phase) => Some((phase, event)),
_ => None,
});
let eligible = match status {
Some((StatusPhaseState::CompleteObjectives, _)) => true,
Some((StatusPhaseState::FreeAdvance, event)) => !event.players_used.contains(&player),
Some(_) => false,
None => {
let order = game.human_players_sorted(game.starting_player_index);
game.round == 3 && order.iter().position(|p| *p == player)
.zip(order.iter().position(|p| *p == game.current_player_index))
.is_some_and(|(own, current)| own < current)
game.round == 3
&& order
.iter()
.position(|p| *p == player)
.zip(order.iter().position(|p| *p == game.current_player_index))
.is_some_and(|(own, current)| own < current)
}
};
if !eligible { return None; }
if !eligible {
return None;
}
let p = game.player(player);
let mut options: Vec<_> = game.cache.get_advances().values()
let mut options: Vec<_> = game
.cache
.get_advances()
.values()
.filter(|a| p.can_advance_free(a.advance, game))
.map(|a| OptionChoice { label: a.name.clone(), description: a.description.clone(),
response: EventResponse::SelectAdvance(a.advance) }).collect();
.map(|a| OptionChoice {
label: a.name.clone(),
description: a.description.clone(),
response: EventResponse::SelectAdvance(a.advance),
})
.collect();
options.sort_by(|a, b| a.label.cmp(&b.label));
if options.is_empty() { return None; }
if options.is_empty() {
return None;
}
let key = advance_key(game);
let selected = game.early_choices.iter().find(|c| c.player == player &&
(c.key == key || c.key.starts_with(&format!("{}:", game.age)) && c.key.ends_with(":FreeAdvance/advance")))
let selected = game
.early_choices
.iter()
.find(|c| {
c.player == player
&& (c.key == key
|| c.key.starts_with(&format!("{}:", game.age))
&& c.key.ends_with(":FreeAdvance/advance"))
})
.map(|c| c.response.clone());
Some(Offer { key, title: "Free Advance".into(), options, selected })
Some(Offer {
key,
title: "Free Advance".into(),
options,
selected,
})
}
pub fn offers(game: &Game, player: usize) -> Vec<Offer> {
if player >= game.players.len() || !game.player(player).is_human()
|| game.dropped_players.contains(&player) || game.civilization_draft.is_some()
|| matches!(game.state, crate::game::GameState::Finished) { return vec![]; }
if player >= game.players.len()
|| !game.player(player).is_human()
|| game.dropped_players.contains(&player)
|| game.civilization_draft.is_some()
|| matches!(game.state, crate::game::GameState::Finished)
{
return vec![];
}
let mut result = current_offers(game, player);
if let Some(offer) = advance_offer(game, player) { result.push(offer); }
if let Some(offer) = advance_offer(game, player) {
result.push(offer);
}
result
}
/// Expose only the current step, never future cards, random results, or another
/// player's hand. Earlier players may still change the available options.
fn current_offers(game: &Game, player: usize) -> Vec<Offer> {
if player >= game.players.len() || !game.player(player).is_human()
|| game.dropped_players.contains(&player) || game.civilization_draft.is_some() || matches!(game.state, crate::game::GameState::Finished) {
if player >= game.players.len()
|| !game.player(player).is_human()
|| game.dropped_players.contains(&player)
|| game.civilization_draft.is_some()
|| matches!(game.state, crate::game::GameState::Finished)
{
return vec![];
}
if game.events.is_empty() { return objective_offers(game, player); }
let Some(index) = game.events.iter().rposition(|e| matches!(e.event_type,
PersistentEventType::StatusPhase(_) | PersistentEventType::Incident(_))) else { return vec![]; };
if game.events.is_empty() {
return objective_offers(game, player);
}
let Some(index) = game.events.iter().rposition(|e| {
matches!(
e.event_type,
PersistentEventType::StatusPhase(_) | PersistentEventType::Incident(_)
)
}) else {
return vec![];
};
let event = &game.events[index];
let first = if matches!(event.event_type, PersistentEventType::StatusPhase(StatusPhaseState::ChangeGovernmentType(_))) {
let players: Vec<_> = game.human_players_sorted(game.starting_player_index).iter().map(|i| game.player(*i)).collect();
let first = if matches!(
event.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::ChangeGovernmentType(_))
) {
let players: Vec<_> = game
.human_players_sorted(game.starting_player_index)
.iter()
.map(|i| game.player(*i))
.collect();
if crate::status_phase::player_that_chooses_next_first_player(&players) == player {
let key = format!("{}:first", game.age);
vec![Offer { selected: game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone()), key,
title: "Choose first player".into(), options: game.human_players_sorted(game.starting_player_index).iter().map(|i| option(game.player(*i).civilization.name.clone(), EventResponse::SelectPlayer(*i))).collect() }]
} else { vec![] }
} else { vec![] };
if event.players_used.contains(&player) { return first; }
vec![Offer {
selected: game
.early_choices
.iter()
.find(|c| c.player == player && c.key == key)
.map(|c| c.response.clone()),
key,
title: "Choose first player".into(),
options: game
.human_players_sorted(game.starting_player_index)
.iter()
.map(|i| {
option(
game.player(*i).civilization.name.clone(),
EventResponse::SelectPlayer(*i),
)
})
.collect(),
}]
} else {
vec![]
}
} else {
vec![]
};
if event.players_used.contains(&player) {
return first;
}
// Nested research/event reactions must finish before early status choices are
// offered. Objective selection is the only supported nested request.
if game.events[index+1..].iter().any(|e| !matches!(e.event_type, PersistentEventType::SelectObjectives(_))) {
if game.events[index + 1..]
.iter()
.any(|e| !matches!(e.event_type, PersistentEventType::SelectObjectives(_)))
{
return vec![];
}
let prefix = scope(game, index).expect("supported event");
let p = game.player(player);
let mut result: Vec<Offer> = first;
let mut add = |suffix: &str, title: String, options: Vec<OptionChoice>| {
if options.is_empty() { return; }
if options.is_empty() {
return;
}
let key = format!("{prefix}{suffix}");
let selected = game.early_choices.iter().find(|c| c.player == player && c.key == key).map(|c| c.response.clone());
result.push(Offer { key, title, options, selected });
let selected = game
.early_choices
.iter()
.find(|c| c.player == player && c.key == key)
.map(|c| c.response.clone());
result.push(Offer {
key,
title,
options,
selected,
});
};
match &event.event_type {
PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => {
let mut options: Vec<_> = p.cities.iter().filter(|c| c.size() == 1)
.map(|c| option(c.position.to_string(), EventResponse::SelectPositions(vec![c.position]))).collect();
let mut options: Vec<_> = p
.cities
.iter()
.filter(|c| c.size() == 1)
.map(|c| {
option(
c.position.to_string(),
EventResponse::SelectPositions(vec![c.position]),
)
})
.collect();
if !options.is_empty() {
options.insert(0, option("Keep all cities", EventResponse::SelectPositions(vec![])));
options.insert(
0,
option("Keep all cities", EventResponse::SelectPositions(vec![])),
);
add("raze", "Raze city".into(), options);
}
}
PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives) => {
return objective_offers(game, player);
}
PersistentEventType::Incident(i) if !i.consumed && !i.replaced_by_sacrifice && i.selected_player.is_none()
&& game.cache.get_incident(i.incident_id).action_card.is_some() => {
PersistentEventType::Incident(i)
if !i.consumed
&& !i.replaced_by_sacrifice
&& i.selected_player.is_none()
&& game.cache.get_incident(i.incident_id).action_card.is_some() =>
{
// Do not ask before event cancellation, placement or other base
// effects. Once an offer is visible, later players may precommit.
if !event.player.handler.as_ref().is_some_and(|h| matches!(&h.request,
@ -173,13 +327,23 @@ fn current_offers(game: &Game, player: usize) -> Vec<Offer> {
return vec![];
}
let cost = if player == i.active_player { 1 } else { 2 };
let mut options = vec![option("Pass", EventResponse::Payment(vec![ResourcePile::empty()]))];
let mut options = vec![option(
"Pass",
EventResponse::Payment(vec![ResourcePile::empty()]),
)];
// No inferred gold/captive conversion: a queued purchase spends
// precisely the displayed culture payment, or asks again.
if p.resources.culture_tokens >= cost {
options.push(option(format!("Take if offered · {cost} culture"), EventResponse::Payment(vec![ResourcePile::culture_tokens(cost)])));
options.push(option(
format!("Take if offered · {cost} culture"),
EventResponse::Payment(vec![ResourcePile::culture_tokens(cost)]),
));
}
add("offer", game.cache.get_incident(i.incident_id).name.clone(), options);
add(
"offer",
game.cache.get_incident(i.incident_id).name.clone(),
options,
);
}
_ => {}
}
@ -187,35 +351,67 @@ fn current_offers(game: &Game, player: usize) -> Vec<Offer> {
}
pub fn can_save(game: &Game, player: usize, key: &str, response: Option<&EventResponse>) -> bool {
(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)))
(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))
})
}
pub fn save(game: &mut Game, player: usize, key: &str, response: Option<EventResponse>) -> Result<(), String> {
if !can_save(game, player, key, response.as_ref()) { return Err("This early choice is no longer available".into()); }
pub fn save(
game: &mut Game,
player: usize,
key: &str,
response: Option<EventResponse>,
) -> Result<(), String> {
if !can_save(game, player, key, response.as_ref()) {
return Err("This early choice is no longer available".into());
}
if key == advance_key(game) {
game.early_choices.retain(|c| c.player != player || !c.key.ends_with(":FreeAdvance/advance"));
game.early_choices
.retain(|c| c.player != player || !c.key.ends_with(":FreeAdvance/advance"));
}
game.early_choices.retain(|c| c.player != player || (c.key != key && !matches!((&c.response, &response),
(EventResponse::SelectHandCards(a), Some(EventResponse::SelectHandCards(b))) if !a.is_empty() && a == b && key.contains(":objective:"))));
if let Some(response) = response { game.early_choices.push(SavedChoice { player, key: key.into(), response }); }
if let Some(response) = response {
game.early_choices.push(SavedChoice {
player,
key: key.into(),
response,
});
}
// Metadata-only platform update; not a turn, journal entry or undo boundary.
game.early_choice_update = true;
Ok(())
}
pub fn expire_current_event(game: &mut Game) {
if game.events.last().is_some_and(|e| matches!(e.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance))) {
if game.events.last().is_some_and(|e| {
matches!(
e.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance)
)
}) {
let key = advance_key(game);
game.early_choices.retain(|c| c.key != key);
}
if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives))) {
if game.events.last().is_some_and(|e| {
matches!(
e.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives)
)
}) {
let prefix = format!("{}:objective:", game.age);
game.early_choices.retain(|c| !c.key.starts_with(&prefix));
}
if game.events.last().is_some_and(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)))) {
game.early_choices.retain(|c| c.key != format!("{}:first", game.age));
if game.events.last().is_some_and(|e| {
matches!(
e.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_))
)
}) {
game.early_choices
.retain(|c| c.key != format!("{}:first", game.age));
}
if let Some(prefix) = scope(game, game.events.len().saturating_sub(1)) {
game.early_choices.retain(|c| !c.key.starts_with(&prefix));
@ -229,32 +425,65 @@ pub fn take_ready(game: &mut Game) -> Option<EventResponse> {
let event = game.events.last()?;
let handler = event.player.handler.as_ref()?;
let (index, suffix) = match &event.event_type {
PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => (game.events.len()-1, "first".into()),
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => (game.events.len()-1, "advance".into()),
PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => (game.events.len()-1, "raze".into()),
PersistentEventType::StatusPhase(StatusPhaseState::DetermineFirstPlayer(_)) => {
(game.events.len() - 1, "first".into())
}
PersistentEventType::StatusPhase(StatusPhaseState::FreeAdvance) => {
(game.events.len() - 1, "advance".into())
}
PersistentEventType::StatusPhase(StatusPhaseState::RazeSize1City) => {
(game.events.len() - 1, "raze".into())
}
PersistentEventType::SelectObjectives(i) => {
let index = game.events.iter().rposition(|e| matches!(e.event_type, PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives)))?;
let index = game.events.iter().rposition(|e| {
matches!(
e.event_type,
PersistentEventType::StatusPhase(StatusPhaseState::CompleteObjectives)
)
})?;
(index, format!("objective:{}", i.shown_objective.as_ref()?))
}
PersistentEventType::Incident(_) if matches!(&handler.request, PersistentEventRequest::Payment(rs)
if rs.iter().any(|r| r.name == "Pay to gain the Action Card")) => (game.events.len()-1, "offer".into()),
PersistentEventType::Incident(_)
if matches!(&handler.request, PersistentEventRequest::Payment(rs)
if rs.iter().any(|r| r.name == "Pay to gain the Action Card")) =>
{
(game.events.len() - 1, "offer".into())
}
_ => return None,
};
let key = if suffix == "advance" { advance_key(game) } else if suffix == "first" { format!("{}:first", game.age) } else if let Some(name) = suffix.strip_prefix("objective:") {
let key = if suffix == "advance" {
advance_key(game)
} else if suffix == "first" {
format!("{}:first", game.age)
} else if let Some(name) = suffix.strip_prefix("objective:") {
objective_key(game, name)
} else { format!("{}{suffix}", scope(game, index)?) };
} else {
format!("{}{suffix}", scope(game, index)?)
};
let legacy_key = format!("{}{suffix}", scope(game, index)?);
let at = game.early_choices.iter().position(|c| c.player == player &&
(c.key == key || suffix == "advance" && c.key == legacy_key))?;
let at = game.early_choices.iter().position(|c| {
c.player == player && (c.key == key || suffix == "advance" && c.key == legacy_key)
})?;
let response = &game.early_choices[at].response;
let valid = match (&handler.request, response) {
(PersistentEventRequest::SelectPlayer(r), EventResponse::SelectPlayer(p)) => r.choices.contains(p),
(PersistentEventRequest::SelectAdvance(r), EventResponse::SelectAdvance(a)) => r.choices.contains(a),
(PersistentEventRequest::SelectPositions(r), EventResponse::SelectPositions(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|p| r.choices.contains(p)),
(PersistentEventRequest::SelectHandCards(r), EventResponse::SelectHandCards(v)) => r.needed.contains(&(v.len() as u8)) && v.iter().all(|c| r.choices.contains(c)),
(PersistentEventRequest::Payment(rs), EventResponse::Payment(v)) => rs.len() == 1 && v.len() == 1
&& game.player(player).resources.has_at_least(&v[0])
&& ((rs[0].optional && v[0].is_empty()) || rs[0].cost.is_valid_payment(&v[0])),
(PersistentEventRequest::SelectPlayer(r), EventResponse::SelectPlayer(p)) => {
r.choices.contains(p)
}
(PersistentEventRequest::SelectAdvance(r), EventResponse::SelectAdvance(a)) => {
r.choices.contains(a)
}
(PersistentEventRequest::SelectPositions(r), EventResponse::SelectPositions(v)) => {
r.needed.contains(&(v.len() as u8)) && v.iter().all(|p| r.choices.contains(p))
}
(PersistentEventRequest::SelectHandCards(r), EventResponse::SelectHandCards(v)) => {
r.needed.contains(&(v.len() as u8)) && v.iter().all(|c| r.choices.contains(c))
}
(PersistentEventRequest::Payment(rs), EventResponse::Payment(v)) => {
rs.len() == 1
&& v.len() == 1
&& game.player(player).resources.has_at_least(&v[0])
&& ((rs[0].optional && v[0].is_empty()) || rs[0].cost.is_valid_payment(&v[0]))
}
_ => false,
};
let choice = game.early_choices.remove(at);

View file

@ -738,9 +738,15 @@ pub(crate) fn draw_and_discard_incident_card_from_pile(
"Events",
|g| &mut g.incidents_left,
|g| {
g.cache.get_incidents().iter()
.filter(|i| !g.action_cards_discarded.contains(&(i.id + GREAT_PERSON_OFFSET)))
.map(|i| i.id).collect_vec()
g.cache
.get_incidents()
.iter()
.filter(|i| {
!g.action_cards_discarded
.contains(&(i.id + GREAT_PERSON_OFFSET))
})
.map(|i| i.id)
.collect_vec()
},
|p| {
p.action_cards

View file

@ -457,7 +457,11 @@ fn action_origin(a: &Action, player: &Player) -> Option<EventOrigin> {
Action::Movement(_) => Some(move_event_origin()),
Action::Undo => panic!("Unexpected undo in log"),
Action::Redo => panic!("Unexpected redo in log"),
Action::QueueMoves { .. } | Action::QueueChoice { .. } | Action::StartTurn | Action::Response(_) | Action::ChooseCivilization(_) => None,
Action::QueueMoves { .. }
| Action::QueueChoice { .. }
| Action::StartTurn
| Action::Response(_)
| Action::ChooseCivilization(_) => None,
}
}

View file

@ -63,16 +63,24 @@ impl Map {
}
pathfinding::prelude::astar(
&from,
|p| p.neighbors().into_iter().filter(|p| revealed(*p)).map(|p| (p, 1_u32)),
|p| {
p.neighbors()
.into_iter()
.filter(|p| revealed(*p))
.map(|p| (p, 1_u32))
},
|p| p.distance(to),
|p| *p == to,
).map(|(_, distance)| distance)
)
.map(|(_, distance)| distance)
}
#[must_use]
pub fn within_revealed_distance(&self, from: Position, to: Position, range: u32) -> bool {
from.distance(to) <= range
&& self.revealed_distance(from, to).is_some_and(|distance| distance <= range)
&& self
.revealed_distance(from, to)
.is_some_and(|distance| distance <= range)
}
pub fn add_unexplored_blocks(&mut self, blocks: Vec<UnexploredBlock>) {
@ -620,11 +628,16 @@ mod revealed_distance_tests {
let middle = Position::new(1, 0);
let b = Position::new(2, 0);
let mut map = Map::new(HashMap::from([
(a, Terrain::Fertile), (middle, Terrain::Unexplored), (b, Terrain::Forest),
(a, Terrain::Fertile),
(middle, Terrain::Unexplored),
(b, Terrain::Forest),
]));
assert_eq!(map.revealed_distance(a, b), None);
assert!(!map.within_revealed_distance(a, b, 2));
map.tiles.extend([(Position::new(0, 1), Terrain::Water), (Position::new(1, 1), Terrain::Mountain)]);
map.tiles.extend([
(Position::new(0, 1), Terrain::Water),
(Position::new(1, 1), Terrain::Mountain),
]);
assert_eq!(map.revealed_distance(a, b), Some(3));
assert!(!map.within_revealed_distance(a, b, 2));
assert!(map.within_revealed_distance(a, b, 3));

View file

@ -99,7 +99,10 @@ fn add_negotiations(player: &Player, game: &Game, base: &mut Vec<MoveRoute>) {
let partner = game.player(partner);
base.retain(|r| {
partner.get_units(r.destination).is_empty()
&& !partner.cities.iter().any(|city| city.position == r.destination)
&& !partner
.cities
.iter()
.any(|city| city.position == r.destination)
});
}
}
@ -138,7 +141,14 @@ fn reachable_with_roads(
.flat_map(|middle| {
next_road_step(player, game, middle, stack_size, moving_xerxes, |_| true)
})
.chain(next_road_step(player, game, start, stack_size, moving_xerxes, |_| true))
.chain(next_road_step(
player,
game,
start,
stack_size,
moving_xerxes,
|_| true,
))
.unique()
.filter_map(|destination| {
road_route(

View file

@ -205,7 +205,11 @@ fn move_units_with_terrain(
unit.carrier_id = embark_carrier_id;
if let Some(terrain) = terrain_movement_restriction(&game.map, to, unit) {
if !(ignore_terrain && matches!(terrain, MovementRestriction::Mountain | MovementRestriction::Forest))
if !(ignore_terrain
&& matches!(
terrain,
MovementRestriction::Mountain | MovementRestriction::Forest
))
&& !(hannibal && terrain == MovementRestriction::Mountain)
&& !(terracing
&& terrain == MovementRestriction::Mountain
@ -520,7 +524,14 @@ fn execute_move_action(game: &mut Game, player: &EventPlayer, m: &MoveUnits) ->
} else if ignore_terrain && game.enemy_player(player.index, m.destination).is_none() {
// Roads ignore the arrival penalty too, not only existing restrictions
// while validating the route. Battles still impose their own stop.
move_units_with_terrain(game, player.index, &m.units, m.destination, m.embark_carrier_id, true);
move_units_with_terrain(
game,
player.index,
&m.units,
m.destination,
m.embark_carrier_id,
true,
);
} else {
move_with_possible_combat(game, player.index, m);
}

View file

@ -176,9 +176,16 @@ fn place_pirate_ship(builder: IncidentBuilder, priority: i32, blockade: bool) ->
IncidentTarget::ActivePlayer,
priority,
move |game, p, _i| {
if get_pirates_player(game).available_units().get(&UnitType::Ship) == 0 {
if get_pirates_player(game)
.available_units()
.get(&UnitType::Ship)
== 0
{
if blockade {
p.log(game, "Pirate event has no effect: Carthage controls all four Pirate Ships");
p.log(
game,
"Pirate event has no effect: Carthage controls all four Pirate Ships",
);
}
return None;
}

View file

@ -23,8 +23,8 @@ use crate::victory_points::victory_points_parts;
use crate::wonder::Wonder;
use serde_json::{Value, json};
mod actions;
mod combat_estimate;
mod collection_potential;
mod combat_estimate;
mod decisions;
mod effects;
mod journal;
@ -159,14 +159,22 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
}
});
let setup = crate::map::get_map_setup(game.players.iter().filter(|p| p.is_human()).count());
let regions: Vec<Value> = setup.home_positions.iter().enumerate()
let regions: Vec<Value> = setup
.home_positions
.iter()
.enumerate()
.map(|(player, home)| (Some(player), &home.position))
.chain(setup.free_positions.iter().map(|position| (None, position)))
.enumerate().map(|(index, (home, position))| {
let tiles: Vec<_> = crate::map::block_tiles(position).into_iter()
.filter(|tile| game.map.is_inside(*tile)).collect();
.enumerate()
.map(|(index, (home, position))| {
let tiles: Vec<_> = crate::map::block_tiles(position)
.into_iter()
.filter(|tile| game.map.is_inside(*tile))
.collect();
json!({"id":index + 1,"homePlayer":home,"tiles":tiles})
}).filter(|region| !region["tiles"].as_array().unwrap().is_empty()).collect();
})
.filter(|region| !region["tiles"].as_array().unwrap().is_empty())
.collect();
// A map-reading aid, not legal move offers. Use visible terrain only, including for spectators.
let mut sea_routes = game
.map
@ -182,14 +190,23 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
.filter(|p| p.is_human())
.map(|p| crate::barbarians::map_guide(game, p.index))
.collect::<Vec<_>>();
let trade_routes = game.players.iter().filter(|p| p.civilization.is_human()).map(|p| {
let enabled = p.can_use_advance(Advance::TradeRoutes);
let routes = if enabled {
crate::content::advances::trade_routes::find_trade_routes(game, p, false)
.iter().map(|r| json!({"from":r.from,"to":r.to,"unit":r.unit_id})).collect::<Vec<_>>()
} else { vec![] };
json!({"player":p.index,"enabled":enabled,"routes":routes})
}).collect::<Vec<_>>();
let trade_routes = game
.players
.iter()
.filter(|p| p.civilization.is_human())
.map(|p| {
let enabled = p.can_use_advance(Advance::TradeRoutes);
let routes = if enabled {
crate::content::advances::trade_routes::find_trade_routes(game, p, false)
.iter()
.map(|r| json!({"from":r.from,"to":r.to,"unit":r.unit_id}))
.collect::<Vec<_>>()
} else {
vec![]
};
json!({"player":p.index,"enabled":enabled,"routes":routes})
})
.collect::<Vec<_>>();
let pirate_spawns = game
.players
.iter()
@ -253,7 +270,7 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
let Some(seat) = seat else {
let mut result = json!({"logOriginNames":log_origin_names,"builtWonders":built_wonders,"cardCatalog":card_catalog,"eventCatalog":event_catalog,"activeEffects":active_effects,"pendingEvent":pending_event,"civilizationDraft":civilization_draft,"waitingFor":waiting_for,"activePlayers":active_players,"activePlayer": active, "canPlay": false, "supportedPhase": supported_phase, "players": players, "cities": [], "advances": [], "objectiveCards": [], "wonderCards": [], "wonderCatalog":wonder_catalog, "objectiveDecision": null, "cityActions": [], "settlers": [], "stopMovement": null, "canUndo": false, "canEndTurn": false, "barbarianGuide":barbarian_guide,"pirateSpawns":pirate_spawns,"seaRoutes":sea_routes});
result["tradeRoutes"] = json!(trade_routes);
result["regions"] = json!(regions);
result["regions"] = json!(regions);
return result;
};
let p = game.player(seat);
@ -324,11 +341,23 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
"shogunateDraft":p.has_special_advance(crate::special_advance::SpecialAdvance::Shogunate)&&p.can_use_advance(Advance::Draft)&&!p.event_info.contains_key("Shogunate Draft"),
"canActivate":city.can_activate(), "activationMood":after_activation.mood_state,"activationCapacity":after_activation.mood_modified_size(p)})
}).collect::<Vec<_>>();
let early_offers = if seat != active || game.events.is_empty() { crate::early_choices::offers(game, seat) } else { vec![] };
let early_offers = if seat != active || game.events.is_empty() {
crate::early_choices::offers(game, seat)
} else {
vec![]
};
let early_advance = early_offers.iter().find(|o| o.key.ends_with("/advance"));
let early_advance_choices: Vec<_> = early_advance.into_iter().flat_map(|o| &o.options).filter_map(|o| {
if let EventResponse::SelectAdvance(a) = o.response { Some(a) } else { None }
}).collect();
let early_advance_choices: Vec<_> = early_advance
.into_iter()
.flat_map(|o| &o.options)
.filter_map(|o| {
if let EventResponse::SelectAdvance(a) = o.response {
Some(a)
} else {
None
}
})
.collect();
let advance_choice = if seat == active {
game.current_event_handler()
.and_then(|handler| match &handler.request {
@ -342,7 +371,8 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
} else {
None
};
let research_uses_event_marker = early_advance.is_some() || advance_choice.is_none()
let research_uses_event_marker = early_advance.is_some()
|| advance_choice.is_none()
|| game
.current_event_handler()
.is_some_and(|handler| decisions::advance_uses_event_marker(game, handler));
@ -421,7 +451,12 @@ pub fn view(game: &Game, seat: Option<usize>) -> Value {
"canUndo":seat == active && game.can_undo(),"canRedo":seat == active && game.can_redo(),"canEndTurn":can_play && PlayingActionType::EndTurn.is_available(game, seat).is_ok()});
result["tradeRoutes"] = json!(trade_routes);
result["regions"] = json!(regions);
result["unavailableSpecialActions"] = json!(special_actions.iter().filter(|a| !a["reason"].is_null()).collect::<Vec<_>>());
result["unavailableSpecialActions"] = json!(
special_actions
.iter()
.filter(|a| !a["reason"].is_null())
.collect::<Vec<_>>()
);
result["activeEffects"] = json!(active_effects);
result["earlyChoices"] = json!(early_offers);
result
@ -838,7 +873,9 @@ mod tests {
.map
.tiles
.keys()
.find(|pos| pos.distance(site) == 2 && game.map.within_revealed_distance(**pos, site, 2))
.find(|pos| {
pos.distance(site) == 2 && game.map.within_revealed_distance(**pos, site, 2)
})
.expect("tile 2 spaces away");
game.players[seat]
.units
@ -877,7 +914,9 @@ fn research_plan(game: &Game, seat: usize, input: &Value) -> Result<Value, Strin
};
let p = game.player(seat);
let eligible = p.can_use_advance(Advance::FreeEducation)
&& !p.event_info.contains_key(&crate::events::EventOrigin::Advance(Advance::FreeEducation).id())
&& !p
.event_info
.contains_key(&crate::events::EventOrigin::Advance(Advance::FreeEducation).id())
&& a.advance != Advance::FreeEducation
&& (a.payment.ideas > 0 || a.payment.gold > 0);
if !eligible {

View file

@ -29,9 +29,7 @@ pub(super) fn describe(game: &Game) -> Option<Value> {
{
"Choose where the exploring fleet finishes"
}
(Request::SelectPositions(_), EventOrigin::LeaderAbility(name))
if name == "Revolt" =>
{
(Request::SelectPositions(_), EventOrigin::LeaderAbility(name)) if name == "Revolt" => {
"Choose a city for the free infantry"
}
(Request::SelectPositions(_), EventOrigin::Advance(Advance::Fanaticism)) => {

View file

@ -273,18 +273,35 @@ fn negotiations_protects_cities_without_units() {
for fortress in [false, true] {
let mut game = JSON.load_game("negotiations");
game.player_mut(0).units.clear();
game.player_mut(1).advances.insert(advance::Advance::Tactics);
game.player_mut(1)
.advances
.insert(advance::Advance::Tactics);
game.player_mut(0).cities[0].pieces.fortress = fortress.then_some(0);
let destination = Position::from_offset("C2");
let can_enter = |game: &server::game::Game| {
possible_move_routes(game.player(1), game, &[0], Position::from_offset("B1"), None)
.iter().any(|routes| routes.iter().any(|route| route.destination == destination))
possible_move_routes(
game.player(1),
game,
&[0],
Position::from_offset("B1"),
None,
)
.iter()
.any(|routes| routes.iter().any(|route| route.destination == destination))
};
assert!(can_enter(&game), "The city is reachable before Negotiations");
let game = server::game_api::execute(game, Action::Playing(PlayingAction::ActionCard(23)), 0);
let game = server::game_api::execute(game, payment_response(ResourcePile::culture_tokens(1)), 0);
assert!(
can_enter(&game),
"The city is reachable before Negotiations"
);
let game =
server::game_api::execute(game, Action::Playing(PlayingAction::ActionCard(23)), 0);
let game =
server::game_api::execute(game, payment_response(ResourcePile::culture_tokens(1)), 0);
let game = server::game_api::execute(game, Action::Playing(PlayingAction::EndTurn), 0);
assert!(!can_enter(&game), "Negotiations must protect a city even without units");
assert!(
!can_enter(&game),
"Negotiations must protect a city even without units"
);
}
}
@ -469,7 +486,9 @@ fn technology_trade_only_offers_partners_within_two_spaces() {
let mut game = Game::from_data(data, cache, GameContext::Play);
// The synthetic contacts must occupy real, revealed map spaces.
for pos in ["C1", "C2", "C3", "C4", "C5"] {
game.map.tiles.insert(Position::from_offset(pos), server::map::Terrain::Fertile);
game.map
.tiles
.insert(Position::from_offset(pos), server::map::Terrain::Fertile);
}
let game = server::game_api::execute(
game,

View file

@ -990,7 +990,11 @@ fn proselytism_counts_settlers_in_a_wonder_city() {
#[test]
fn arts_can_reserve_its_fee_from_great_arena_mood() {
use server::cultural_influence::influence_culture_boost_cost;
let mut game = execute_action(load_culture(), advance_action(Advance::Arts, ResourcePile::ideas(2)), 1);
let mut game = execute_action(
load_culture(),
advance_action(Advance::Arts, ResourcePile::ideas(2)),
1,
);
game.players[1].wonders_owned.insert(Wonder::Colosseum);
game.players[1].resources = ResourcePile::mood_tokens(7);
let kind = PlayingActionType::Special(SpecialAction::Modifier(
@ -1004,14 +1008,23 @@ fn arts_can_reserve_its_fee_from_great_arena_mood() {
#[test]
fn forced_labor_allows_construction_but_not_second_activation() {
use server::construct::can_construct;
use server::city_pieces::Building;
use server::construct::can_construct;
use server::player::CostTrigger;
let mut game = JSON.load_game("forced_labor");
game.players[0].advances.insert(server::advance::Advance::Writing);
game.players[0]
.advances
.insert(server::advance::Advance::Writing);
let check = |g: &server::game::Game| {
let p = g.player(0);
can_construct(&p.cities[0], Building::Academy, p, g, CostTrigger::NoModifiers, &[])
can_construct(
&p.cities[0],
Building::Academy,
p,
g,
CostTrigger::NoModifiers,
&[],
)
};
assert!(check(&game).is_err());
game = server::game_api::execute(game, custom_action(CustomActionType::ForcedLabor), 0);

View file

@ -122,13 +122,32 @@ fn converting_ship_carries_army_passengers_in_one_group_move() {
game.players[0].units[0].unit_type = UnitType::Ship;
for u in &mut game.players[0].units {
u.position = sea;
if u.id != 3 { u.unit_type = UnitType::Infantry; u.carrier_id = Some(3); }
if u.id != 3 {
u.unit_type = UnitType::Infantry;
u.carrier_id = Some(3);
}
}
game = server::game_api::execute(game, move_action(vec![3], land), 0);
game = server::game_api::execute(game, Action::Response(EventResponse::SelectUnits(vec![])), 0);
assert!(game.players[0].units.iter().all(|u| u.position == land && u.carrier_id.is_none()));
assert!(game.players[0].units.iter().all(|u| u.unit_type == UnitType::Infantry));
game = server::game_api::execute(
game,
Action::Response(EventResponse::SelectUnits(vec![])),
0,
);
assert!(
game.players[0]
.units
.iter()
.all(|u| u.position == land && u.carrier_id.is_none())
);
assert!(
game.players[0]
.units
.iter()
.all(|u| u.unit_type == UnitType::Infantry)
);
if let server::game::GameState::Movement(m) = &game.state {
assert_eq!(m.movement_actions_left, 2);
} else { panic!("expected movement"); }
} else {
panic!("expected movement");
}
}

View file

@ -456,26 +456,55 @@ fn naval_defenders_exclude_passengers_from_dice_and_combat_casualties() {
passenger.carrier_id = Some(if id < 92 { 1 } else { 2 });
game.player_mut(1).units.push(passenger);
}
assert_eq!(server::combat_stats::active_defenders(&game, 1, Position::from_offset("D2")), vec![1, 2]);
assert_eq!(
server::combat_stats::active_defenders(&game, 1, Position::from_offset("D2")),
vec![1, 2]
);
// Two dice per side; 3 on each die yields one hit per side.
game.dice_roll_outcomes = vec![4; 20];
let before = game.dice_roll_log.len();
let mut game = execute(game, move_action(vec![7, 8], Position::from_offset("D2")), 0);
let mut game = execute(
game,
move_action(vec![7, 8], Position::from_offset("D2")),
0,
);
assert_eq!(game.dice_roll_log.len() - before, 4, "only ships roll");
// Resolve the attacker's ship loss and any excess passengers first.
for _ in 0..4 {
let event = game.current_event();
if event.player.index == 1 { break; }
let PersistentEventRequest::SelectUnits(req) = &event.player.handler.as_ref().unwrap().request else { panic!("expected casualties"); };
let ids = req.request.choices.iter().take(*req.request.needed.start() as usize).copied().collect();
if event.player.index == 1 {
break;
}
let PersistentEventRequest::SelectUnits(req) =
&event.player.handler.as_ref().unwrap().request
else {
panic!("expected casualties");
};
let ids = req
.request
.choices
.iter()
.take(*req.request.needed.start() as usize)
.copied()
.collect();
game = execute(game, Action::Response(EventResponse::SelectUnits(ids)), 0);
}
// Identical ships are removed automatically; the remaining prompt is only
// for passengers exceeding the surviving ship's two transport spaces.
assert_eq!(game.player(1).get_units(Position::from_offset("D2")).iter().filter(|u| u.is_ship()).count(), 1);
assert_eq!(
game.player(1)
.get_units(Position::from_offset("D2"))
.iter()
.filter(|u| u.is_ship())
.count(),
1
);
let event = game.current_event();
assert_eq!(event.player.index, 1);
let PersistentEventRequest::SelectUnits(req) = &event.player.handler.as_ref().unwrap().request else { panic!("expected excess passengers"); };
let PersistentEventRequest::SelectUnits(req) = &event.player.handler.as_ref().unwrap().request
else {
panic!("expected excess passengers");
};
assert_eq!(req.request.choices, vec![90, 91, 92, 93]);
assert_eq!(req.request.needed, 2..=2);
}
@ -546,7 +575,11 @@ fn retreat_from_pirates_without_a_kill_grants_no_reward() {
move_action(vec![7, 8], Position::from_offset("D2")),
0,
);
let game = execute(game, Action::Response(EventResponse::ResourceReward(ResourcePile::empty())), 0);
let game = execute(
game,
Action::Response(EventResponse::ResourceReward(ResourcePile::empty())),
0,
);
assert_retreat_round(&game, 1);
let game = execute(game, Action::Response(EventResponse::Bool(true)), 0);
assert!(game.events.is_empty());

View file

@ -140,25 +140,48 @@ fn exhausted_land_skips_when_all_eligible_spaces_have_units() {
for owner in [0, 1] {
for unit_type in [UnitType::Infantry, UnitType::Settler] {
let mut game = JSON.load_game("exhausted_land");
let positions: Vec<_> = game.player(0).cities.iter()
let positions: Vec<_> = game
.player(0)
.cities
.iter()
.flat_map(|city| city.position.neighbors())
.filter(|pos| game.try_get_any_city(*pos).is_none()
&& matches!(game.map.get(*pos), Some(Terrain::Fertile | Terrain::Forest | Terrain::Mountain)))
.filter(|pos| {
game.try_get_any_city(*pos).is_none()
&& matches!(
game.map.get(*pos),
Some(Terrain::Fertile | Terrain::Forest | Terrain::Mountain)
)
})
.collect();
assert!(!positions.is_empty());
for (index, position) in positions.iter().enumerate() {
game.player_mut(owner).units.push(Unit::new(
owner, *position, unit_type, 1000 + index as u32,
owner,
*position,
unit_type,
1000 + index as u32,
));
}
let before = game.map.tiles.clone();
let game = server::game_api::execute(game,
Action::Response(EventResponse::SelectAdvance(Advance::Storage)), 0);
assert_eq!(game.map.tiles, before, "Occupied terrain must not be exhausted");
let game = server::game_api::execute(
game,
Action::Response(EventResponse::SelectAdvance(Advance::Storage)),
0,
);
assert_eq!(
game.map.tiles, before,
"Occupied terrain must not be exhausted"
);
if let Some(handler) = game.current_event_handler() {
assert!(!matches!(handler.request,
server::content::persistent_events::PersistentEventRequest::SelectPositions(_)),
"No exhausted-land placement should remain pending");
assert!(
!matches!(
handler.request,
server::content::persistent_events::PersistentEventRequest::SelectPositions(
_
)
),
"No exhausted-land placement should remain pending"
);
}
}
}

View file

@ -117,11 +117,16 @@ fn test_standing_army() {
fn colony_does_not_count_distance_through_unexplored_regions() {
let mut game = JSON.load_game("colony");
for pos in ["D4", "D5", "D6"] {
game.map.tiles.insert(server::position::Position::from_offset(pos), server::map::Terrain::Unexplored);
game.map.tiles.insert(
server::position::Position::from_offset(pos),
server::map::Terrain::Unexplored,
);
}
let game = server::game_api::execute(game, Action::Playing(PlayingAction::EndTurn), 0);
let event = serde_json::to_value(game.current_event()).unwrap();
let choices = event["handler"]["request"]["SelectHandCards"]["choices"].as_array().unwrap();
let choices = event["handler"]["request"]["SelectHandCards"]["choices"]
.as_array()
.unwrap();
assert!(!choices.contains(&serde_json::json!({"ObjectiveCard": 17})));
assert!(choices.contains(&serde_json::json!({"ObjectiveCard": 32})));
}

View file

@ -351,8 +351,18 @@ fn high_ground_is_not_skipped_after_attacker_flanking() {
game.players[1].action_cards = vec![40];
for (player, action) in [
(0, move_action(vec![0], Position::from_offset("C1"))),
(0, Action::Response(EventResponse::SelectHandCards(vec![HandCard::ActionCard(42)]))),
(1, Action::Response(EventResponse::SelectHandCards(vec![HandCard::ActionCard(40)]))),
(
0,
Action::Response(EventResponse::SelectHandCards(vec![HandCard::ActionCard(
42,
)])),
),
(
1,
Action::Response(EventResponse::SelectHandCards(vec![HandCard::ActionCard(
40,
)])),
),
] {
game = server::game_api::execute(game, action, player);
}
@ -363,7 +373,13 @@ fn high_ground_is_not_skipped_after_attacker_flanking() {
fn check(value: &serde_json::Value) {
if let Some(roll) = value.get("CombatRoll") {
if value["player"] == 0 {
assert!(roll["rolls"].as_array().unwrap().iter().all(|r| r["bonus"] == false));
assert!(
roll["rolls"]
.as_array()
.unwrap()
.iter()
.all(|r| r["bonus"] == false)
);
}
}
match value {