refactor units (#257)

This commit is contained in:
Gregor Zeitlinger 2025-05-30 16:01:32 +02:00 • committed by GitHub
commit 2984d89e42
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
315 changed files with 5098 additions and 1266 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

View file

@ -6,6 +6,7 @@ use server::content::custom_actions::CustomActionType;
use server::map::Terrain;
use server::player::Player;
use server::resource::ResourceType;
use server::unit;
use server::unit::UnitType;
use server::wonder::Wonder;
use std::collections::HashMap;
@ -190,7 +191,7 @@ impl Assets {
)),
),
(
UnitType::Leader,
unit::LEADER_UNIT,
None,
load_png(include_bytes!("../assets/flag-svgrepo-com.png")),
),
@ -332,6 +333,17 @@ impl Assets {
"../assets/augustus-of-prima-porta-svgrepo-com.png"
)),
),
// Greece
(
CustomActionType::Idol,
load_png(include_bytes!(
"../assets/alexander-the-great-svgrepo-com.png"
)),
),
(
CustomActionType::Master,
load_png(include_bytes!("../assets/greek-pillar-svgrepo-com.png")),
),
]
.iter()
.cloned()
@ -379,7 +391,10 @@ impl Assets {
CivAssets { units }
}
pub fn unit(&self, unit_type: UnitType, player: &Player) -> &Texture2D {
pub fn unit(&self, mut unit_type: UnitType, player: &Player) -> &Texture2D {
if unit_type.is_leader() {
unit_type = unit::LEADER_UNIT;
}
self.civ
.get(&player.civilization.name)
.and_then(|c| c.units.get(&unit_type))

View file

@ -179,13 +179,7 @@ fn recruit_button<'a>(rc: &'a RenderContext, city: &'a City) -> Option<IconActio
rc.assets().unit(UnitType::Infantry, rc.shown_player),
vec!["Recruit Units".to_string()],
Box::new(|| {
RecruitAmount::new_selection(
rc.game,
city.player_index,
city.position,
Units::empty(),
None,
)
RecruitAmount::new_selection(rc.game, city.player_index, city.position, Units::empty())
}),
))
}

View file

@ -30,12 +30,8 @@ pub fn pay_construction_dialog(rc: &RenderContext, cp: &ConstructionPayment) ->
city,
),
ConstructionProject::Units(r) => {
let mut recruit = Recruit::new(&r.amount.units, cp.city_position, payment)
let recruit = Recruit::new(&r.amount.units, cp.city_position, payment)
.with_replaced_units(&r.replaced_units);
if let Some(l) = &r.amount.leader_name {
recruit = recruit.with_leader(l);
}
StateUpdate::execute_activation(
Action::Playing(PlayingAction::Recruit(recruit)),
vec![],

View file

@ -91,7 +91,7 @@ pub fn unit_request_dialog(rc: &RenderContext, r: &UnitTypeRequest) -> StateUpda
)));
}
} else {
let mut tooltip = vec![u.name().to_string()];
let mut tooltip = vec![u.name(rc.game).to_string()];
add_unit_description(&mut tooltip, *u);
show_tooltip_for_circle(rc, &tooltip, center, 20.);
}

View file

@ -211,8 +211,6 @@ fn setup_local_game() -> Game {
add_unit(&mut game, "B3", player_index1, UnitType::Settler);
add_unit(&mut game, "B3", player_index1, UnitType::Settler);
add_unit(&mut game, "B3", player_index1, UnitType::Settler);
// game.players[player_index1].active_leader =
// Some(Leader::builder("Alexander", "", "", "", "").build());
add_unit(&mut game, "C1", player_index2, UnitType::Infantry);
add_unit(&mut game, "C1", player_index2, UnitType::Infantry);

View file

@ -202,10 +202,10 @@ pub fn show_top_left(rc: &RenderContext) {
label(&format!(
"Leader {}",
if let Some(l) = &player.active_leader {
l
if let Some(l) = &player.active_leader() {
l.name(game)
} else {
"-"
"-".to_string()
}
));

View file

@ -1,13 +1,6 @@
use itertools::Itertools;
use macroquad::prelude::*;
use server::game::Game;
use server::player::{CostTrigger, Player};
use server::player_events::CostInfo;
use server::position::Position;
use server::recruit::{recruit_cost, recruit_cost_without_replaced};
use server::unit::{Unit, UnitType, Units};
use crate::client_state::{ActiveDialog, StateUpdate};
use crate::construct_ui::{ConstructionPayment, ConstructionProject};
use crate::dialog_ui::{OkTooltip, cancel_button, ok_button};
@ -16,12 +9,18 @@ use crate::select_ui;
use crate::select_ui::{CountSelector, HasCountSelectableObject, HighlightType};
use crate::tooltip::show_tooltip_for_circle;
use crate::unit_ui::{UnitSelection, add_unit_description, draw_unit_type};
use server::game::Game;
use server::player::{CostTrigger, Player};
use server::player_events::CostInfo;
use server::position::Position;
use server::recruit::{recruit_cost, recruit_cost_without_replaced};
use server::unit::UnitType::{Cavalry, Elephant, Infantry, Leader, Settler, Ship};
use server::unit::{Unit, UnitType, Units, get_units_to_replace};
#[derive(Clone)]
pub struct SelectableUnit {
pub unit_type: UnitType,
pub selectable: CountSelector,
leader_name: Option<String>,
cost: Result<CostInfo, String>,
}
@ -30,7 +29,6 @@ pub struct RecruitAmount {
player_index: usize,
city_position: Position,
pub units: Units,
pub leader_name: Option<String>,
pub selectable: Vec<SelectableUnit>,
}
@ -46,19 +44,17 @@ impl RecruitAmount {
player_index: usize,
city_position: Position,
units: Units,
leader_name: Option<&String>,
) -> StateUpdate {
let player = game.player(player_index);
let selectable: Vec<SelectableUnit> = new_units(player)
.into_iter()
.map(|u| selectable_unit(city_position, &units, leader_name, player, &u, game))
.map(|u| selectable_unit(city_position, &units, player, u, game))
.collect();
StateUpdate::OpenDialog(ActiveDialog::RecruitUnitSelection(RecruitAmount {
player_index,
city_position,
units,
leader_name: leader_name.cloned(),
selectable,
}))
}
@ -67,69 +63,44 @@ impl RecruitAmount {
fn selectable_unit(
city_position: Position,
units: &Units,
leader_name: Option<&String>,
player: &Player,
unit: &NewUnit,
unit_type: UnitType,
game: &Game,
) -> SelectableUnit {
let mut all = units.clone();
all += &unit.unit_type;
all += &unit_type;
let current: u8 = if matches!(unit.unit_type, UnitType::Leader) {
u8::from(leader_name.is_some_and(|i| *i == unit.leader_name.clone().unwrap()))
} else {
units.get(&unit.unit_type)
};
let current: u8 = units.get(&unit_type);
let cost = recruit_cost_without_replaced(
game,
player,
&all,
city_position,
unit.leader_name.as_ref().or(leader_name),
CostTrigger::WithModifiers,
);
let max = if cost.is_ok() { current + 1 } else { current };
SelectableUnit {
unit_type: unit.unit_type,
unit_type,
cost,
selectable: CountSelector {
current,
min: 0,
max,
},
leader_name: unit.leader_name.clone(),
}
}
struct NewUnit {
unit_type: UnitType,
leader_name: Option<String>,
}
impl NewUnit {
fn new(unit_type: UnitType, leader_name: Option<String>) -> NewUnit {
NewUnit {
unit_type,
leader_name,
}
}
}
fn new_units(player: &Player) -> Vec<NewUnit> {
UnitType::get_all()
fn new_units(player: &Player) -> Vec<UnitType> {
vec![Settler, Infantry, Ship, Cavalry, Elephant]
.into_iter()
.flat_map(|u| {
if u == UnitType::Leader {
player
.available_leaders
.iter()
.map(|l| NewUnit::new(UnitType::Leader, Some(l.to_string())))
.collect_vec()
} else {
vec![NewUnit::new(u, None::<String>)]
}
})
.chain(
player
.available_leaders
.iter()
.map(|l| Leader(*l))
.collect_vec(),
)
.collect()
}
@ -150,7 +121,7 @@ impl RecruitSelection {
replaced_units: Vec<u32>,
) -> RecruitSelection {
let available_units = game.player(amount.player_index).available_units();
let need_replacement = available_units.get_units_to_replace(&amount.units);
let need_replacement = get_units_to_replace(&available_units, &amount.units);
RecruitSelection {
player,
@ -171,7 +142,6 @@ impl RecruitSelection {
game.player(self.amount.player_index),
&self.amount.units,
self.amount.city_position,
self.amount.leader_name.as_ref(),
self.replaced_units.as_slice(),
CostTrigger::WithModifiers,
)
@ -222,11 +192,7 @@ pub fn select_dialog(rc: &RenderContext, a: &RecruitAmount) -> StateUpdate {
Ok(_) => format!(" ({} available with current resources)", s.selectable.max),
Err(e) => format!(" ({e})"),
};
let name = match s.leader_name.as_ref() {
None => s.unit_type.name().to_string(),
Some(n) => n.to_string(),
};
let mut tooltip = vec![format!("Recruit {}{}", name, suffix)];
let mut tooltip = vec![format!("Recruit {}{}", s.unit_type.name(game), suffix)];
add_unit_description(&mut tooltip, s.unit_type);
show_tooltip_for_circle(rc, &tooltip, p, radius);
},
@ -244,26 +210,12 @@ pub fn select_dialog(rc: &RenderContext, a: &RecruitAmount) -> StateUpdate {
|s, u| {
let mut units = s.units.clone();
units += &u.unit_type;
update_selection(
game,
s,
units,
u.leader_name.as_ref().or(s.leader_name.as_ref()),
)
update_selection(game, s, units)
},
|s, u| {
let mut units = s.units.clone();
units -= &u.unit_type;
update_selection(
game,
s,
units,
if matches!(u.unit_type, UnitType::Leader) {
None
} else {
s.leader_name.as_ref()
},
)
update_selection(game, s, units)
},
Vec2::new(0., 0.),
true,
@ -277,7 +229,6 @@ fn open_dialog(rc: &RenderContext, city: Position, sel: RecruitSelection) -> Sta
rc.shown_player,
&sel.amount.units,
city,
sel.amount.leader_name.as_ref(),
&sel.replaced_units,
CostTrigger::WithModifiers,
)
@ -287,20 +238,15 @@ fn open_dialog(rc: &RenderContext, city: Position, sel: RecruitSelection) -> Sta
rc.game.city(p, city),
&format!(
"Recruit {} in {city}",
sel.amount.units.to_string(sel.amount.leader_name.as_ref()),
sel.amount.units.to_string(Some(rc.game)),
),
ConstructionProject::Units(sel),
&cost,
)))
}
fn update_selection(
game: &Game,
s: &RecruitAmount,
units: Units,
leader_name: Option<&String>,
) -> StateUpdate {
RecruitAmount::new_selection(game, s.player_index, s.city_position, units, leader_name)
fn update_selection(game: &Game, s: &RecruitAmount, units: Units) -> StateUpdate {
RecruitAmount::new_selection(game, s.player_index, s.city_position, units)
}
pub fn replace_dialog(rc: &RenderContext, sel: &RecruitSelection) -> StateUpdate {

View file

@ -283,15 +283,8 @@ pub fn units_on_tile(game: &Game, pos: Position) -> impl Iterator<Item = (usize,
})
}
pub fn name(u: &UnitType) -> &str {
if let UnitType::Leader = u {
return "Leader";
}
u.name()
}
pub fn unit_label(unit: &Unit, army_move: bool, game: &Game) -> String {
let name = name(&unit.unit_type);
let name = unit.unit_type.name(game);
let mut notes = vec![];
if unit.unit_type.is_army_unit() && !army_move {

View file

@ -35,7 +35,8 @@ run = [
[tasks.ci]
description = "Run CI tasks server"
run = [
"rustup component add rustfmt", # should be dony by `tools` section, but doesn't work in CI
"rustup component add rustfmt", # should be dony by `tools` section, but doesn't work reliably in CI
"rustup component add clippy", # should be dony by `tools` section, but doesn't work reliably in CI
"cargo build",
"cargo fmt --check",
"cargo clippy",

View file

@ -185,7 +185,7 @@ pub(crate) trait AbilityInitializerSetup: Sized {
)
}
fn add_combat_round_start_listener(
fn add_combat_strength_listener(
self,
priority: i32,
listener: impl Fn(&Game, &Combat, &mut CombatStrength, CombatRole)

View file

@ -305,7 +305,7 @@ pub fn combat_requirement_met(
})
}
pub(crate) fn can_play_action_card(game: &Game, p: &Player, id: u8) -> Result<(), String> {
pub(crate) fn can_play_civil_card(game: &Game, p: &Player, id: u8) -> Result<(), String> {
if !p.action_cards.contains(&id) {
return Err("Action card not available".to_string());
}

View file

@ -403,7 +403,6 @@ fn recruit_actions(
player,
&next,
city.position,
None,
&[],
CostTrigger::NoModifiers,
) {

View file

@ -10,7 +10,7 @@ use crate::content::{
};
use crate::game::Game;
use crate::incident::Incident;
use crate::leader::{Leader, LeaderAbility};
use crate::leader::{Leader, LeaderInfo};
use crate::objective_card::{Objective, ObjectiveCard};
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo};
use crate::status_phase::StatusPhaseState::{ChangeGovernmentType, DetermineFirstPlayer};
@ -51,6 +51,7 @@ pub struct Cache {
civilizations_by_name: HashMap<String, Civilization>,
all_special_advances: Vec<SpecialAdvanceInfo>,
leaders: HashMap<Leader, LeaderInfo>,
}
impl Default for Cache {
@ -142,6 +143,11 @@ impl Cache {
.flat_map(|c| c.special_advances)
.sorted_by_key(|s| s.advance)
.collect(),
leaders: civilizations::get_all_uncached()
.into_iter()
.flat_map(|c| c.leaders)
.map(|l| (l.leader, l))
.collect(),
}
}
@ -330,22 +336,7 @@ impl Cache {
match name {
// "Maya" => maya::maya(), // still needs to be implemented
// for integration testing
"test0" => Civilization::new(
"test0",
vec![],
vec![
Leader::new(
"Alexander",
LeaderAbility::builder("", "").build(),
LeaderAbility::builder("", "").build(),
),
Leader::new(
"Kleopatra",
LeaderAbility::builder("", "").build(),
LeaderAbility::builder("", "").build(),
),
],
), // for testing
"test0" => Civilization::new("test0", vec![], vec![]),
"test1" => Civilization::new("test1", vec![], vec![]),
"test2" => Civilization::new("test2", vec![], vec![]),
_ => self
@ -355,6 +346,17 @@ impl Cache {
.expect("civilization not found"),
}
}
///
/// # Panics
///
/// Panics if special advance does not exist
#[must_use]
pub fn get_leader(&self, leader: &Leader) -> &LeaderInfo {
self.leaders
.get(leader)
.unwrap_or_else(|| panic!("leader not found: {leader:?}"))
}
}
fn status_phase_handlers() -> HashMap<StatusPhaseState, Builtin> {

View file

@ -1,19 +1,19 @@
use crate::content::civilizations::{BARBARIANS, PIRATES};
use crate::{leader::Leader, special_advance::SpecialAdvanceInfo};
use crate::{leader::LeaderInfo, special_advance::SpecialAdvanceInfo};
//todo add optional special starting tile
#[derive(Clone)]
pub struct Civilization {
pub name: String,
pub special_advances: Vec<SpecialAdvanceInfo>,
pub leaders: Vec<Leader>,
pub leaders: Vec<LeaderInfo>,
}
impl Civilization {
pub fn new(
name: &str,
special_advances: Vec<SpecialAdvanceInfo>,
leaders: Vec<Leader>,
leaders: Vec<LeaderInfo>,
) -> Self {
Self {
name: name.to_string(),

View file

@ -162,7 +162,7 @@ impl Combat {
let p = self.player(role);
self.fighting_units(game, p)
.iter()
.any(|&unit_id| game.player(p).get_unit(unit_id).unit_type == UnitType::Leader)
.any(|&unit_id| game.player(p).get_unit(unit_id).unit_type.is_leader())
}
#[must_use]
@ -211,7 +211,7 @@ pub(crate) fn log_round(game: &mut Game, c: &Combat) {
.collect_vec()
})
.collect::<Units>()
.to_string(game.player(c.attacker()).active_leader.as_ref())
.to_string(Some(game))
));
game.add_info_log_item(&format!(
"Defenders: {}",
@ -220,7 +220,7 @@ pub(crate) fn log_round(game: &mut Game, c: &Combat) {
.iter()
.map(|u| u.unit_type)
.collect::<Units>()
.to_string(game.player(c.defender()).active_leader.as_ref())
.to_string(Some(game))
));
}

View file

@ -634,7 +634,7 @@ fn kill_fighters(game: &mut Game, player: usize, killed_unit_ids: &[u32], c: &mu
.iter()
.map(|id| p.get_unit(*id).unit_type)
.collect::<Units>()
.to_string(p.active_leader.as_ref())
.to_string(Some(game))
));
kill_combat_units(game, c, player, killed_unit_ids);

View file

@ -1,8 +1,8 @@
use crate::combat::Combat;
use crate::combat_listeners::CombatStrength;
use crate::game::Game;
use crate::unit::UnitType::{Cavalry, Elephant, Infantry, Leader};
use crate::unit::{UnitType, Units};
use crate::unit::UnitType::{Cavalry, Elephant, Infantry};
use crate::unit::{LEADER_UNIT, UnitType, Units};
use num::Zero;
use serde::{Deserialize, Serialize};
@ -161,8 +161,8 @@ impl CombatDieRoll {
}
pub(crate) const COMBAT_DIE_SIDES: [CombatDieRoll; 12] = [
CombatDieRoll::new(1, Leader),
CombatDieRoll::new(1, Leader),
CombatDieRoll::new(1, LEADER_UNIT),
CombatDieRoll::new(1, LEADER_UNIT),
CombatDieRoll::new(2, Cavalry),
CombatDieRoll::new(2, Elephant),
CombatDieRoll::new(3, Elephant),
@ -238,18 +238,18 @@ fn dice_roll_with_leader_reroll(
) -> CombatDieRoll {
let side = roll_die(game, roll_log);
if deny_combat_abilities || side.bonus != Leader || !unit_types.has_unit(&Leader) {
if deny_combat_abilities || side.bonus != LEADER_UNIT || !unit_types.has_unit(&LEADER_UNIT) {
return side;
}
*unit_types -= &Leader;
*unit_types -= &LEADER_UNIT;
// if used, the leader grants unlimited rerolls of 1s
loop {
add_roll_log_effect(roll_log, "re-roll");
let side = roll_die(game, roll_log);
if side.bonus != Leader {
if side.bonus != LEADER_UNIT {
return side;
}
}
@ -262,6 +262,6 @@ fn add_roll_log_effect(roll_log: &mut [String], effect: &str) {
fn roll_die(game: &mut Game, roll_log: &mut Vec<String>) -> CombatDieRoll {
let roll = game.next_dice_roll();
roll_log.push(format!("{} ({}, ", roll.value, roll.bonus));
roll_log.push(format!("{} ({}, ", roll.value, roll.bonus.generic_name()));
roll.clone()
}

View file

@ -1,5 +1,5 @@
use crate::advance::Advance;
use crate::{resource_pile::ResourcePile, unit::Units};
use crate::{resource_pile::ResourcePile, unit, unit::Units};
pub const JSON_SCHEMA_VERSION: u16 = 2;
pub const MAX_CITY_PIECES: usize = 4; // i.e. city size 5
@ -27,7 +27,7 @@ pub const UNIT_LIMIT: Units = Units {
ships: 4,
cavalry: 4,
elephants: 4,
leaders: 1,
leader: Some(unit::LEADER),
};
pub const UNIT_LIMIT_BARBARIANS: Units = Units {
settlers: 0,
@ -35,7 +35,7 @@ pub const UNIT_LIMIT_BARBARIANS: Units = Units {
ships: 0,
cavalry: 4,
elephants: 4,
leaders: 0,
leader: None,
};
pub const UNIT_LIMIT_PIRATES: Units = Units {
settlers: 0,
@ -43,7 +43,7 @@ pub const UNIT_LIMIT_PIRATES: Units = Units {
ships: 4,
cavalry: 0,
elephants: 0,
leaders: 0,
leader: None,
};
pub const BUILDING_COST: ResourcePile = ResourcePile {
food: 1,

View file

@ -68,7 +68,8 @@ pub(crate) fn cultural_takeover(id: u8, tactics_card: TacticsCardFactory) -> Act
|game, s, a| {
game.add_info_log_item(&format!(
"{} selected unit to gain: {}",
s.player_name, s.choice,
s.player_name,
s.choice.non_leader_name(),
));
add_unit(
s.player_index,

View file

@ -43,7 +43,7 @@ fn war_ships() -> AdvanceBuilder {
"Ignore the first hit it the first round of combat \
when attacking with Ships or disembarking from Ships",
)
.add_combat_round_start_listener(5, |g, c, s, role| {
.add_combat_strength_listener(5, |g, c, s, role| {
let st = &c.stats;
let disembark = role.is_attacker() && g.map.is_sea(st.attacker.position);
let sea_battle = g.map.is_sea(st.defender.position);

View file

@ -144,7 +144,7 @@ fn fanaticism() -> AdvanceBuilder {
If you lose the battle, you get 1 free Infantry Unit after the battle and \
place it in one of your cities.",
)
.add_combat_round_start_listener(1, |game, c, s, _role| {
.add_combat_strength_listener(1, |game, c, s, _role| {
if c.first_round() && c.defender_temple(game) {
s.extra_combat_value += 2;
s.roll_log

View file

@ -53,7 +53,10 @@ pub(crate) fn trade_route_log(
for t in trade_routes {
log.push(format!(
"{} at {} traded with city at {}",
game.players[player_index].get_unit(t.unit_id).unit_type,
game.players[player_index]
.get_unit(t.unit_id)
.unit_type
.non_leader_name(),
t.from,
t.to,
));

View file

@ -33,7 +33,7 @@ fn tactics() -> AdvanceBuilder {
)
.with_advance_bonus(CultureToken)
.with_unlocked_building(Fortress)
.add_combat_round_start_listener(3, fortress),
.add_combat_strength_listener(3, fortress),
)
}
@ -156,7 +156,7 @@ fn steel_weapons() -> AdvanceBuilder {
add_steel_weapons(s.player_index, c);
},
)
.add_combat_round_start_listener(2, use_steel_weapons)
.add_combat_strength_listener(2, use_steel_weapons)
}
fn draft() -> AdvanceBuilder {

View file

@ -1,9 +1,9 @@
mod greece;
pub(crate) mod greece;
pub(crate) mod maya;
pub(crate) mod rome;
use crate::civilization::Civilization;
use crate::leader::{Leader, LeaderAbility};
use crate::leader::{Leader, LeaderAbility, LeaderInfo};
pub const BARBARIANS: &str = "Barbarians";
pub const PIRATES: &str = "Pirates";
@ -21,43 +21,44 @@ pub fn get_all_uncached() -> Vec<Civilization> {
"Federation",
vec![],
vec![
test_leader("James T. Kirk"),
test_leader("Kathryn Janeway"),
test_leader("Spock"),
test_leader(Leader::Kirk, "James T. Kirk"),
test_leader(Leader::Janeway, "Kathryn Janeway"),
test_leader(Leader::Spock, "Spock"),
],
),
Civilization::new(
"Borg",
vec![],
vec![
test_leader("Borg Queen"),
test_leader("Seven of Nine"),
test_leader("Jean Luc Picard"),
test_leader(Leader::BorgQueen, "Borg Queen"),
test_leader(Leader::SevenOfNine, "Seven of Nine"),
test_leader(Leader::Picard, "Jean Luc Picard"),
],
),
Civilization::new(
"Klingons",
vec![],
vec![
test_leader("Khan"),
test_leader("Kahless"),
test_leader("Worf"),
test_leader(Leader::Khan, "Khan"),
test_leader(Leader::Kahless, "Kahless"),
test_leader(Leader::Worf, "Worf"),
],
),
Civilization::new(
"Romulans",
vec![],
vec![
test_leader("Sela"),
test_leader("Narek"),
test_leader("Tomalak"),
test_leader(Leader::Sela, "Sela"),
test_leader(Leader::Narek, "Narek"),
test_leader(Leader::Tomalak, "Tomalak"),
],
),
]
}
fn test_leader(name: &str) -> Leader {
Leader::new(
fn test_leader(leader: Leader, name: &str) -> LeaderInfo {
LeaderInfo::new(
leader,
name,
LeaderAbility::builder("", "").build(),
LeaderAbility::builder("", "").build(),

View file

@ -1,13 +1,19 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::advance::Advance;
use crate::advance::{Advance, gain_advance_without_payment};
use crate::card::HandCard;
use crate::civilization::Civilization;
use crate::combat::update_combat_strength;
use crate::combat_listeners::CombatStrength;
use crate::content::advances::warfare::draft_cost;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::persistent_events::PositionRequest;
use crate::content::persistent_events::{AdvanceRequest, HandCardsRequest, PositionRequest};
use crate::game::Game;
use crate::leader::{Leader, LeaderAbility, LeaderInfo, leader_position};
use crate::map::{block_has_player_city, get_map_setup};
use crate::payment::PaymentConversion;
use crate::player::gain_resources;
use crate::player::{Player, gain_resources};
use crate::playing_actions::{PlayingAction, PlayingActionType};
use crate::resource_pile::ResourcePile;
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo, SpecialAdvanceRequirement};
use itertools::Itertools;
@ -16,7 +22,7 @@ pub(crate) fn greece() -> Civilization {
Civilization::new(
"Greece",
vec![study(), sparta(), hellenistic_culture(), city_states()],
vec![],
vec![alexander(), leonidas(), pericles()],
)
}
@ -119,8 +125,7 @@ fn city_states() -> SpecialAdvanceInfo {
if game
.player_mut(player_index)
.event_info
.insert("city_states".to_string(), "used".to_string())
.is_some()
.contains_key("city_states")
{
return None;
}
@ -167,8 +172,203 @@ fn city_states() -> SpecialAdvanceInfo {
let p = game.player_mut(s.player_index);
p.get_city_mut(choice).activate();
p.get_city_mut(*position).increase_mood_state();
p.event_info
.insert("city_states".to_string(), "used".to_string());
}
},
)
.build()
}
const IDOL: &str = "As a free action, pay 1 culture token to \
play an action card as a free action";
fn alexander() -> LeaderInfo {
LeaderInfo::new(
Leader::Alexander,
"Alexander the Great",
LeaderAbility::builder("Idol", IDOL)
.add_custom_action(CustomActionType::Idol)
.build(),
LeaderAbility::builder(
"Ruler of the World",
"In a land battle, gain 1 combat value for each region
with a city you control, except the starting region.",
)
.add_combat_strength_listener(7, |game, c, s, r| {
if !c.is_sea_battle(game) {
let setup = get_map_setup(game.human_players_count());
let player = c.player(r);
let extra = setup
.free_positions
.into_iter()
.chain(
setup
.home_positions
.iter()
.enumerate()
.filter_map(|(i, h)| (i != player).then_some(h.position.clone())),
)
.filter(|b| block_has_player_city(game, b, player))
.count();
s.extra_combat_value += extra as i8;
s.roll_log
.push(format!("Ruler of the World adds {extra} combat value",));
}
})
.build(),
)
}
pub(crate) fn use_idol() -> Builtin {
Builtin::builder("Idol", IDOL)
.add_hand_card_request(
|event| &mut event.custom_action,
0,
|game, player, _| {
Some(HandCardsRequest::new(
idol_cards(game, game.player(player), &ResourcePile::empty()),
1..=1,
"Select an action card to play as a free action using Idol",
))
},
|game, s, _| {
let HandCard::ActionCard(id) = s.choice[0] else {
panic!("expected action card");
};
game.add_info_log_item(&format!(
"{} decided to play {} as a free action using Idol",
s.player_name,
game.cache.get_civil_card(id).name
));
PlayingAction::ActionCard(id)
.execute_without_action_cost(game, s.player_index)
.expect("playing action card with Idol");
},
)
.build()
}
pub(crate) fn idol_cards(game: &Game, p: &Player, extra_cost: &ResourcePile) -> Vec<HandCard> {
p.action_cards
.iter()
.filter_map(|&a| {
let action_cost = PlayingActionType::ActionCard(a).cost(game);
if action_cost.free {
// can play directly
return None;
}
let mut payment_options = action_cost.payment_options(p);
payment_options.default += extra_cost.clone();
p.can_afford(&payment_options)
.then_some(HandCard::ActionCard(a))
})
.collect_vec()
}
fn leonidas() -> LeaderInfo {
LeaderInfo::new(
Leader::Leonidas,
"Leonidas I",
LeaderAbility::builder(
"That's Sparta",
"Gain 1 culture token when recruiting in the city where Leonidas is present.",
)
.add_simple_persistent_event_listener(
|event| &mut event.recruit,
4,
|game, player_index, _player_name, r| {
if leader_position(game.player(player_index)) == r.city_position {
gain_resources(
game,
player_index,
ResourcePile::culture_tokens(1),
|name, pile| format!("{name} gained {pile} for That's Sparta"),
);
}
},
)
.build(),
LeaderAbility::builder(
"Hero of Thermopylae",
"In land battle: \
Get +2 combat value per army unit you have less than your enemy.",
)
.add_combat_strength_listener(8, |game, c, s, r| {
let p = c.player(r);
let pl = c.fighting_units(game, p).len();
let op = c.fighting_units(game, c.opponent(p)).len();
let extra = op.saturating_sub(pl) * 2;
if extra > 0 {
s.extra_combat_value += extra as i8;
s.roll_log
.push(format!("Hero of Thermopylae adds {extra} combat value",));
}
})
.build(),
)
}
const MASTER: &str = "Pericles is in a Happy city: Gain 1 education advance for free.";
fn pericles() -> LeaderInfo {
LeaderInfo::new(
Leader::Pericles,
"Pericles",
LeaderAbility::builder("Master", MASTER)
.add_custom_action(CustomActionType::Master)
.build(),
LeaderAbility::builder("Admiral", "In Sea battles: Gain +2 combat value")
.add_combat_strength_listener(20, |game, c, s, _r| {
if c.is_sea_battle(game) {
s.extra_combat_value += 2;
s.roll_log.push("Admiral adds +2 combat value".to_string());
}
})
.build(),
)
}
pub(crate) fn use_master() -> Builtin {
Builtin::builder("Master", MASTER)
.add_advance_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
let player = game.player(player_index);
Some(AdvanceRequest::new(master_education_advances(game, player)))
},
|game, s, c| {
let advance = s.choice;
game.add_info_log_item(&format!(
"{} decided to gain {} for free using Master",
s.player_name,
advance.name(game)
));
gain_advance_without_payment(
game,
advance,
s.player_index,
c.payment.clone(),
true,
);
},
)
.build()
}
pub(crate) fn master_education_advances(game: &Game, player: &Player) -> Vec<Advance> {
game.cache
.get_advance_group("Education")
.advances
.iter()
.filter_map(|a| {
player
.can_advance_free(a.advance, game)
.then_some(a.advance)
})
.collect_vec()
}

View file

@ -8,7 +8,7 @@ use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::persistent_events::{HandCardsRequest, PaymentRequest, PositionRequest};
use crate::game::Game;
use crate::leader::{Leader, LeaderAbility, LeaderAbilityBuilder, leader_position};
use crate::leader::{Leader, LeaderAbility, LeaderAbilityBuilder, LeaderInfo, leader_position};
use crate::map::{block_for_position, block_has_player_city};
use crate::objective_card::{discard_objective_card, gain_objective_card_from_pile};
use crate::payment::{
@ -26,7 +26,7 @@ pub(crate) fn rome() -> Civilization {
Civilization::new(
"Rome",
vec![aqueduct(), roman_roads(), captivi(), provinces()],
vec![augustus(), ceasar(), sulla()],
vec![augustus(), caesar(), sulla()],
)
}
@ -170,8 +170,9 @@ fn provinces() -> SpecialAdvanceInfo {
.build()
}
fn augustus() -> Leader {
Leader::new(
fn augustus() -> LeaderInfo {
LeaderInfo::new(
Leader::Augustus,
"Augustus",
LeaderAbility::builder("Princeps", PRINCEPS)
.add_custom_action(CustomActionType::Princeps)
@ -181,7 +182,7 @@ fn augustus() -> Leader {
"If you don't own a city in the region: \
Gain 2 combat value in every combat round",
)
.add_combat_round_start_listener(6, |game, c, s, r| {
.add_combat_strength_listener(6, |game, c, s, r| {
if c.has_leader(r, game)
&& !block_has_player_city(
game,
@ -275,8 +276,9 @@ pub(crate) fn validate_princeps_cards(cards: &[HandCard]) -> Result<(), String>
}
}
fn ceasar() -> Leader {
Leader::new(
fn caesar() -> LeaderInfo {
LeaderInfo::new(
Leader::Caesar,
"Gaius Julius Caesar",
LeaderAbility::builder(
"Statesman",
@ -324,8 +326,9 @@ fn ceasar() -> Leader {
)
}
fn sulla() -> Leader {
Leader::new(
fn sulla() -> LeaderInfo {
LeaderInfo::new(
Leader::Sulla,
"Sulla",
add_barbarian_control(
LeaderAbility::builder(
@ -353,7 +356,7 @@ fn sulla() -> Leader {
"Civilizer",
"In every combat round against barbarians: Gain 2 combat value",
)
.add_combat_round_start_listener(5, |game, c, s, r| {
.add_combat_strength_listener(5, |game, c, s, r| {
if c.has_leader(r, game) && c.is_barbarian_battle(r, game) {
s.extra_combat_value += 2;
s.roll_log.push("Sulla adds 2 combat value".to_string());
@ -366,9 +369,8 @@ fn sulla() -> Leader {
pub(crate) fn owner_of_sulla_in_range(position: Position, game: &Game) -> Option<usize> {
// Check if Sulla is within 2 spaces of the given position
game.players.iter().find_map(|p| {
p.active_leader
.as_ref()
.is_some_and(|l| l == "Sulla" && leader_position(p).distance(position) <= 2)
p.active_leader()
.is_some_and(|l| l == Leader::Sulla && leader_position(p).distance(position) <= 2)
.then_some(p.index)
})
}

View file

@ -5,6 +5,9 @@ use crate::content::advances::culture::{sports_options, use_sports, use_theaters
use crate::content::advances::democracy::use_civil_liberties;
use crate::content::advances::economy::{use_bartering, use_taxes};
use crate::content::builtin::Builtin;
use crate::content::civilizations::greece::{
idol_cards, master_education_advances, use_idol, use_master,
};
use crate::content::civilizations::rome::{use_aqueduct, use_princeps};
use crate::content::persistent_events::{
PersistentEventType, TriggerPersistentEventParams, trigger_persistent_event_with_listener,
@ -101,6 +104,8 @@ pub enum CustomActionType {
// Greece
HellenisticInfluenceCultureAttempt,
Idol,
Master,
}
impl CustomActionType {
@ -140,6 +145,10 @@ impl CustomActionType {
CustomActionType::Aqueduct => {
CustomActionType::free_and_advance_cost_without_discounts()
}
CustomActionType::Idol => CustomActionType::free(ResourcePile::culture_tokens(1)),
CustomActionType::Master => {
CustomActionInfo::new(false, None, ActionResourceCost::Tokens(1))
}
}
}
@ -246,6 +255,8 @@ impl Display for CustomActionType {
CustomActionType::HellenisticInfluenceCultureAttempt => {
write!(f, "Hellenistic Culture")
}
CustomActionType::Idol => write!(f, "Idol"),
CustomActionType::Master => write!(f, "Master"),
}
}
}
@ -264,6 +275,8 @@ pub(crate) fn custom_action_builtins() -> HashMap<CustomActionType, Builtin> {
(CustomActionType::GreatStatue, use_great_statue()),
(CustomActionType::Aqueduct, use_aqueduct()),
(CustomActionType::Princeps, use_princeps()),
(CustomActionType::Idol, use_idol()),
(CustomActionType::Master, use_master()),
])
}
@ -315,6 +328,8 @@ pub(crate) fn can_play_custom_action(
CustomActionType::Princeps => game
.try_get_any_city(leader_position(p))
.is_some_and(City::can_activate),
CustomActionType::Idol => !idol_cards(game, p, &ResourcePile::culture_tokens(1)).is_empty(),
CustomActionType::Master => !master_education_advances(game, p).is_empty(),
_ => true,
};
if !can_play {

View file

@ -162,7 +162,7 @@ pub(crate) fn kill_incident_units(game: &mut Game, s: &SelectedChoice<Vec<u32>>)
.iter()
.map(|u| {
let unit = p.get_unit(*u);
format!("{} at {}", unit.unit_type, unit.position)
format!("{} at {}", unit.unit_type.name(game), unit.position)
})
.join(", ")
));

View file

@ -324,7 +324,8 @@ pub(crate) fn great_commander() -> Objective {
let o = s.opponent(player);
let not_more_fighters = s.player(player).fighters(b).amount() <= o.fighters(b).amount();
if s.is_winner(player) && s.player(player).present.leaders > 0 && not_more_fighters {
if s.is_winner(player) && s.player(player).present.leader.is_some() && not_more_fighters
{
objective_is_ready(game.player_mut(player), name);
}
},
@ -341,7 +342,7 @@ pub(crate) fn brutus() -> Objective {
|game, player, _, s| {
let l = &s.opponent(player).losses;
if l.leaders > 0
if l.leader.is_some()
&& l.clone()
.to_vec()
.iter()

View file

@ -239,7 +239,7 @@ pub(crate) fn unit_versatility(objective: &str, unit_type: UnitType) -> Objectiv
objective,
&format!(
"You have at least 3 army groups with at least 1 {} unit each.",
unit_type.name()
unit_type.non_leader_name()
),
)
.status_phase_check(move |_game, player| {

View file

@ -381,7 +381,13 @@ pub(crate) fn martyr(id: u8) -> TacticsCard {
game.add_info_log_item(&format!(
"{} sacrifices {} using Martyr",
game.player_name(s.player_index),
a_or_an(game.player(s.player_index).get_unit(unit).unit_type.name())
a_or_an(
&game
.player(s.player_index)
.get_unit(unit)
.unit_type
.name(game)
)
));
kill_combat_units(game, &mut r.combat, s.player_index, &[unit]);
},
@ -439,7 +445,13 @@ pub(crate) fn archers(id: u8) -> TacticsCard {
game.add_info_log_item(&format!(
"{} sacrifices {} for Archers",
game.player_name(s.player_index),
a_or_an(game.player(s.player_index).get_unit(unit).unit_type.name())
a_or_an(
&game
.player(s.player_index)
.get_unit(unit)
.unit_type
.name(game)
)
));
kill_combat_units(game, &mut r.combat, s.player_index, &[unit]);
},

View file

@ -8,6 +8,7 @@ use crate::content::custom_actions::CustomActionType;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::PersistentEventState;
use crate::game::{Game, GameContext, GameOptions, GameState};
use crate::leader::Leader;
use crate::log::ActionLogAge;
use crate::map::{Map, MapData};
use crate::objective_card::init_objective_card;
@ -235,11 +236,8 @@ pub struct PlayerData {
units: Vec<UnitData>,
civilization: String,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
active_leader: Option<String>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
available_leaders: Vec<String>,
available_leaders: Vec<Leader>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
advances: Vec<Advance>,
@ -257,7 +255,7 @@ pub struct PlayerData {
completed_objectives: Vec<String>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
captured_leaders: Vec<String>,
captured_leaders: Vec<Leader>,
#[serde(default)]
#[serde(skip_serializing_if = "f32::is_zero")]
event_victory_points: f32,
@ -288,7 +286,6 @@ pub struct PlayerData {
///
/// Panics if elements like wonders or advances don't exist
fn initialize_player(data: PlayerData, game: &mut Game, all: &[Builtin]) {
let leader = data.active_leader.clone();
let objective_cards = data.objective_cards.clone();
let player = player_from_data(data, game);
let player_index = player.index;
@ -296,8 +293,8 @@ fn initialize_player(data: PlayerData, game: &mut Game, all: &[Builtin]) {
builtin::init_player(game, player_index, all);
advance::init_player(game, player_index);
if let Some(leader) = leader {
Player::with_leader(&leader, game, player_index, |game, leader| {
if let Some(leader) = game.player(player_index).active_leader() {
Player::with_leader(leader, game, player_index, |game, leader| {
leader.listeners.init(game, player_index);
});
}
@ -353,7 +350,6 @@ fn player_from_data(data: PlayerData, game: &Game) -> Player {
events: PlayerEvents::new(),
destroyed_structures: DestroyedStructures::from_data(data.destroyed_structures),
units,
active_leader: data.active_leader,
available_leaders: data.available_leaders,
great_library_advance: data.great_library_advance,
special_advances: civilization
@ -413,7 +409,6 @@ pub fn player_data(player: Player) -> PlayerData {
destroyed_structures: player.destroyed_structures.data(),
units,
civilization: player.civilization.name,
active_leader: player.active_leader,
available_leaders: player.available_leaders.into_iter().collect(),
advances: player.advances.iter().sorted_by_key(Advance::id).collect(),
great_library_advance: player.great_library_advance,
@ -450,7 +445,6 @@ pub fn cloned_player_data(player: &Player) -> PlayerData {
destroyed_structures: player.destroyed_structures.cloned_data(),
units,
civilization: player.civilization.name.clone(),
active_leader: player.active_leader.clone(),
available_leaders: player.available_leaders.clone(),
advances: player.advances.iter().sorted_by_key(Advance::id).collect(),
great_library_advance: player.great_library_advance,

View file

@ -1,20 +1,64 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::ability_initializer::{AbilityInitializerBuilder, AbilityListeners};
use crate::events::EventOrigin;
use crate::game::Game;
use crate::player::Player;
use crate::position::Position;
use crate::unit::UnitType;
use serde::{Deserialize, Serialize};
#[derive(Clone)]
pub struct Leader {
pub name: String,
pub abilities: Vec<LeaderAbility>,
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Hash)]
pub enum Leader {
// Test
Kirk,
Janeway,
Spock,
BorgQueen,
SevenOfNine,
Picard,
Khan,
Kahless,
Worf,
Sela,
Narek,
Tomalak,
// for Egypt later
Kleopatra,
// Rome
Augustus,
Caesar,
Sulla,
// Greece
Alexander,
Leonidas,
Pericles,
}
impl Leader {
#[must_use]
pub fn new(name: &str, first_ability: LeaderAbility, second_ability: LeaderAbility) -> Leader {
pub fn name(&self, game: &Game) -> String {
game.cache.get_leader(self).name.clone()
}
}
#[derive(Clone)]
pub struct LeaderInfo {
pub leader: Leader,
pub name: String,
pub abilities: Vec<LeaderAbility>,
}
impl LeaderInfo {
#[must_use]
pub fn new(
leader: Leader,
name: &str,
first_ability: LeaderAbility,
second_ability: LeaderAbility,
) -> LeaderInfo {
Self {
leader,
name: name.to_string(),
abilities: vec![first_ability, second_ability],
}
@ -75,6 +119,6 @@ pub(crate) fn leader_position(player: &Player) -> Position {
player
.units
.iter()
.find_map(|unit| (unit.unit_type == UnitType::Leader).then_some(unit.position))
.find_map(|unit| unit.unit_type.is_leader().then_some(unit.position))
.expect("unit not found")
}

View file

@ -157,7 +157,7 @@ fn format_playing_action_log_item(action: &PlayingAction, game: &Game) -> String
),
PlayingAction::Construct(c) => format_construct_log_item(game, player, &player_name, c),
PlayingAction::Collect(c) => format_collect_log_item(player, &player_name, c),
PlayingAction::Recruit(r) => format_recruit_log_item(player, &player_name, r),
PlayingAction::Recruit(r) => format_recruit_log_item(player, &player_name, r, game),
PlayingAction::IncreaseHappiness(i) => format_happiness_increase(player, &player_name, i),
PlayingAction::InfluenceCultureAttempt(c) => {
format_cultural_influence_attempt_log_item(game, player.index, &player_name, c)
@ -241,7 +241,12 @@ pub(crate) fn format_city_happiness_increase(
)
}
fn format_recruit_log_item(player: &Player, player_name: &String, r: &Recruit) -> String {
fn format_recruit_log_item(
player: &Player,
player_name: &String,
r: &Recruit,
game: &Game,
) -> String {
let city_position = &r.city_position;
let units = &r.units;
let payment = &r.payment;
@ -262,7 +267,7 @@ fn format_recruit_log_item(player: &Player, player_name: &String, r: &Recruit) -
);
format!(
"{player_name} paid {payment} to recruit {} in the city at {city_position}{mood}{replace_str}{replace_pos}",
units.to_string(r.leader_name.as_ref())
units.to_string(Some(game))
)
}
@ -366,7 +371,7 @@ pub(crate) fn move_action_log(game: &Game, player: &Player, m: &MoveUnits) -> St
.iter()
.map(|unit| player.get_unit(*unit).unit_type)
.collect::<Units>()
.to_string(player.active_leader.as_ref());
.to_string(Some(game));
let start = player.get_unit(m.units[0]).position;
let start_is_water = game.map.is_sea(start);
let dest = m.destination;

View file

@ -2,7 +2,7 @@ use crate::advance::{Advance, base_advance_cost, player_government};
use crate::city_pieces::DestroyedStructures;
use crate::consts::{STACK_LIMIT, UNIT_LIMIT_BARBARIANS, UNIT_LIMIT_PIRATES};
use crate::events::{Event, EventOrigin};
use crate::leader::LeaderAbility;
use crate::leader::{Leader, LeaderAbility};
use crate::payment::{PaymentOptions, PaymentReason};
use crate::player_events::{CostInfo, TransientEvents};
use crate::special_advance::SpecialAdvance;
@ -19,7 +19,7 @@ use crate::{
},
content::custom_actions::CustomActionType,
game::Game,
leader::Leader,
leader::LeaderInfo,
player_events::PlayerEvents,
position::Position,
resource_pile::ResourcePile,
@ -27,6 +27,7 @@ use crate::{
utils,
};
use enumset::EnumSet;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering::{self, *};
use std::collections::HashMap;
@ -50,8 +51,7 @@ pub struct Player {
pub destroyed_structures: DestroyedStructures,
pub units: Vec<Unit>,
pub civilization: Civilization,
pub active_leader: Option<String>,
pub available_leaders: Vec<String>,
pub available_leaders: Vec<Leader>,
pub advances: EnumSet<Advance>,
pub great_library_advance: Option<Advance>,
pub special_advances: EnumSet<SpecialAdvance>,
@ -59,7 +59,7 @@ pub struct Player {
pub wonders_owned: EnumSet<Wonder>, // transient
pub incident_tokens: u8,
pub completed_objectives: Vec<String>,
pub captured_leaders: Vec<String>,
pub captured_leaders: Vec<Leader>,
pub event_victory_points: f32,
pub custom_actions: HashMap<CustomActionType, EventOrigin>,
pub wonder_cards: Vec<Wonder>,
@ -102,12 +102,11 @@ impl Player {
cities: Vec::new(),
destroyed_structures: DestroyedStructures::new(),
units: Vec::new(),
active_leader: None,
available_leaders: civilization
.leaders
.iter()
.map(|l| l.name.clone())
.collect(),
.map(|leader| leader.leader)
.collect_vec(),
civilization,
advances: EnumSet::empty(),
special_advances: EnumSet::empty(),
@ -137,12 +136,12 @@ impl Player {
///
/// Panics if the leader does not exist
#[must_use]
pub fn get_leader(&self, name: &str) -> &Leader {
pub fn get_leader(&self, name: Leader) -> &LeaderInfo {
self.civilization
.leaders
.iter()
.find(|leader| leader.name == name)
.unwrap_or_else(|| panic!("Leader {name} not found"))
.find(|leader| leader.leader == name)
.unwrap_or_else(|| panic!("Leader {name:?} not found"))
}
///
@ -159,7 +158,7 @@ impl Player {
}
pub(crate) fn with_leader(
leader: &str,
leader: Leader,
game: &mut Game,
player_index: usize,
f: impl FnOnce(&mut Game, &LeaderAbility) + Clone,
@ -168,7 +167,7 @@ impl Player {
.civilization
.leaders
.iter()
.position(|l| l.name == leader)
.position(|l| l.leader == leader)
.expect("player should have the leader");
let l = game.players[player_index].civilization.leaders.remove(pos);
for a in &l.abilities {
@ -181,10 +180,10 @@ impl Player {
}
#[must_use]
pub fn available_leaders(&self) -> Vec<&Leader> {
pub fn available_leaders(&self) -> Vec<&LeaderInfo> {
self.available_leaders
.iter()
.map(|name| self.get_leader(name))
.map(|name| self.get_leader(*name))
.collect()
}
@ -551,6 +550,17 @@ impl Player {
.collect()
}
#[must_use]
pub fn active_leader(&self) -> Option<Leader> {
self.units.iter().find_map(|unit| {
if let UnitType::Leader(l) = unit.unit_type {
Some(l)
} else {
None
}
})
}
pub(crate) fn trigger_event<T, U, V>(
&self,
event: fn(&TransientEvents) -> &Event<T, U, V, ()>,

View file

@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::{can_play_action_card, play_action_card};
use crate::action_card::{can_play_civil_card, play_action_card};
use crate::advance::{AdvanceAction, base_advance_cost, gain_advance_without_payment};
use crate::city::found_city;
use crate::collect::{PositionCollection, collect};
@ -56,9 +56,6 @@ pub struct Recruit {
pub city_position: Position,
pub payment: ResourcePile,
#[serde(default)]
#[serde(skip_serializing_if = "Option::is_none")]
pub leader_name: Option<String>,
#[serde(default)]
#[serde(skip_serializing_if = "Vec::is_empty")]
pub replaced_units: Vec<u32>,
}
@ -70,17 +67,10 @@ impl Recruit {
units: units.clone(),
city_position,
payment,
leader_name: None,
replaced_units: Vec::new(),
}
}
#[must_use]
pub fn with_leader(mut self, leader_name: &str) -> Self {
self.leader_name = Some(leader_name.to_string());
self
}
#[must_use]
pub fn with_replaced_units(mut self, replaced_units: &[u32]) -> Self {
self.replaced_units = replaced_units.to_vec();
@ -144,7 +134,7 @@ impl PlayingActionType {
can_play_custom_action(game, p, *c)?;
}
PlayingActionType::ActionCard(id) => {
can_play_action_card(game, p, *id)?;
can_play_civil_card(game, p, *id)?;
}
PlayingActionType::WonderCard(name) => {
if !p.wonder_cards.contains(name) {
@ -213,7 +203,15 @@ impl PlayingAction {
game.actions_left -= 1;
}
let origin_override = match playing_action_type {
self.execute_without_action_cost(game, player_index)
}
pub(crate) fn execute_without_action_cost(
self,
game: &mut Game,
player_index: usize,
) -> Result<(), String> {
let origin_override = match self.playing_action_type() {
PlayingActionType::Custom(c) => {
if let Some(key) = c.info().once_per_turn {
game.players[player_index]
@ -337,6 +335,7 @@ fn assert_allowed(
#[derive(Clone, Debug, PartialEq)]
pub enum ActionResourceCost {
Resources(ResourcePile),
Tokens(u8),
AdvanceCostWithoutDiscount,
}
@ -377,6 +376,9 @@ impl ActionCost {
ActionResourceCost::Resources(c) => {
PaymentOptions::resources(player, PaymentReason::ActionCard, c.clone())
}
ActionResourceCost::Tokens(tokens) => {
PaymentOptions::tokens(player, PaymentReason::ActionCard, *tokens)
}
ActionResourceCost::AdvanceCostWithoutDiscount => base_advance_cost(player),
}
}

View file

@ -2,6 +2,7 @@ use crate::combat;
use crate::consts::STACK_LIMIT;
use crate::content::persistent_events::PersistentEventType;
use crate::game::Game;
use crate::leader::Leader;
use crate::map::home_position;
use crate::payment::{PaymentOptions, PaymentReason};
use crate::player::{CostTrigger, Player, add_unit};
@ -18,7 +19,6 @@ pub(crate) fn recruit(game: &mut Game, player_index: usize, r: Recruit) -> Resul
game.player(player_index),
&r.units,
r.city_position,
r.leader_name.as_ref(),
&r.replaced_units,
game.execute_cost_trigger(),
)?;
@ -27,24 +27,15 @@ pub(crate) fn recruit(game: &mut Game, player_index: usize, r: Recruit) -> Resul
// kill separately, because they may be on different positions
kill_units(game, &[*unit], player_index, None);
}
if let Some(leader_name) = &r.leader_name {
if let Some(previous_leader) = game.player_mut(player_index).active_leader.take() {
Player::with_leader(
&previous_leader,
game,
player_index,
|game, previous_leader| {
previous_leader.listeners.deinit(game, player_index);
},
);
}
set_active_leader(game, leader_name.clone(), player_index);
}
let player = game.player_mut(player_index);
let vec = r.units.clone().to_vec();
player.units.reserve_exact(vec.len());
player.get_city_mut(r.city_position).activate();
for unit_type in vec {
if let UnitType::Leader(l) = &unit_type {
set_active_leader(game, *l, player_index);
}
let position = match &unit_type {
UnitType::Ship => game
.player(player_index)
@ -59,14 +50,13 @@ pub(crate) fn recruit(game: &mut Game, player_index: usize, r: Recruit) -> Resul
Ok(())
}
fn set_active_leader(game: &mut Game, leader_name: String, player_index: usize) {
fn set_active_leader(game: &mut Game, leader: Leader, player_index: usize) {
game.players[player_index]
.available_leaders
.retain(|name| name != &leader_name);
Player::with_leader(&leader_name, game, player_index, |game, leader| {
.retain(|name| name != &leader);
Player::with_leader(leader, game, player_index, |game, leader| {
leader.listeners.one_time_init(game, player_index);
});
game.player_mut(player_index).active_leader = Some(leader_name);
}
pub(crate) fn on_recruit(game: &mut Game, player_index: usize, r: Recruit) {
@ -119,25 +109,30 @@ pub fn recruit_cost(
player: &Player,
units: &Units,
city_position: Position,
leader_name: Option<&String>,
replaced_units: &[u32],
execute: CostTrigger,
) -> Result<CostInfo, String> {
let mut require_replace = units.clone();
for t in player.available_units().to_vec() {
let a = require_replace.get_mut(&t);
if *a > 0 {
*a -= 1;
if require_replace.get_amount(&t) > 0 {
require_replace -= &t;
}
}
let replaced_units = replaced_units
.iter()
.map(|id| player.get_unit(*id).unit_type)
.map(|id| {
let unit_type = player.get_unit(*id).unit_type;
if unit_type.is_leader() {
require_replace.leader.map_or(unit_type, UnitType::Leader)
} else {
unit_type
}
})
.collect();
if require_replace != replaced_units {
return Err("Invalid replacement".to_string());
}
recruit_cost_without_replaced(game, player, units, city_position, leader_name, execute)
recruit_cost_without_replaced(game, player, units, city_position, execute)
}
///
@ -149,10 +144,10 @@ pub fn recruit_cost_without_replaced(
player: &Player,
units: &Units,
city_position: Position,
leader_name: Option<&String>,
execute: CostTrigger,
) -> Result<CostInfo, String> {
let city = player.get_city(city_position);
if city.pieces.market.is_none()
&& (units.elephants > 0
|| (units.cavalry > 0 && !is_cavalry_province_city(player, city_position, game)))
@ -164,7 +159,7 @@ pub fn recruit_cost_without_replaced(
}
for (t, a) in units.clone() {
let avail = player.unit_limit().get(&t);
let avail = player.unit_limit().get_amount(&t);
if a > avail {
return Err(format!("Only have {avail} {t:?} - not {a}"));
}
@ -202,14 +197,12 @@ pub fn recruit_cost_without_replaced(
return Err("Too many units in stack".to_string());
}
let match_leader = match units.leaders {
0 => leader_name.is_none(),
1 => leader_name.is_some_and(|n| player.available_leaders.contains(n)),
_ => false,
};
if !match_leader {
return Err("Invalid leader".to_string());
if let Some(l) = units.leader {
if !player.available_leaders.contains(&l) {
return Err(format!("Leader {l:?} not available"));
}
}
Ok(cost)
}

View file

@ -2,10 +2,7 @@ use UnitType::*;
use itertools::Itertools;
use num::Zero;
use serde::{Deserialize, Serialize};
use std::{
fmt::Display,
ops::{AddAssign, SubAssign},
};
use std::ops::{AddAssign, SubAssign};
use crate::ability_initializer::AbilityInitializerSetup;
use crate::city::is_valid_city_terrain;
@ -17,7 +14,7 @@ use crate::explore::is_any_ship;
use crate::game::GameState;
use crate::movement::{CurrentMove, MovementRestriction};
use crate::player::{Player, remove_unit};
use crate::{game::Game, position::Position, resource_pile::ResourcePile, utils};
use crate::{game::Game, leader, position::Position, resource_pile::ResourcePile, unit, utils};
#[readonly::make]
#[derive(Clone)]
@ -151,27 +148,43 @@ pub enum UnitType {
Ship,
Cavalry,
Elephant,
Leader,
Leader(leader::Leader),
}
impl UnitType {
#[must_use]
pub fn get_all() -> Vec<Self> {
vec![Settler, Infantry, Ship, Cavalry, Elephant, Leader]
pub fn generic_name(&self) -> &'static str {
if let Leader(_) = self {
"leader"
} else {
self.non_leader_name()
}
}
///
/// # Panics
///
/// Panics if called on a leader unit.
#[must_use]
pub fn name(&self) -> &'static str {
pub fn non_leader_name(&self) -> &'static str {
match self {
Settler => "settler",
Infantry => "infantry",
Ship => "ship",
Cavalry => "cavalry",
Elephant => "elephant",
Leader => "leader",
Leader(l) => panic!("UnitType::non_leader_name called on a leader unit: {l:?}",),
}
}
#[must_use]
pub fn name(&self, game: &Game) -> String {
if let Leader(l) = self {
return game.cache.get_leader(l).name.clone();
}
self.non_leader_name().to_string()
}
#[must_use]
pub fn cost(&self) -> ResourcePile {
match self {
@ -179,7 +192,7 @@ impl UnitType {
Infantry => ResourcePile::food(1) + ResourcePile::ore(1),
Ship => ResourcePile::wood(2),
Cavalry => ResourcePile::food(1) + ResourcePile::wood(1),
Leader => ResourcePile::culture_tokens(1) + ResourcePile::mood_tokens(1),
Leader(_) => ResourcePile::culture_tokens(1) + ResourcePile::mood_tokens(1),
}
}
@ -200,10 +213,10 @@ impl UnitType {
"Army unit. Combat abilities: -1 hit but no combat value on {}",
Self::sides(Elephant)
),
Leader => format!(
Leader(_) => format!(
"Army unit. Combat abilities: Reroll the die until you get a \
non-leader roll on {}",
Self::sides(Leader)
Self::sides(unit::LEADER_UNIT)
),
}
}
@ -228,7 +241,7 @@ impl UnitType {
#[must_use]
pub fn is_army_unit(&self) -> bool {
matches!(self, Infantry | Cavalry | Elephant | Leader)
matches!(self, Infantry | Cavalry | Elephant | Leader(_))
}
#[must_use]
@ -240,11 +253,10 @@ impl UnitType {
pub fn is_military(&self) -> bool {
!self.is_settler()
}
}
impl Display for UnitType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.name())
#[must_use]
pub fn is_leader(&self) -> bool {
matches!(self, Leader(_))
}
}
@ -266,8 +278,8 @@ pub struct Units {
#[serde(skip_serializing_if = "u8::is_zero")]
pub elephants: u8,
#[serde(default)]
#[serde(skip_serializing_if = "u8::is_zero")]
pub leaders: u8,
#[serde(skip_serializing_if = "Option::is_none")]
pub leader: Option<leader::Leader>,
}
impl Units {
@ -278,7 +290,7 @@ impl Units {
ships: u8,
cavalry: u8,
elephants: u8,
leaders: u8,
leader: Option<leader::Leader>,
) -> Self {
Self {
settlers,
@ -286,13 +298,13 @@ impl Units {
ships,
cavalry,
elephants,
leaders,
leader,
}
}
#[must_use]
pub fn empty() -> Self {
Self::new(0, 0, 0, 0, 0, 0)
Self::new(0, 0, 0, 0, 0, None)
}
#[must_use]
@ -302,7 +314,16 @@ impl Units {
#[must_use]
pub fn is_empty(&self) -> bool {
self.clone().to_vec().is_empty()
self.amount() == 0
}
#[must_use]
pub fn get_amount(&self, unit: &UnitType) -> u8 {
if matches!(unit, Leader(_)) {
self.leaders()
} else {
self.get(unit)
}
}
#[must_use]
@ -313,25 +334,17 @@ impl Units {
Ship => self.ships,
Cavalry => self.cavalry,
Elephant => self.elephants,
Leader => self.leaders,
Leader(_) => self.leaders(),
}
}
#[must_use]
pub fn get_mut(&mut self, unit: &UnitType) -> &mut u8 {
match *unit {
Settler => &mut self.settlers,
Infantry => &mut self.infantry,
Ship => &mut self.ships,
Cavalry => &mut self.cavalry,
Elephant => &mut self.elephants,
Leader => &mut self.leaders,
}
fn leaders(&self) -> u8 {
self.leader.map_or(0, |_| 1)
}
#[must_use]
pub fn amount(&self) -> u8 {
self.settlers + self.infantry + self.ships + self.cavalry + self.elephants + self.leaders
self.settlers + self.infantry + self.ships + self.cavalry + self.elephants + self.leaders()
}
#[must_use]
@ -341,21 +354,12 @@ impl Units {
.collect()
}
///
/// # Panics
///
/// Panics if `game` is `None` and the units contain a leader.
#[must_use]
pub fn get_units_to_replace(&self, new_units: &Units) -> Units {
let mut units_to_replace = Units::empty();
for (unit_type, count) in self.clone() {
let new_count = new_units.get(&unit_type) as i8;
let replace = new_count - count as i8;
if replace > 0 {
*units_to_replace.get_mut(&unit_type) += replace as u8;
}
}
units_to_replace
}
#[must_use]
pub fn to_string(&self, leader_name: Option<&String>) -> String {
pub fn to_string(&self, game: Option<&Game>) -> String {
let mut unit_types = Vec::new();
if self.settlers > 0 {
unit_types.push(format!(
@ -392,12 +396,12 @@ impl Units {
}
));
}
if self.leaders > 0 {
unit_types.push(if self.leaders == 1 {
leader_name.map_or("a leader", |v| v).to_string()
if let Some(l) = self.leader {
if let Some(game) = game {
unit_types.push(l.name(game));
} else {
format!("{} leaders", self.leaders)
});
panic!("game missing for leader")
}
}
utils::format_and(&unit_types, "no units")
}
@ -417,7 +421,7 @@ impl AddAssign<&UnitType> for Units {
Ship => self.ships += 1,
Cavalry => self.cavalry += 1,
Elephant => self.elephants += 1,
Leader => self.leaders += 1,
Leader(l) => self.leader = Some(l),
}
}
}
@ -430,7 +434,7 @@ impl SubAssign<&UnitType> for Units {
Ship => self.ships -= 1,
Cavalry => self.cavalry -= 1,
Elephant => self.elephants -= 1,
Leader => self.leaders -= 1,
Leader(_) => self.leader = None,
}
}
}
@ -475,7 +479,10 @@ impl Iterator for UnitsIntoIterator {
2 => Some((Ship, u.ships)),
3 => Some((Cavalry, u.cavalry)),
4 => Some((Elephant, u.elephants)),
5 => Some((Leader, u.leaders)),
5 => Some((
self.units.leader.map_or(unit::LEADER_UNIT, Leader),
u.leaders(),
)),
_ => None,
}
}
@ -551,12 +558,8 @@ pub(crate) fn units_killed(game: &mut Game, player_index: usize, killed_units: K
fn kill_unit(game: &mut Game, unit_id: u32, player_index: usize, killer: Option<usize>) {
let unit = remove_unit(player_index, unit_id, game);
if matches!(unit.unit_type, UnitType::Leader) {
let leader = game.players[player_index]
.active_leader
.take()
.expect("A player should have an active leader when having a leader unit");
Player::with_leader(&leader, game, player_index, |game, leader| {
if let Leader(leader) = unit.unit_type {
Player::with_leader(leader, game, player_index, |game, leader| {
leader.listeners.deinit(game, player_index);
});
if let Some(killer) = killer {
@ -667,10 +670,7 @@ pub(crate) fn choose_carried_units_to_remove() -> Builtin {
game.add_info_log_item(&format!(
"{} killed carried units: {}",
s.player_name,
units
.into_iter()
.collect::<Units>()
.to_string(game.player(s.player_index).active_leader.as_ref())
units.into_iter().collect::<Units>().to_string(Some(game))
));
}
kill_units_without_event(game, &s.choice, s.player_index, e.killer);
@ -683,14 +683,31 @@ pub fn set_unit_position(player: usize, unit_id: u32, position: Position, game:
game.player_mut(player).get_unit_mut(unit_id).position = position;
}
#[must_use]
pub fn get_units_to_replace(available: &Units, new_units: &Units) -> Units {
let mut units_to_replace = Units::empty();
for (unit_type, count) in available.clone() {
for _ in 0..new_units.get_amount(&unit_type).saturating_sub(count) {
units_to_replace += &unit_type;
}
}
units_to_replace
}
// ignore the concrete leader here, it is just a placeholder
pub const LEADER: leader::Leader = leader::Leader::Alexander;
pub const LEADER_UNIT: UnitType = Leader(LEADER);
#[cfg(test)]
mod tests {
use crate::unit::UnitType::*;
use crate::unit::Units;
use crate::unit::{Units, get_units_to_replace};
use crate::{leader, unit};
#[test]
fn into_iter() {
let units = Units::new(0, 1, 0, 2, 1, 1);
let units = Units::new(0, 1, 0, 2, 1, Some(leader::Leader::Sulla));
assert_eq!(
units.into_iter().collect::<Vec<_>>(),
vec![
@ -699,27 +716,18 @@ mod tests {
(Ship, 0),
(Cavalry, 2),
(Elephant, 1),
(Leader, 1),
(Leader(leader::Leader::Sulla), 1),
]
);
}
#[test]
fn to_vec() {
let units = Units::new(0, 1, 0, 2, 1, 1);
fn test_get_units_to_replace() {
let available = Units::new(0, 1, 0, 2, 1, Some(unit::LEADER));
let new_units = Units::new(0, 2, 0, 1, 1, Some(leader::Leader::Sulla));
assert_eq!(
units.to_vec(),
vec![Infantry, Cavalry, Cavalry, Elephant, Leader]
);
}
#[test]
fn get_units_to_replace() {
let units = Units::new(0, 1, 0, 2, 1, 1);
let new_units = Units::new(0, 2, 0, 1, 1, 1);
assert_eq!(
units.get_units_to_replace(&new_units),
Units::new(0, 1, 0, 0, 0, 0)
get_units_to_replace(&available, &new_units),
Units::new(0, 1, 0, 0, 0, None)
);
}
}

View file

@ -37,7 +37,7 @@ fn test_sanitation_and_draft() {
// we should figure out that sanitation or draft are used, but not both
// actually that code turns out to be too complicated and slow, so the log now says you
// used both
let units = Units::new(1, 1, 0, 0, 0, 0);
let units = Units::new(1, 1, 0, 0, 0, None);
let city_position = Position::from_offset("A1");
JSON.test(
"sanitation_and_draft",
@ -56,7 +56,6 @@ fn test_sanitation_and_draft() {
&game.players[0],
&units,
city_position,
None,
CostTrigger::WithModifiers,
)
.unwrap()
@ -296,7 +295,7 @@ fn test_civil_liberties() {
TestAction::undoable(
0,
Action::Playing(Recruit(playing_actions::Recruit::new(
&Units::new(0, 1, 0, 0, 0, 0),
&Units::new(0, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::mood_tokens(2),
))),
@ -669,7 +668,7 @@ fn test_overpay() {
vec![TestAction::illegal(
0,
Action::Playing(Recruit(playing_actions::Recruit::new(
&Units::new(0, 1, 0, 0, 0, 0),
&Units::new(0, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::mood_tokens(1) + ResourcePile::gold(2), //paid too much
))),

View file

@ -36,7 +36,7 @@ fn all_actions() {
(
ActionType::Playing(PlayingActionType::Recruit),
vec![Action::Playing(PlayingAction::Recruit(Recruit::new(
&Units::new(1, 0, 0, 0, 0, 0),
&Units::new(1, 0, 0, 0, 0, None),
Position::from_offset("D8"),
ResourcePile::food(2)
)))]

View file

@ -1,4 +1,4 @@
use crate::common::{JsonTest, TestAction, move_action, payment_response};
use crate::common::{JsonTest, TestAction, custom_action, move_action, payment_response};
use server::action::Action;
use server::city_pieces::Building;
use server::content::custom_actions::CustomActionType;
@ -20,7 +20,7 @@ fn sparta_draft() {
vec![TestAction::undoable(
0,
Action::Playing(PlayingAction::Recruit(Recruit::new(
&Units::new(0, 1, 0, 0, 0, 0),
&Units::new(0, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::culture_tokens(1),
))),
@ -98,7 +98,7 @@ fn city_states() {
TestAction::undoable(
0,
Action::Playing(PlayingAction::Recruit(Recruit::new(
&Units::new(0, 1, 0, 0, 0, 0),
&Units::new(0, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::culture_tokens(1),
))),
@ -113,3 +113,37 @@ fn city_states() {
],
)
}
#[test]
fn idol() {
JSON.test(
"idol",
vec![
TestAction::undoable(0, custom_action(CustomActionType::Idol)).skip_json(),
TestAction::undoable(0, payment_response(ResourcePile::culture_tokens(1))).skip_json(),
TestAction::undoable(0, payment_response(ResourcePile::culture_tokens(1))),
],
)
}
#[test]
fn ruler_of_the_world() {
JSON.test(
"ruler_of_the_world",
vec![TestAction::not_undoable(
0,
move_action(vec![0], Position::from_offset("D8")),
)],
);
}
#[test]
fn master() {
JSON.test(
"master",
vec![
TestAction::undoable(0, custom_action(CustomActionType::Master)).skip_json(),
TestAction::not_undoable(0, payment_response(ResourcePile::mood_tokens(1))),
],
);
}

View file

@ -172,7 +172,7 @@ fn test_recruit_combat() {
TestAction::undoable(
0,
Action::Playing(Recruit(server::playing_actions::Recruit::new(
&Units::new(0, 0, 3, 0, 0, 0),
&Units::new(0, 0, 3, 0, 0, None),
Position::from_offset("C2"),
ResourcePile::wood(5) + ResourcePile::gold(1),
))),

View file

@ -5,6 +5,7 @@ use server::card::HandCard;
use server::collect::PositionCollection;
use server::content::persistent_events::{EventResponse, SelectedStructure, Structure};
use server::game_setup::{GameSetupBuilder, setup_game};
use server::leader::Leader;
use server::log::current_player_turn_log;
use server::unit::Units;
use server::wonder::Wonder;
@ -159,7 +160,7 @@ fn basic_actions() {
let player = &mut game.players[0];
player.gain_resources(ResourcePile::food(1));
let recruit_action = Action::Playing(Recruit(playing_actions::Recruit::new(
&Units::new(1, 0, 0, 0, 0, 0),
&Units::new(1, 0, 0, 0, 0, None),
city_position,
ResourcePile::food(2),
)));
@ -349,7 +350,7 @@ fn test_recruit() {
0,
Action::Playing(Recruit(
playing_actions::Recruit::new(
&Units::new(1, 1, 0, 0, 0, 0),
&Units::new(1, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::food(1) + ResourcePile::ore(1) + ResourcePile::gold(2),
)
@ -365,14 +366,11 @@ fn test_recruit_leader() {
"recruit_leader",
vec![TestAction::undoable(
0,
Action::Playing(Recruit(
playing_actions::Recruit::new(
&Units::new(0, 0, 0, 0, 0, 1),
Position::from_offset("A1"),
ResourcePile::mood_tokens(1) + ResourcePile::culture_tokens(1),
)
.with_leader("Alexander"),
)),
Action::Playing(Recruit(playing_actions::Recruit::new(
&Units::new(0, 0, 0, 0, 0, Some(Leader::Augustus)),
Position::from_offset("A1"),
ResourcePile::mood_tokens(1) + ResourcePile::culture_tokens(1),
))),
)],
);
}
@ -385,11 +383,10 @@ fn test_replace_leader() {
0,
Action::Playing(Recruit(
playing_actions::Recruit::new(
&Units::new(0, 0, 0, 0, 0, 1),
&Units::new(0, 0, 0, 0, 0, Some(Leader::Augustus)),
Position::from_offset("A1"),
ResourcePile::mood_tokens(1) + ResourcePile::culture_tokens(1),
)
.with_leader("Kleopatra")
.with_replaced_units(&[10]),
)),
)],

View file

@ -15,7 +15,7 @@ const JSON: JsonTest = JsonTest::child("objective_cards", "instant");
#[test]
fn test_draft() {
let r = Action::Playing(PlayingAction::Recruit(playing_actions::Recruit::new(
&Units::new(0, 1, 0, 0, 0, 0),
&Units::new(0, 1, 0, 0, 0, None),
Position::from_offset("A1"),
ResourcePile::mood_tokens(1),
)));
@ -83,6 +83,8 @@ fn test_warmonger() {
.skip_json(),
TestAction::not_undoable(0, move_action(vec![2, 3], Position::from_offset("B1")))
.skip_json(),
TestAction::not_undoable(0, Action::Response(EventResponse::Bool(false))).skip_json(),
TestAction::not_undoable(0, Action::Response(EventResponse::Bool(false))).skip_json(),
TestAction::undoable(
0,
Action::Response(EventResponse::SelectHandCards(vec![
@ -90,17 +92,11 @@ fn test_warmonger() {
])),
)
.with_pre_assert(|game| {
let PersistentEventRequest::SelectHandCards(c) = &game
.events
.last()
.expect("last event")
.player
.handler
.as_ref()
.expect("handler")
.request
let h = &game.events.last().expect("last event").player.handler;
let PersistentEventRequest::SelectHandCards(c) =
&h.as_ref().expect("handler").request
else {
panic!("Expected SelectHandCards request");
panic!("Expected SelectHandCards request, got: {h:?}");
};
//can't fulfill both objectives with same name
assert_eq!(c.choices.len(), 2);

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -415,4 +415,4 @@
"action_cards_discarded": [
2
]
}
}

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -52,7 +52,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -309,4 +309,4 @@
"incidents_left": [
28
]
}
}

View file

@ -52,7 +52,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -58,7 +58,7 @@
},
{
"position": "C1",
"unit_type": "Leader",
"unit_type": "Infantry",
"movement_restrictions": [
"Battle"
],
@ -285,10 +285,9 @@
"player": 0,
"present": {
"settlers": 2,
"infantry": 1,
"infantry": 2,
"cavalry": 1,
"elephants": 1,
"leaders": 1
"elephants": 1
}
},
"defender": {
@ -336,7 +335,7 @@
"action_log_index": 2,
"log": [
[
"Player1 marched 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader from C2 to C1 and captured Player2's city at C1",
"Player1 marched 2 settlers, 2 infantry, 1 cavalry and 1 elephant from C2 to C1 and captured Player2's city at C1",
"Player1 gained 1 gold for capturing a city",
"Player1 could not store 1 gold"
],

View file

@ -49,7 +49,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -55,7 +55,7 @@
},
{
"position": "C1",
"unit_type": "Leader",
"unit_type": "Infantry",
"movement_restrictions": [
"Battle"
],
@ -221,10 +221,9 @@
"player": 0,
"present": {
"settlers": 2,
"infantry": 1,
"infantry": 2,
"cavalry": 1,
"elephants": 1,
"leaders": 1
"elephants": 1
}
},
"defender": {
@ -250,16 +249,16 @@
"action_log_index": 2,
"log": [
[
"Player1 marched 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader from C2 to C1"
"Player1 marched 2 settlers, 2 infantry, 1 cavalry and 1 elephant from C2 to C1"
],
[
"Combat round 1",
"Attackers: 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader",
"Attackers: 2 settlers, 2 infantry, 1 cavalry and 1 elephant",
"Defenders: 2 infantry"
],
[
"Player1 did not play a Tactics Card",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 25 and gets 2 hits against defending units.",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 26 and gets 2 hits against defending units.",
"Player2 rolled 1 (leader, no bonus), 1 (leader, no bonus) for combined combat value of 2 and gets 0 hits against attacking units.",
"Player2 has to remove all of their defending units",
"Player2 removed 2 infantry",

View file

@ -55,7 +55,7 @@
},
{
"position": "C1",
"unit_type": "Leader",
"unit_type": "Infantry",
"movement_restrictions": [
"Battle"
],
@ -218,10 +218,9 @@
"player": 0,
"present": {
"settlers": 2,
"infantry": 1,
"infantry": 2,
"cavalry": 1,
"elephants": 1,
"leaders": 1
"elephants": 1
}
},
"defender": {
@ -444,16 +443,16 @@
"action_log_index": 6,
"log": [
[
"Player1 marched 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader from C2 to C1"
"Player1 marched 2 settlers, 2 infantry, 1 cavalry and 1 elephant from C2 to C1"
],
[
"Combat round 1",
"Attackers: 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader",
"Attackers: 2 settlers, 2 infantry, 1 cavalry and 1 elephant",
"Defenders: 2 infantry"
],
[
"Player1 did not play a Tactics Card",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 25 and gets 2 hits against defending units.",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 26 and gets 2 hits against defending units.",
"Player2 rolled 1 (leader, no bonus), 1 (leader, no bonus) for combined combat value of 2 and gets 0 hits against attacking units.",
"Player2 has to remove all of their defending units",
"Player2 removed 2 infantry",

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -255,4 +255,4 @@
"action_cards_discarded": [
9
]
}
}

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -268,4 +268,4 @@
"action_cards_discarded": [
3
]
}
}

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Cavalry",
"id": 2
},
{
@ -118,7 +118,9 @@
"units": [
{
"position": "A1",
"unit_type": "Leader",
"unit_type": {
"Leader": "Sulla"
},
"id": 0
},
{
@ -128,7 +130,6 @@
}
],
"civilization": "Rome",
"active_leader": "Sulla",
"advances": [
"Farming",
"Mining"

View file

@ -43,7 +43,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Cavalry",
"id": 2
},
{
@ -110,7 +110,9 @@
"units": [
{
"position": "A1",
"unit_type": "Leader",
"unit_type": {
"Leader": "Sulla"
},
"id": 0
},
{
@ -120,7 +122,6 @@
}
],
"civilization": "Rome",
"active_leader": "Sulla",
"advances": [
"Farming",
"Mining"

View file

@ -41,7 +41,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -41,7 +41,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -343,4 +343,4 @@
"action_cards_discarded": [
37
]
}
}

View file

@ -46,7 +46,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -46,7 +46,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -415,4 +415,4 @@
"action_cards_discarded": [
41
]
}
}

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -355,4 +355,4 @@
4,
2
]
}
}

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -278,4 +278,4 @@
"action_cards_discarded": [
7
]
}
}

View file

@ -49,7 +49,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -55,7 +55,7 @@
},
{
"position": "C1",
"unit_type": "Leader",
"unit_type": "Infantry",
"movement_restrictions": [
"Battle"
],
@ -218,10 +218,9 @@
"player": 0,
"present": {
"settlers": 2,
"infantry": 1,
"infantry": 2,
"cavalry": 1,
"elephants": 1,
"leaders": 1
"elephants": 1
}
},
"defender": {
@ -258,13 +257,13 @@
"action_log_index": 2,
"log": [
[
"Player1 marched 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader from C2 to C1"
"Player1 marched 2 settlers, 2 infantry, 1 cavalry and 1 elephant from C2 to C1"
],
[
"Combat round 1",
"Attackers: 2 settlers, 1 infantry, 1 cavalry, 1 elephant and a leader",
"Attackers: 2 settlers, 2 infantry, 1 cavalry and 1 elephant",
"Defenders: 2 infantry",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 25 and gets 2 hits against defending units.",
"Player1 rolled 6 (infantry, +1 combat value), 6 (infantry, +1 combat value), 6 (infantry, no bonus), 6 (infantry, no bonus) for combined combat value of 26 and gets 2 hits against defending units.",
"Player2 rolled 1 (leader, no bonus), 1 (leader, no bonus) for combined combat value of 2 and gets 0 hits against attacking units.",
"Player2 has to remove all of their defending units",
"Player2 removed 2 infantry",

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -45,7 +45,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -393,4 +393,4 @@
"action_cards_discarded": [
39
]
}
}

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -323,4 +323,4 @@
"action_cards_discarded": [
1
]
}
}

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -249,4 +249,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -49,7 +49,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -299,4 +299,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -107,10 +107,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Fishing",

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Fishing",

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -49,7 +49,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -380,4 +380,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

View file

@ -107,10 +107,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -48,7 +48,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -262,4 +262,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -52,7 +52,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{

View file

@ -52,7 +52,7 @@
},
{
"position": "C2",
"unit_type": "Leader",
"unit_type": "Infantry",
"id": 2
},
{
@ -427,4 +427,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -105,9 +105,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Farming",
"Fishing",
@ -169,10 +166,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Fishing",

View file

@ -105,9 +105,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Farming",
"Fishing",
@ -173,10 +170,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Fishing",

View file

@ -109,9 +109,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Farming",
"FreeEconomy",
@ -174,10 +171,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -166,9 +166,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Draft",
"Farming",
@ -232,10 +229,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -108,9 +108,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Draft",
"Farming",
@ -174,10 +171,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -98,9 +98,6 @@
}
],
"civilization": "test2",
"available_leaders": [
"Kʼinich Janaab Pakal I"
],
"advances": [
"Draft",
"Farming",
@ -158,10 +155,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"Mining"

View file

@ -109,10 +109,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

View file

@ -109,10 +109,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

View file

@ -108,10 +108,6 @@
}
],
"civilization": "test0",
"available_leaders": [
"Alexander",
"Kleopatra"
],
"advances": [
"Farming",
"FreeEconomy",

Some files were not shown because too many files have changed in this diff Show more