refactor custom actions (#261)

This commit is contained in:
Gregor Zeitlinger 2025-06-03 08:05:49 +02:00 • committed by GitHub
commit 58be39c8cd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
133 changed files with 1151 additions and 936 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

View file

@ -10,7 +10,7 @@ use crate::render_context::RenderContext;
use itertools::Itertools;
use server::action::Action;
use server::city::City;
use server::content::custom_actions::{CustomAction, CustomActionType};
use server::content::custom_actions::{CustomAction, CustomActionCommand};
use server::cultural_influence::available_influence_actions;
use server::happiness::available_happiness_actions;
use server::playing_actions::{PlayingAction, PlayingActionType};
@ -69,13 +69,13 @@ pub fn action_buttons(rc: &RenderContext) -> StateUpdate {
});
}
let mut i = 0;
for (a, origin) in game.available_custom_actions(rc.shown_player.index) {
if let Some(action) = generic_custom_action(rc, a, None) {
for c in game.available_custom_actions(rc.shown_player.index) {
if let Some(action) = generic_custom_action(rc, &c, None) {
if bottom_left_texture(
rc,
&assets.custom_actions[&a],
&assets.custom_actions[&c.action],
icon_pos(i as i8, -1),
&event_help(rc, &origin),
&event_help(rc, &c.event_origin),
) {
return action;
}
@ -97,11 +97,11 @@ pub fn custom_action_buttons<'a>(
rc.game
.available_custom_actions(rc.shown_player.index)
.into_iter()
.filter_map(|(a, origin)| {
generic_custom_action(rc, a, city).map(|action| {
.filter_map(|c| {
generic_custom_action(rc, &c, city).map(|action| {
IconAction::new(
&rc.assets().custom_actions[&a],
event_help(rc, &origin),
&rc.assets().custom_actions[&c.action],
event_help(rc, &c.event_origin),
Box::new(move || action.clone()),
)
})
@ -124,20 +124,24 @@ fn global_move(rc: &RenderContext) -> StateUpdate {
fn generic_custom_action(
rc: &RenderContext,
custom_action_type: CustomActionType,
c: &CustomActionCommand,
city: Option<&City>,
) -> Option<StateUpdate> {
let custom_action_type = c.action;
if let Some(city) = city {
return custom_action_type
.is_available_city(rc.shown_player, city)
.then_some(StateUpdate::execute(Action::Playing(
if c.is_city_available(rc.game, city) {
return Some(StateUpdate::execute(Action::Playing(
PlayingAction::Custom(CustomAction::new(custom_action_type, Some(city.position))),
)));
}
}
(!custom_action_type.is_city_bound()).then_some(StateUpdate::execute(Action::Playing(
PlayingAction::Custom(CustomAction::new(custom_action_type, None)),
)))
c.city_bound()
.is_none()
.then_some(StateUpdate::execute(Action::Playing(
PlayingAction::Custom(CustomAction::new(custom_action_type, None)),
)))
}
pub fn base_or_custom_action(
@ -152,7 +156,7 @@ pub fn base_or_custom_action(
.iter()
.map(|action_type| match action_type {
PlayingActionType::Custom(c) => {
let origin = rc.shown_player.custom_action_origin(c);
let origin = &rc.shown_player.custom_action_command(*c).event_origin;
(
Some(origin.clone()),
execute(BaseOrCustomDialog {

View file

@ -344,6 +344,10 @@ impl Assets {
CustomActionType::Master,
load_png(include_bytes!("../assets/greek-pillar-svgrepo-com.png")),
),
(
CustomActionType::ImperialArmy,
load_png(include_bytes!("../assets/farmer-farm-svgrepo-com.png")),
),
]
.iter()
.cloned()

View file

@ -143,7 +143,10 @@ impl ActiveDialog {
let v = vec!["Click on a building to influence its culture".to_string()];
if let PlayingActionType::Custom(c) = &b.action_type {
let mut r = v.clone();
r.extend(event_help(rc, &rc.shown_player.custom_action_origin(c)));
r.extend(event_help(
rc,
&rc.shown_player.custom_action_command(*c).event_origin,
));
}
v
} else {

View file

@ -10,7 +10,11 @@ pub fn event_help(rc: &RenderContext, origin: &EventOrigin) -> Vec<String> {
let d = match origin {
EventOrigin::Advance(a) => vec![a.info(rc.game).description.clone()],
EventOrigin::Wonder(w) => vec![rc.game.cache.get_wonder(*w).description.clone()],
EventOrigin::Builtin(b) => vec![cache.get_builtin(b, rc.game).description.clone()],
EventOrigin::Ability(b) => vec![
cache
.get_ability_description(b, rc.game, rc.shown_player)
.clone(),
],
EventOrigin::CivilCard(id) => vec![cache.get_civil_card(*id).description.clone()],
EventOrigin::TacticsCard(id) => vec![cache.get_tactics_card(*id).description.clone()],
EventOrigin::Incident(id) => cache.get_incident(*id).description(rc.game),

View file

@ -2,13 +2,19 @@ use crate::advance::Advance;
use crate::card::{HandCard, validate_card_selection_for_origin};
use crate::combat::{Combat, update_combat_strength};
use crate::combat_listeners::CombatStrength;
use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::custom_actions::{
CustomActionActionExecution, CustomActionCommand, CustomActionExecution, CustomActionInfo,
};
use crate::content::persistent_events::{
AdvanceRequest, EventResponse, HandCardsRequest, MultiRequest, PaymentRequest,
PersistentEventHandler, PersistentEventRequest, PlayerRequest, PositionRequest,
ResourceRewardRequest, SelectedStructure, StructuresRequest, UnitTypeRequest, UnitsRequest,
};
use crate::events::{Event, EventOrigin};
use crate::player::Player;
use crate::player_events::{PersistentEvent, PersistentEvents, TransientEvents};
use crate::playing_actions::PlayingActionType;
use crate::position::Position;
use crate::resource_pile::ResourcePile;
use crate::tactics_card::CombatRole;
@ -134,6 +140,10 @@ pub(crate) trait AbilityInitializerSetup: Sized {
fn get_key(&self) -> EventOrigin;
fn name(&self) -> String;
fn description(&self) -> String;
fn add_ability_initializer<F>(mut self, initializer: F) -> Self
where
F: Fn(&mut Game, usize, i32) + 'static + Sync + Send,
@ -869,16 +879,54 @@ pub(crate) trait AbilityInitializerSetup: Sized {
)
}
fn add_custom_action(self, action: CustomActionType) -> Self {
fn add_custom_action(
self,
action: CustomActionType,
info: impl Fn(CustomActionType) -> CustomActionInfo + Send + Sync + 'static,
ability: impl Fn(AbilityBuilder) -> AbilityBuilder + Sync + Send + 'static,
can_play: impl Fn(&Game, &Player) -> bool + Sync + Send + 'static,
) -> Self {
let name = self.name();
let desc = self.description();
self.add_custom_action_execution(
action,
info,
CustomActionExecution::Action(CustomActionActionExecution::new(
ability(Ability::builder(&name, &desc)).build(),
Arc::new(can_play),
None,
)),
)
}
fn add_action_modifier(
self,
action: CustomActionType,
info: impl Fn(CustomActionType) -> CustomActionInfo + Send + Sync + 'static,
base_action: PlayingActionType,
) -> Self {
self.add_custom_action_execution(action, info, CustomActionExecution::Modifier(base_action))
}
fn add_custom_action_execution(
self,
action: CustomActionType,
info: impl Fn(CustomActionType) -> CustomActionInfo + Send + Sync + 'static,
execution: CustomActionExecution,
) -> Self {
let deinitializer_action = action;
let key = self.get_key().clone();
let exec = execution.clone();
self.add_ability_initializer(move |game, player_index, _prio_delta| {
let player = &mut game.players[player_index];
player.custom_actions.insert(action, key.clone());
game.player_mut(player_index).custom_actions.insert(
action,
CustomActionCommand::new(action, exec.clone(), key.clone(), info(action)),
);
})
.add_ability_deinitializer(move |game, player_index| {
let player = &mut game.players[player_index];
player.custom_actions.remove(&deinitializer_action);
game.player_mut(player_index)
.custom_actions
.remove(&deinitializer_action);
})
}
}

View file

@ -36,19 +36,6 @@ pub enum Action {
Redo,
}
impl Action {
#[must_use]
pub fn get_type(&self) -> ActionType {
match self {
Self::Playing(v) => ActionType::Playing(v.playing_action_type()),
Self::Movement(_) => ActionType::Movement,
Self::Response(_) => ActionType::Response,
Self::Undo => ActionType::Undo,
Self::Redo => ActionType::Redo,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum ActionType {
Playing(PlayingActionType),

View file

@ -150,6 +150,14 @@ impl AbilityInitializerSetup for ActionCardBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::CivilCard(self.id)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
pub(crate) fn play_action_card(game: &mut Game, player_index: usize, id: u8) {

View file

@ -220,6 +220,14 @@ impl AbilityInitializerSetup for AdvanceBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::Advance(self.advance)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
#[derive(Clone)]

View file

@ -14,7 +14,7 @@ use crate::cultural_influence::{
InfluenceCultureAttempt, available_influence_actions, available_influence_culture,
};
use crate::events::EventOrigin;
use crate::game::Game;
use crate::game::{Game, GameState};
use crate::happiness::{available_happiness_actions, happiness_cost};
use crate::payment::PaymentOptions;
use crate::player::{CostTrigger, Player};
@ -84,8 +84,10 @@ impl AiActions {
.map(Action::Response)
.collect(),
)]
} else {
} else if game.state == GameState::Playing {
base_actions(self, game)
} else {
vec![]
};
for (t, a) in &actions {
assert!(
@ -192,16 +194,21 @@ fn base_actions(ai: &mut AiActions, game: &Game) -> Vec<(ActionType, Vec<Action>
));
}
for (a, _) in game.available_custom_actions(p.index) {
let cities = if a.is_city_bound() {
for command in game.available_custom_actions(p.index) {
let cities = if command.city_bound().is_some() {
p.cities
.iter()
.filter_map(|city| a.is_available_city(p, city).then_some(Some(city.position)))
.filter_map(|city| {
command
.is_city_available(game, city)
.then_some(Some(city.position))
})
.collect_vec()
} else {
vec![None]
};
let a = command.action;
for c in cities {
actions.push((
ActionType::Playing(PlayingActionType::Custom(a)),
@ -595,7 +602,7 @@ fn change_government(p: &Player, game: &Game) -> Vec<EventResponse> {
fn hand_card_strategy(o: &EventOrigin, r: &HandCardsRequest) -> SelectMultiStrategy {
match o {
EventOrigin::Builtin(n) if n == "Select Objective Cards to Complete" => {
EventOrigin::Ability(n) if n == "Select Objective Cards to Complete" => {
SelectMultiStrategy::Max
}
EventOrigin::CivilCard(_)
@ -609,7 +616,7 @@ fn hand_card_strategy(o: &EventOrigin, r: &HandCardsRequest) -> SelectMultiStrat
fn select_position_strategy(o: &EventOrigin, _r: &PositionRequest) -> SelectMultiStrategy {
match o {
EventOrigin::Builtin(n) if n == "Raze city" => SelectMultiStrategy::Min,
EventOrigin::Ability(n) if n == "Raze city" => SelectMultiStrategy::Min,
_ => SelectMultiStrategy::All,
}
}

View file

@ -2,8 +2,8 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::city::City;
use crate::combat::move_with_possible_combat;
use crate::consts::STACK_LIMIT;
use crate::content::ability::Ability;
use crate::content::advances::theocracy::cities_that_can_add_units;
use crate::content::builtin::Builtin;
use crate::content::persistent_events::{
PersistentEventType, PositionRequest, ResourceRewardRequest, UnitTypeRequest,
};
@ -62,8 +62,8 @@ impl BarbariansEventState {
}
}
pub(crate) fn barbarians_bonus() -> Builtin {
Builtin::builder("Barbarians bonus", "-")
pub(crate) fn barbarians_bonus() -> Ability {
Ability::builder("Barbarians bonus", "-")
.add_resource_request(
|event| &mut event.combat_end,
105,

View file

@ -2,16 +2,17 @@ use crate::action_card::{ActionCard, CivilCard};
use crate::advance::{Advance, AdvanceInfo};
use crate::city_pieces::Building;
use crate::civilization::Civilization;
use crate::content::ability::Ability;
use crate::content::advances::AdvanceGroup;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::custom_action_builtins;
use crate::content::custom_actions::CustomActionExecution;
use crate::content::{
action_cards, advances, builtin, civilizations, incidents, objective_cards, objectives, wonders,
ability, action_cards, advances, civilizations, incidents, objective_cards, objectives, wonders,
};
use crate::game::Game;
use crate::incident::Incident;
use crate::leader::{Leader, LeaderInfo};
use crate::objective_card::{Objective, ObjectiveCard};
use crate::player::Player;
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo};
use crate::status_phase::StatusPhaseState::{ChangeGovernmentType, DetermineFirstPlayer};
use crate::status_phase::{
@ -25,9 +26,9 @@ use std::collections::HashMap;
#[derive(Clone)]
pub struct Cache {
all_builtins: Vec<Builtin>,
builtins_by_name: HashMap<String, Builtin>,
status_phase_handlers: HashMap<StatusPhaseState, Builtin>,
all_abilities: Vec<Ability>,
abilities_by_name: HashMap<String, Ability>,
status_phase_handlers: HashMap<StatusPhaseState, Ability>,
all_advance_groups: Vec<AdvanceGroup>,
advance_groups_by_name: HashMap<String, AdvanceGroup>,
@ -64,15 +65,10 @@ impl Cache {
#[must_use]
pub fn new() -> Self {
Cache {
all_builtins: builtin::get_all_uncached(),
builtins_by_name: builtin::get_all_uncached()
all_abilities: ability::get_all_uncached(),
abilities_by_name: ability::get_all_uncached()
.into_iter()
.map(|builtin| (builtin.name.clone(), builtin))
.chain(
custom_action_builtins()
.into_values()
.map(|builtin| (builtin.name.clone(), builtin)),
)
.map(|a| (a.name.clone(), a))
.collect(),
status_phase_handlers: status_phase_handlers(),
@ -207,29 +203,40 @@ impl Cache {
}
#[must_use]
pub fn get_builtins(&self) -> &Vec<Builtin> {
&self.all_builtins
pub fn get_ability(&self) -> &Vec<Ability> {
&self.all_abilities
}
///
/// # Panics
///
/// Panics if builtin does not exist
/// Panics if ability does not exist
#[must_use]
pub fn get_builtin(&self, name: &str, game: &Game) -> &Builtin {
self.builtins_by_name
pub fn get_ability_description(&self, name: &str, game: &Game, player: &Player) -> String {
self.abilities_by_name
.get(name)
.or_else(|| {
if let Some(p) = get_status_phase(game) {
return Some(self.status_phase_handler(p));
}
None
})
.unwrap_or_else(|| panic!("builtin not found: {name}"))
.map_or_else(
|| {
for c in player.custom_actions.values() {
if let CustomActionExecution::Action(e) = &c.execution {
if e.execution.name == name {
return Some(e.execution.description.clone());
}
}
}
if let Some(p) = get_status_phase(game) {
return Some(self.status_phase_handler(p).description.clone());
}
None
},
|a| Some(a.description.clone()),
)
.unwrap_or_else(|| panic!("ability not found: {name}"))
}
#[must_use]
pub fn status_phase_handler(&self, p: &StatusPhaseState) -> &Builtin {
pub fn status_phase_handler(&self, p: &StatusPhaseState) -> &Ability {
match p {
DetermineFirstPlayer(_) => &self.status_phase_handlers[&DetermineFirstPlayer(0)],
ChangeGovernmentType(_) => &self.status_phase_handlers[&ChangeGovernmentType(false)],
@ -351,7 +358,7 @@ impl Cache {
}
}
fn status_phase_handlers() -> HashMap<StatusPhaseState, Builtin> {
fn status_phase_handlers() -> HashMap<StatusPhaseState, Ability> {
use StatusPhaseState::*;
HashMap::from([

View file

@ -144,14 +144,14 @@ pub(crate) fn validate_card_selection_for_origin(
EventOrigin::CivilCard(id) if *id == 31 || *id == 32 => {
validate_new_plans(cards, game).map(|()| Vec::new())
}
EventOrigin::Builtin(b) if b == "Select Objective Cards to Complete" => {
EventOrigin::Ability(b) if b == "Select Objective Cards to Complete" => {
let PersistentEventType::SelectObjectives(c) = &game.current_event().event_type else {
return Err("no selection handler".to_string());
};
match_objective_cards(cards, &c.objective_opportunities, game)
}
EventOrigin::Builtin(b) if b == "Princeps" => {
EventOrigin::Ability(b) if b == "Princeps" => {
validate_princeps_cards(cards).map(|()| Vec::new())
}
_ => Ok(Vec::new()),

View file

@ -1,5 +1,4 @@
use crate::advance::Advance;
use crate::content::custom_actions::collect_modifiers;
use crate::content::persistent_events::PersistentEventType;
use crate::events::EventOrigin;
use crate::game::Game;
@ -318,10 +317,5 @@ pub fn available_collect_actions_for_city(
#[must_use]
pub fn available_collect_actions(game: &Game, player: usize) -> Vec<PlayingActionType> {
base_or_custom_available(
game,
player,
PlayingActionType::Collect,
collect_modifiers(),
)
base_or_custom_available(game, player, &PlayingActionType::Collect)
}

View file

@ -2,7 +2,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::combat::{Combat, CombatRetreatState, capture_position, log_round};
use crate::combat_roll::CombatHits;
use crate::combat_stats::CombatStats;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::persistent_events::{PersistentEventType, PositionRequest, UnitsRequest};
use crate::game::Game;
use crate::log::current_action_log_item;
@ -512,8 +512,8 @@ fn add_tactics_listener(
}
}
pub(crate) fn choose_fighter_casualties() -> Builtin {
Builtin::builder("Choose Casualties", "Choose which carried units to remove.")
pub(crate) fn choose_fighter_casualties() -> Ability {
Ability::builder("Choose Casualties", "Choose which carried units to remove.")
.add_units_request(
|event| &mut event.combat_round_end,
1,
@ -569,8 +569,8 @@ pub(crate) fn choose_fighter_casualties() -> Builtin {
.build()
}
pub(crate) fn offer_retreat() -> Builtin {
Builtin::builder("Offer Retreat", "Do you want to retreat?")
pub(crate) fn offer_retreat() -> Ability {
Ability::builder("Offer Retreat", "Do you want to retreat?")
.add_bool_request(
|event| &mut event.combat_round_end,
0,
@ -599,8 +599,8 @@ pub(crate) fn offer_retreat() -> Builtin {
.build()
}
pub(crate) fn place_settler() -> Builtin {
Builtin::builder(
pub(crate) fn place_settler() -> Ability {
Ability::builder(
"Place Settler",
"After losing a city, place a settler in another city.",
)

View file

@ -1,6 +1,6 @@
pub mod ability;
pub mod action_cards;
pub mod advances;
pub mod builtin;
pub mod civilizations;
pub mod custom_actions;
pub mod effects;

View file

@ -26,56 +26,64 @@ use crate::unit::choose_carried_units_to_remove;
use crate::wonder::{build_wonder, on_draw_wonder_card};
#[derive(Clone)]
pub struct Builtin {
pub struct Ability {
pub name: String,
pub description: String,
pub listeners: AbilityListeners,
}
impl Builtin {
impl Ability {
#[must_use]
pub fn builder(name: &str, description: &str) -> BuiltinBuilder {
BuiltinBuilder::new(name, description)
pub fn builder(name: &str, description: &str) -> AbilityBuilder {
AbilityBuilder::new(name, description)
}
}
pub struct BuiltinBuilder {
pub struct AbilityBuilder {
name: String,
descriptions: String,
description: String,
builder: AbilityInitializerBuilder,
}
impl BuiltinBuilder {
impl AbilityBuilder {
fn new(name: &str, description: &str) -> Self {
Self {
name: name.to_string(),
descriptions: description.to_string(),
description: description.to_string(),
builder: AbilityInitializerBuilder::new(),
}
}
#[must_use]
pub fn build(self) -> Builtin {
Builtin {
pub fn build(self) -> Ability {
Ability {
name: self.name,
description: self.descriptions,
description: self.description,
listeners: self.builder.build(),
}
}
}
impl AbilityInitializerSetup for BuiltinBuilder {
impl AbilityInitializerSetup for AbilityBuilder {
fn builder(&mut self) -> &mut AbilityInitializerBuilder {
&mut self.builder
}
fn get_key(&self) -> EventOrigin {
EventOrigin::Builtin(self.name.clone())
EventOrigin::Ability(self.name.clone())
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
#[must_use]
pub fn get_all_uncached() -> Vec<Builtin> {
pub fn get_all_uncached() -> Vec<Ability> {
vec![
fishing_collect(),
pay_for_action(),
@ -111,7 +119,7 @@ pub fn get_all_uncached() -> Vec<Builtin> {
]
}
pub(crate) fn init_player(game: &mut Game, player_index: usize, all: &[Builtin]) {
pub(crate) fn init_player(game: &mut Game, player_index: usize, all: &[Ability]) {
for b in all {
b.listeners.init(game, player_index);
}

View file

@ -1,8 +1,8 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::{ActionCard, ActionCardInfo, on_play_action_card};
use crate::barbarians::get_barbarians_player;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::influence_modifiers;
use crate::content::ability::Ability;
use crate::content::custom_actions::is_base_or_modifier;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{SelectedStructure, Structure, UnitTypeRequest};
use crate::content::tactics_cards::TacticsCardFactory;
@ -11,7 +11,6 @@ use crate::cultural_influence::{
};
use crate::game::Game;
use crate::player::{Player, gain_unit, remove_unit};
use crate::player_events::PlayingActionInfo;
use crate::playing_actions::{ActionCost, PlayingActionType};
use crate::unit::UnitType;
use crate::utils::remove_element;
@ -117,16 +116,21 @@ fn any_barbarian_city_can_be_influenced(game: &Game, p: &Player) -> bool {
})
}
pub(crate) fn use_cultural_takeover() -> Builtin {
Builtin::builder("cultural_takeover", "-")
pub(crate) fn use_cultural_takeover() -> Ability {
Ability::builder("cultural_takeover", "-")
.add_transient_event_listener(
|event| &mut event.is_playing_action_available,
3,
|available, game, i| {
let p = game.player(i.player);
if game
.permanent_effects
.contains(&PermanentEffect::CulturalTakeover)
&& !is_influence(i)
&& !is_base_or_modifier(
&i.action_type,
p,
&PlayingActionType::InfluenceCultureAttempt,
)
{
*available =
Err("Cultural Takeover: You may only influence culture.".to_string());
@ -173,11 +177,3 @@ fn is_barbarian_takeover(game: &Game, c: &InfluenceCultureInfo) -> bool {
.permanent_effects
.contains(&PermanentEffect::CulturalTakeover)
}
fn is_influence(i: &PlayingActionInfo) -> bool {
match &i.action_type {
PlayingActionType::InfluenceCultureAttempt => true,
PlayingActionType::Custom(i) if influence_modifiers().contains(i) => true,
_ => false,
}
}

View file

@ -1,10 +1,10 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::ActionCard;
use crate::collect::available_collect_actions_for_city;
use crate::content::ability::Ability;
use crate::content::action_cards::cultural_takeover::cultural_takeover;
use crate::content::action_cards::mercenaries::mercenaries;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::collect_modifiers;
use crate::content::custom_actions::is_base_or_modifier;
use crate::content::effects::{CollectEffect, ConstructEffect, PermanentEffect};
use crate::content::incidents::great_builders::can_construct_anything;
use crate::content::incidents::great_explorer::{action_explore_request, explore_adjacent_block};
@ -15,7 +15,6 @@ use crate::content::tactics_cards::{
};
use crate::game::Game;
use crate::player::{Player, gain_unit};
use crate::player_events::PlayingActionInfo;
use crate::playing_actions::{ActionCost, PlayingActionType};
use crate::resource_pile::ResourcePile;
use crate::unit::UnitType;
@ -97,17 +96,18 @@ pub(crate) fn collect_special_action(game: &Game, player: &Player) -> bool {
.any(|c| !available_collect_actions_for_city(game, player.index, c.position).is_empty())
}
pub(crate) fn collect_only() -> Builtin {
Builtin::builder("collect only", "-")
pub(crate) fn collect_only() -> Ability {
Ability::builder("collect only", "-")
.add_transient_event_listener(
|event| &mut event.is_playing_action_available,
4,
|available, game, i| {
let p = game.player(i.player);
if game
.permanent_effects
.iter()
.any(|e| matches!(e, &PermanentEffect::Collect(_)))
&& !is_collect(i)
&& !is_base_or_modifier(&i.action_type, p, &PlayingActionType::Collect)
{
*available = Err("You may only collect.".to_string());
}
@ -145,14 +145,6 @@ pub(crate) fn collect_only() -> Builtin {
.build()
}
fn is_collect(i: &PlayingActionInfo) -> bool {
match &i.action_type {
PlayingActionType::Collect => true,
PlayingActionType::Custom(c) if collect_modifiers().contains(c) => true,
_ => false,
}
}
fn explorer(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
let b = ActionCard::builder(
id,

View file

@ -1,8 +1,8 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action::Action;
use crate::action_card::ActionCard;
use crate::content::ability::Ability;
use crate::content::action_cards::development::collect_special_action;
use crate::content::builtin::Builtin;
use crate::content::effects::{CollectEffect, PermanentEffect};
use crate::content::incidents::great_diplomat::{DiplomaticRelations, Negotiations};
use crate::content::persistent_events::PlayerRequest;
@ -76,8 +76,8 @@ fn negotiations(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
.build()
}
pub(crate) fn use_negotiations() -> Builtin {
Builtin::builder("Negotiations", "")
pub(crate) fn use_negotiations() -> Ability {
Ability::builder("Negotiations", "")
.add_simple_persistent_event_listener(
|e| &mut e.turn_start,
1,
@ -193,8 +193,8 @@ fn opponents_not_affected_by_assassination(game: &Game, player_index: usize) ->
.collect()
}
pub(crate) fn use_assassination() -> Builtin {
Builtin::builder("Assassination", "")
pub(crate) fn use_assassination() -> Ability {
Ability::builder("Assassination", "")
.add_simple_persistent_event_listener(
|e| &mut e.turn_start,
2,

View file

@ -2,9 +2,9 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::{ActionCard, ActionCardBuilder, CivilCardTarget, discard_action_card};
use crate::advance::{Advance, gain_advance_without_payment};
use crate::card::HandCard;
use crate::content::ability::Ability;
use crate::content::action_cards::inspiration;
use crate::content::advances::theocracy::cities_that_can_add_units;
use crate::content::builtin::Builtin;
use crate::content::persistent_events::{
AdvanceRequest, HandCardsRequest, PaymentRequest, PlayerRequest, PositionRequest,
};
@ -277,9 +277,9 @@ fn teach_us(id: u8, tactics_card: TacticsCardFactory) -> ActionCard {
.build()
}
pub(crate) fn use_teach_us() -> Builtin {
pub(crate) fn use_teach_us() -> Ability {
// this action card is special - it's played directly after a battle - like objective cards
Builtin::builder(
Ability::builder(
"Teach us",
"If you just captured a city: Gain 1 advance from the loser for free \
without changing the Game Event counter.",

View file

@ -1,10 +1,12 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::city::MoodState;
use crate::content::advances::{AdvanceGroup, advance_group_builder};
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType::{AbsolutePower, ForcedLabor};
use crate::content::persistent_events::ResourceRewardRequest;
use crate::payment::ResourceReward;
use crate::player::Player;
use crate::resource_pile::ResourcePile;
pub(crate) fn autocracy() -> AdvanceGroup {
advance_group_builder(
@ -73,48 +75,60 @@ fn totalitarianism() -> AdvanceBuilder {
)
}
const ABSOLUTE_POWER: &str =
"Once per turn, as a free action, you may spend 2 mood tokens to get an additional action";
fn absolute_power() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::AbsolutePower, "Absolute Power", ABSOLUTE_POWER)
.add_custom_action(AbsolutePower)
AdvanceInfo::builder(
Advance::AbsolutePower,
"Absolute Power",
"Once per turn, as a free action, you may spend 2 mood tokens to get an additional action",
)
.add_custom_action(
AbsolutePower,
|a| a.free_and_once_per_turn(ResourcePile::mood_tokens(2)),
|b| {
b.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, _, player_name, _| {
game.actions_left += 1;
game.add_info_log_item(&format!(
"{player_name} got an extra action using Absolute Power",
));
},
)
},
|_, _| true,
)
}
pub(crate) fn use_absolute_power() -> Builtin {
Builtin::builder("Absolute Power", ABSOLUTE_POWER)
.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, _, player_name, _| {
game.actions_left += 1;
game.add_info_log_item(&format!(
"{player_name} got an extra action using Absolute Power",
));
},
)
.build()
}
const FORCED_LABOR: &str = "Once per turn, as a free action, \
you may spend 1 mood token to treat your Angry cities as neutral for the rest of the turn";
fn forced_labor() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::ForcedLabor, "Forced Labor", FORCED_LABOR)
.add_custom_action(ForcedLabor)
AdvanceInfo::builder(
Advance::ForcedLabor,
"Forced Labor",
"Once per turn, as a free action, \
you may spend 1 mood token to treat your Angry cities as neutral for the rest of the turn",
)
.add_custom_action(
ForcedLabor,
|a| a.free_and_once_per_turn(ResourcePile::mood_tokens(1)),
|b| {
b.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, _, player_name, _| {
// we check that the action was played
game.add_info_log_item(&format!(
"{player_name} paid 1 mood token to treat Angry cities as neutral"
));
},
)
},
|_game, player| any_angry(player),
)
}
pub(crate) fn use_forced_labor() -> Builtin {
Builtin::builder("Forced Labor", FORCED_LABOR)
.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, _, player_name, _| {
// we check that the action was played
game.add_info_log_item(&format!(
"{player_name} paid 1 mood token to treat Angry cities as neutral"
));
},
)
.build()
fn any_angry(player: &Player) -> bool {
player
.cities
.iter()
.any(|city| city.mood_state == MoodState::Angry)
}

View file

@ -3,16 +3,20 @@ use crate::advance::Bonus::{CultureToken, MoodToken};
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::city::{City, MoodState};
use crate::city_pieces::Building::Obelisk;
use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::advances::{AdvanceGroup, advance_group_builder};
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::custom_actions::{
CustomActionActionExecution, CustomActionExecution, CustomActionType, any_non_happy,
};
use crate::content::persistent_events::PaymentRequest;
use crate::happiness::increase_happiness;
use crate::payment::{PaymentOptions, PaymentReason};
use crate::player::{Player, gain_resources};
use crate::playing_actions::PlayingActionType;
use crate::resource::ResourceType;
use crate::resource_pile::ResourcePile;
use crate::wonder::draw_wonder_card;
use crate::wonder::{Wonder, draw_wonder_card};
use std::sync::Arc;
use std::vec;
pub(crate) fn culture() -> AdvanceGroup {
@ -28,7 +32,11 @@ fn arts() -> AdvanceBuilder {
)
.with_advance_bonus(CultureToken)
.with_unlocked_building(Obelisk)
.add_custom_action(CustomActionType::ArtsInfluenceCultureAttempt)
.add_action_modifier(
CustomActionType::ArtsInfluenceCultureAttempt,
|a| a.free_and_once_per_turn(ResourcePile::culture_tokens(1)),
PlayingActionType::InfluenceCultureAttempt,
)
}
const SPORTS_DESC: &str = "As an action, you may spend \
@ -37,7 +45,18 @@ const SPORTS_DESC: &str = "As an action, you may spend \
fn sports() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::Sports, "Sports", SPORTS_DESC)
.with_advance_bonus(MoodToken)
.add_custom_action(CustomActionType::Sports)
.add_custom_action_execution(
CustomActionType::Sports,
|_| CustomActionType::regular(),
CustomActionExecution::Action(CustomActionActionExecution::new(
use_sports(),
Arc::new(|_game, p| can_use_sports(p)),
Some(Arc::new(|game, city| {
let p = game.player(city.player_index);
sports_options(p, city).is_some_and(|c| c.can_afford(&p.resources))
})),
)),
)
}
fn monuments() -> AdvanceBuilder {
@ -65,13 +84,20 @@ fn monuments() -> AdvanceBuilder {
)
}
const THEATERS_DESC: &str = "Once per turn, as a free action, you may convert 1 culture token \
into 1 mood token, or 1 mood token into 1 culture token";
fn theaters() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::Theaters, "Theaters", THEATERS_DESC)
.with_advance_bonus(MoodToken)
.add_custom_action(CustomActionType::Theaters)
AdvanceInfo::builder(
Advance::Theaters,
"Theaters",
"Once per turn, as a free action, you may convert 1 culture token \
into 1 mood token, or 1 mood token into 1 culture token",
)
.with_advance_bonus(MoodToken)
.add_custom_action(
CustomActionType::Theaters,
|a| a.free_and_once_per_turn(ResourcePile::empty()),
use_theaters,
|_game, p| p.resources.culture_tokens > 0 || p.resources.mood_tokens > 0,
)
}
#[must_use]
@ -93,8 +119,18 @@ pub fn sports_options(player: &Player, city: &City) -> Option<PaymentOptions> {
}
}
pub(crate) fn use_sports() -> Builtin {
Builtin::builder("Sports", SPORTS_DESC)
fn can_use_sports(p: &Player) -> bool {
if !any_non_happy(p) {
return false;
}
if p.resources.culture_tokens > 0 {
return true;
}
p.wonders_owned.contains(Wonder::Colosseum) && p.resources.mood_tokens > 0
}
fn use_sports() -> Ability {
Ability::builder("Sports", SPORTS_DESC)
.add_payment_request_listener(
|event| &mut event.custom_action,
0,
@ -130,34 +166,35 @@ pub(crate) fn use_sports() -> Builtin {
.build()
}
pub(crate) fn use_theaters() -> Builtin {
Builtin::builder("Theaters", THEATERS_DESC)
.add_payment_request_listener(
|event| &mut event.custom_action,
0,
|game, player, _| {
Some(vec![PaymentRequest::mandatory(
PaymentOptions::sum(
game.player(player),
PaymentReason::CustomAction,
1, &[ResourceType::CultureTokens, ResourceType::MoodTokens]),
"Convert 1 culture token into 1 mood token, or 1 mood token into 1 culture token",
)])
},
|game, s, _| {
gain_resources(
game,
s.player_index,
theater_opposite(&s.choice[0]),
|name,pile|
fn use_theaters(b: AbilityBuilder) -> AbilityBuilder {
b.add_payment_request_listener(
|event| &mut event.custom_action,
0,
|game, player, _| {
Some(vec![PaymentRequest::mandatory(
PaymentOptions::sum(
game.player(player),
PaymentReason::CustomAction,
1,
&[ResourceType::CultureTokens, ResourceType::MoodTokens],
),
"Convert 1 culture token into 1 mood token, or 1 mood token into 1 culture token",
)])
},
|game, s, _| {
gain_resources(
game,
s.player_index,
theater_opposite(&s.choice[0]),
|name, pile| {
format!(
"{name} used Theaters to convert {} into {pile}",
s.choice[0],
),
);
},
)
.build()
)
},
);
},
)
}
fn theater_opposite(payment: &ResourcePile) -> ResourcePile {

View file

@ -3,7 +3,7 @@ use crate::action::Action;
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::city::MoodState;
use crate::content::advances::{AdvanceGroup, advance_group_builder};
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::custom_actions::CustomActionType::{
CivilLiberties, FreeEconomyCollect, VotingIncreaseHappiness,
};
@ -30,7 +30,11 @@ fn voting() -> AdvanceBuilder {
"Voting",
"As a free action, you may spend 1 mood token to use 'Increase happiness'",
)
.add_custom_action(VotingIncreaseHappiness)
.add_action_modifier(
VotingIncreaseHappiness,
|_| CustomActionType::cost(ResourcePile::mood_tokens(1)),
PlayingActionType::IncreaseHappiness,
)
}
fn separation_of_power() -> AdvanceBuilder {
@ -52,29 +56,32 @@ fn separation_of_power() -> AdvanceBuilder {
)
}
const CIVIL_LIBERTIES: &str = "As an action, you may gain 3 mood tokens. \
The cost of Draft is increased to 2 mood token";
fn civil_liberties() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::CivilLiberties, "Civil Liberties", CIVIL_LIBERTIES)
.add_custom_action(CivilLiberties)
}
pub(crate) fn use_civil_liberties() -> Builtin {
Builtin::builder("Civil Liberties", CIVIL_LIBERTIES)
.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, player_index, _, _| {
gain_resources(
game,
player_index,
ResourcePile::mood_tokens(3),
|name, pile| format!("{name} used Civil Liberties to gain {pile}",),
);
},
)
.build()
AdvanceInfo::builder(
Advance::CivilLiberties,
"Civil Liberties",
"As an action, you may gain 3 mood tokens. \
The cost of Draft is increased to 2 mood token",
)
.add_custom_action(
CivilLiberties,
|_| CustomActionType::regular(),
|b| {
b.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, player_index, _, _| {
gain_resources(
game,
player_index,
ResourcePile::mood_tokens(3),
|name, pile| format!("{name} used Civil Liberties to gain {pile}",),
);
},
)
},
|_, _| true,
)
}
fn free_economy() -> AdvanceBuilder {
@ -84,7 +91,11 @@ fn free_economy() -> AdvanceBuilder {
"As a free action, you may spend 1 mood token to collect \
resources in one city. This must be your only collect action this turn",
)
.add_custom_action(FreeEconomyCollect)
.add_action_modifier(
FreeEconomyCollect,
|a| a.free_and_once_per_turn(ResourcePile::mood_tokens(1)),
PlayingActionType::Collect,
)
.add_transient_event_listener(
|event| &mut event.is_playing_action_available,
0,

View file

@ -4,9 +4,9 @@ use crate::advance::Bonus::{CultureToken, MoodToken};
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::card::{HandCard, all_action_hand_cards};
use crate::city_pieces::Building::Market;
use crate::content::ability::AbilityBuilder;
use crate::content::advances::trade_routes::{TradeRoute, trade_route_log, trade_route_reward};
use crate::content::advances::{AdvanceGroup, advance_group_builder};
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::custom_actions::CustomActionType::Taxes;
use crate::content::persistent_events::{HandCardsRequest, ResourceRewardRequest};
@ -34,87 +34,98 @@ fn currency() -> AdvanceBuilder {
.with_advance_bonus(CultureToken)
}
const BARTER_DESC: &str = "Once per turn, as a free action, \
you may spend discard an action card for 1 gold or 1 culture token.";
fn bartering() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::Bartering, "Bartering", BARTER_DESC)
.with_advance_bonus(MoodToken)
.add_custom_action(CustomActionType::Bartering)
.with_unlocked_building(Market)
AdvanceInfo::builder(
Advance::Bartering,
"Bartering",
"Once per turn, as a free action, \
you may spend discard an action card for 1 gold or 1 culture token.",
)
.with_advance_bonus(MoodToken)
.add_custom_action(
CustomActionType::Bartering,
|a| a.free_and_once_per_turn(ResourcePile::empty()),
use_bartering,
|_game, p| !p.action_cards.is_empty(),
)
.with_unlocked_building(Market)
}
pub(crate) fn use_bartering() -> Builtin {
Builtin::builder("Bartering", BARTER_DESC)
.add_hand_card_request(
|event| &mut event.custom_action,
1,
|game, player_index, _| {
Some(HandCardsRequest::new(
all_action_hand_cards(game.player(player_index)),
1..=1,
"Select an action card to discard",
))
},
|game, s, _e| {
let HandCard::ActionCard(card) = s.choice[0] else {
panic!("Invalid type");
};
game.add_info_log_item(&format!(
"{} discarded {} for 1 gold or 1 culture token",
s.player_name,
game.cache.get_action_card(card).name()
));
discard_action_card(game, s.player_index, card);
},
)
.add_resource_request(
|event| &mut event.custom_action,
0,
|_game, _player_index, _| {
Some(ResourceRewardRequest::new(
ResourceReward::sum(1, &[ResourceType::Gold, ResourceType::CultureTokens]),
"Select a resource to gain".to_string(),
))
},
|_game, s, _| {
vec![format!(
"{} gained {} for discarding an action card",
s.player_name, s.choice
)]
},
)
.build()
fn use_bartering(b: AbilityBuilder) -> AbilityBuilder {
b.add_hand_card_request(
|event| &mut event.custom_action,
1,
|game, player_index, _| {
Some(HandCardsRequest::new(
all_action_hand_cards(game.player(player_index)),
1..=1,
"Select an action card to discard",
))
},
|game, s, _e| {
let HandCard::ActionCard(card) = s.choice[0] else {
panic!("Invalid type");
};
game.add_info_log_item(&format!(
"{} discarded {} for 1 gold or 1 culture token",
s.player_name,
game.cache.get_action_card(card).name()
));
discard_action_card(game, s.player_index, card);
},
)
.add_resource_request(
|event| &mut event.custom_action,
0,
|_game, _player_index, _| {
Some(ResourceRewardRequest::new(
ResourceReward::sum(1, &[ResourceType::Gold, ResourceType::CultureTokens]),
"Select a resource to gain".to_string(),
))
},
|_game, s, _| {
vec![format!(
"{} gained {} for discarding an action card",
s.player_name, s.choice
)]
},
)
}
const TAXES_DESCRIPTION: &str = "Once per turn, as an action, you may spend 1 mood token to gain \
food, wood, or ore equal to the number of cities you control. \
If you have the Currency advance, you may gain gold instead of food, wood, or ore.";
fn taxes() -> AdvanceBuilder {
AdvanceInfo::builder(Advance::Taxes, "Taxes", TAXES_DESCRIPTION).add_custom_action(Taxes)
AdvanceInfo::builder(
Advance::Taxes,
"Taxes",
"Once per turn, as an action, you may spend 1 mood token to gain \
food, wood, or ore equal to the number of cities you control. \
If you have the Currency advance, you may gain gold instead of food, wood, or ore.",
)
.add_custom_action(
Taxes,
|a| a.once_per_turn(ResourcePile::mood_tokens(1)),
use_taxes,
|_, _| true,
)
}
pub(crate) fn use_taxes() -> Builtin {
Builtin::builder("Taxes", TAXES_DESCRIPTION)
.add_resource_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
let options = tax_options(game.player(player_index));
Some(ResourceRewardRequest::new(
options,
"Select a resource to gain".to_string(),
))
},
|_game, s, _| {
vec![format!(
"{} gained {} for using Taxes",
s.player_name, s.choice
)]
},
)
.build()
fn use_taxes(b: AbilityBuilder) -> AbilityBuilder {
b.add_resource_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
let options = tax_options(game.player(player_index));
Some(ResourceRewardRequest::new(
options,
"Select a resource to gain".to_string(),
))
},
|_game, s, _| {
vec![format!(
"{} gained {} for using Taxes",
s.player_name, s.choice
)]
},
)
}
#[must_use]

View file

@ -2,8 +2,8 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::advance::Bonus::{CultureToken, MoodToken};
use crate::advance::{Advance, AdvanceBuilder, AdvanceInfo};
use crate::city_pieces::Building::Port;
use crate::content::ability::Ability;
use crate::content::advances::{AdvanceGroup, advance_group_builder};
use crate::content::builtin::Builtin;
use crate::game::Game;
use crate::player::gain_resources;
use crate::position::Position;
@ -106,8 +106,8 @@ fn is_enemy_player_or_pirate_zone(game: &Game, player_index: usize, position: Po
game.enemy_player(player_index, position).is_some() || game.is_pirate_zone(position)
}
pub(crate) fn fishing_collect() -> Builtin {
Builtin::builder("Fishing", "")
pub(crate) fn fishing_collect() -> Ability {
Ability::builder("Fishing", "")
.add_transient_event_listener(
|event| &mut event.collect_options,
1,

View file

@ -14,7 +14,11 @@ use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo, SpecialAdvanceR
use itertools::Itertools;
pub(crate) fn china() -> Civilization {
Civilization::new("China", vec![rice(), expansion(), fireworks()], vec![])
Civilization::new(
"China",
vec![rice(), expansion(), fireworks(), imperial_army()],
vec![],
)
}
fn rice() -> SpecialAdvanceInfo {
@ -161,3 +165,27 @@ fn apply_fireworks(e: &mut CombatRoundEnd, p: usize, do_update: bool) -> bool {
h.opponent_hit_cancels += 1;
})
}
const IMPERIAL_ARMY: &str = "Once per turn, as an action, \
you may convert any number of settlers into infantry units, and vice versa.";
fn imperial_army() -> SpecialAdvanceInfo {
SpecialAdvanceInfo::builder(
SpecialAdvance::ImperialArmy,
SpecialAdvanceRequirement::AnyGovernment,
"Imperial Army",
IMPERIAL_ARMY,
)
// .add_custom_action(
// CustomActionType::ImperialArmy,
// |a| a.once_per_turn(ResourcePile::empty()),
// use_imperial_army(),
// |_game, _p| todo!(),
// )
.build()
}
//
// fn use_imperial_army() -> Ability {
// // todo
// Ability::builder("Imperial Army", IMPERIAL_ARMY).build()
// }

View file

@ -4,16 +4,16 @@ use crate::card::HandCard;
use crate::civilization::Civilization;
use crate::combat::update_combat_strength;
use crate::combat_listeners::CombatStrength;
use crate::content::ability::AbilityBuilder;
use crate::content::advances::warfare::draft_cost;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::CustomActionType;
use crate::content::custom_actions::{CustomActionInfo, CustomActionType};
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::{Player, gain_resources};
use crate::playing_actions::{PlayingAction, PlayingActionType};
use crate::playing_actions::{ActionResourceCost, PlayingAction, PlayingActionType};
use crate::resource_pile::ResourcePile;
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo, SpecialAdvanceRequirement};
use itertools::Itertools;
@ -104,7 +104,16 @@ fn hellenistic_culture() -> SpecialAdvanceInfo {
"Cultural influence: You may use any influenced city as a starting point. \
You may replace the cost of Arts with 2 mood tokens.",
)
.add_custom_action(CustomActionType::HellenisticInfluenceCultureAttempt)
.add_action_modifier(
CustomActionType::HellenisticInfluenceCultureAttempt,
|_| {
CustomActionType::free_and_once_per_turn_mutually_exclusive(
ResourcePile::mood_tokens(2),
CustomActionType::ArtsInfluenceCultureAttempt,
)
},
PlayingActionType::InfluenceCultureAttempt,
)
.build()
}
@ -117,7 +126,6 @@ fn city_states() -> SpecialAdvanceInfo {
you may instead decrease the mood of another city \
of at least the same size and mood level.",
)
.add_custom_action(CustomActionType::HellenisticInfluenceCultureAttempt)
.add_position_request(
|event| &mut event.city_activation_mood_decreased,
0,
@ -180,16 +188,22 @@ fn city_states() -> SpecialAdvanceInfo {
.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(
"Idol",
"As a free action, pay 1 culture token to \
play an action card as a free action",
)
.add_custom_action(
CustomActionType::Idol,
|_| CustomActionType::free(ResourcePile::culture_tokens(1)),
use_idol,
|game, p| !idol_cards(game, p, &ResourcePile::culture_tokens(1)).is_empty(),
)
.build(),
LeaderAbility::builder(
"Ruler of the World",
"In a land battle, gain 1 combat value for each region
@ -220,41 +234,39 @@ fn alexander() -> LeaderInfo {
)
}
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
));
fn use_idol(b: AbilityBuilder) -> AbilityBuilder {
b.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()
PlayingAction::ActionCard(id)
.execute_without_action_cost(game, s.player_index)
.expect("playing action card with Idol");
},
)
}
pub(crate) fn idol_cards(game: &Game, p: &Player, extra_cost: &ResourcePile) -> Vec<HandCard> {
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);
let action_cost = PlayingActionType::ActionCard(a).cost(game, p.index);
if action_cost.free {
// can play directly
return None;
@ -312,15 +324,21 @@ fn leonidas() -> LeaderInfo {
)
}
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(
"Master",
"Pericles is in a Happy city: Gain 1 education advance for free.",
)
.add_custom_action(
CustomActionType::Master,
|_| CustomActionInfo::new(false, None, ActionResourceCost::Tokens(1)),
use_master,
|game, p| !master_education_advances(game, p).is_empty(),
)
.build(),
LeaderAbility::builder("Admiral", "In Sea battles: Gain +2 combat value")
.add_combat_strength_listener(102, |game, c, s, _r| {
if c.is_sea_battle(game) {
@ -332,35 +350,27 @@ fn pericles() -> LeaderInfo {
)
}
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()
fn use_master(b: AbilityBuilder) -> AbilityBuilder {
b.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);
},
)
}
pub(crate) fn master_education_advances(game: &Game, player: &Player) -> Vec<Advance> {
fn master_education_advances(game: &Game, player: &Player) -> Vec<Advance> {
game.cache
.get_advance_group("Education")
.advances

View file

@ -1,10 +1,10 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::{discard_action_card, gain_action_card_from_pile};
use crate::advance::{Advance, gain_advance_without_payment};
use crate::advance::{Advance, base_advance_cost, gain_advance_without_payment};
use crate::card::{HandCard, all_action_hand_cards, all_objective_hand_cards};
use crate::city::MoodState;
use crate::city::{City, MoodState};
use crate::civilization::Civilization;
use crate::content::builtin::Builtin;
use crate::content::ability::AbilityBuilder;
use crate::content::custom_actions::CustomActionType;
use crate::content::persistent_events::{HandCardsRequest, PaymentRequest, PositionRequest};
use crate::game::Game;
@ -15,6 +15,7 @@ use crate::payment::{
PaymentConversion, PaymentConversionType, PaymentOptions, PaymentReason, base_resources,
};
use crate::player::{can_add_army_unit, gain_resources, gain_unit};
use crate::playing_actions::PlayingActionType;
use crate::position::Position;
use crate::resource_pile::ResourcePile;
use crate::special_advance::{SpecialAdvance, SpecialAdvanceInfo, SpecialAdvanceRequirement};
@ -38,7 +39,12 @@ fn aqueduct() -> SpecialAdvanceInfo {
"Ignore Famine events. \
Sanitation cost is reduced to 0 resources or a free action",
)
.add_custom_action(CustomActionType::Aqueduct)
.add_custom_action(
CustomActionType::Aqueduct,
|_| CustomActionType::free_and_advance_cost_without_discounts(),
use_aqueduct,
|_game, p| !p.has_advance(Advance::Sanitation) && p.can_afford(&base_advance_cost(p)),
)
.add_transient_event_listener(
|event| &mut event.advance_cost,
3,
@ -54,25 +60,23 @@ fn aqueduct() -> SpecialAdvanceInfo {
.build()
}
pub(crate) fn use_aqueduct() -> Builtin {
Builtin::builder("Aqueduct", "Gain Sanitation as a free action")
.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, player, name, a| {
game.add_info_log_item(&format!(
"{name} uses Aqueduct to gain Sanitation as a free action",
));
gain_advance_without_payment(
game,
Advance::Sanitation,
player,
a.payment.clone(),
true,
);
},
)
.build()
fn use_aqueduct(b: AbilityBuilder) -> AbilityBuilder {
b.add_simple_persistent_event_listener(
|event| &mut event.custom_action,
0,
|game, player, name, a| {
game.add_info_log_item(&format!(
"{name} uses Aqueduct to gain Sanitation as a free action",
));
gain_advance_without_payment(
game,
Advance::Sanitation,
player,
a.payment.clone(),
true,
);
},
)
}
fn roman_roads() -> SpecialAdvanceInfo {
@ -174,9 +178,23 @@ fn augustus() -> LeaderInfo {
LeaderInfo::new(
Leader::Augustus,
"Augustus",
LeaderAbility::builder("Princeps", PRINCEPS)
.add_custom_action(CustomActionType::Princeps)
.build(),
LeaderAbility::builder(
"Princeps",
"As an action, pay 1 culture token and \
activate the city where Augustus is: \
Draw 1 action and 1 objective card. \
Then discard 1 action and 1 objective card.",
)
.add_custom_action(
CustomActionType::Princeps,
|_| CustomActionType::cost(ResourcePile::culture_tokens(1)),
use_princeps,
|game, p| {
game.try_get_any_city(leader_position(p))
.is_some_and(City::can_activate)
},
)
.build(),
LeaderAbility::builder(
"Imperator",
"If you don't own a city in the region: \
@ -198,64 +216,57 @@ fn augustus() -> LeaderInfo {
)
}
const PRINCEPS: &str = "As an action, pay 1 culture token and \
activate the city where Augustus is: \
Draw 1 action and 1 objective card. \
Then discard 1 action and 1 objective card.";
pub(crate) fn use_princeps() -> Builtin {
Builtin::builder("Princeps", PRINCEPS)
.add_hand_card_request(
|event| &mut event.custom_action,
0,
|game, player, _| {
let p = game.player_mut(player);
let position = leader_position(p);
p.get_city_mut(position).activate();
game.add_info_log_item(&format!(
"{} activates the city {position} \
fn use_princeps(b: AbilityBuilder) -> AbilityBuilder {
b.add_hand_card_request(
|event| &mut event.custom_action,
0,
|game, player, _| {
let p = game.player_mut(player);
let position = leader_position(p);
p.get_city_mut(position).activate();
game.add_info_log_item(&format!(
"{} activates the city {position} \
to draw 1 action and 1 objective card using Princeps",
game.player_name(player)
));
gain_action_card_from_pile(game, player);
gain_objective_card_from_pile(game, player);
game.player_name(player)
));
gain_action_card_from_pile(game, player);
gain_objective_card_from_pile(game, player);
let p = game.player(player);
Some(HandCardsRequest::new(
all_action_hand_cards(p)
.into_iter()
.chain(all_objective_hand_cards(p))
.collect_vec(),
2..=2,
"Select 1 action and 1 objective card from your hand",
))
},
|game, s, _| {
let p = s.player_index;
for c in &s.choice {
match c {
HandCard::ActionCard(card) => {
game.add_info_log_item(&format!(
"{} discarded action card {} for Princeps",
s.player_name,
game.cache.get_action_card(*card).name()
));
discard_action_card(game, p, *card);
}
HandCard::ObjectiveCard(card) => {
game.add_info_log_item(&format!(
"{} discarded objective card {} for Princeps",
s.player_name,
game.cache.get_objective_card(*card).name()
));
discard_objective_card(game, p, *card);
}
HandCard::Wonder(_) => panic!("Invalid hand card type"),
let p = game.player(player);
Some(HandCardsRequest::new(
all_action_hand_cards(p)
.into_iter()
.chain(all_objective_hand_cards(p))
.collect_vec(),
2..=2,
"Select 1 action and 1 objective card from your hand",
))
},
|game, s, _| {
let p = s.player_index;
for c in &s.choice {
match c {
HandCard::ActionCard(card) => {
game.add_info_log_item(&format!(
"{} discarded action card {} for Princeps",
s.player_name,
game.cache.get_action_card(*card).name()
));
discard_action_card(game, p, *card);
}
HandCard::ObjectiveCard(card) => {
game.add_info_log_item(&format!(
"{} discarded objective card {} for Princeps",
s.player_name,
game.cache.get_objective_card(*card).name()
));
discard_objective_card(game, p, *card);
}
HandCard::Wonder(_) => panic!("Invalid hand card type"),
}
},
)
.build()
}
},
)
}
pub(crate) fn validate_princeps_cards(cards: &[HandCard]) -> Result<(), String> {
@ -285,7 +296,11 @@ fn caesar() -> LeaderInfo {
"As a free action, you may use 'Increase happiness' \
to increase happiness in the city where Caesar is.",
)
.add_custom_action(CustomActionType::StatesmanIncreaseHappiness)
.add_action_modifier(
CustomActionType::StatesmanIncreaseHappiness,
|_| CustomActionType::free(ResourcePile::empty()),
PlayingActionType::IncreaseHappiness,
)
.build(),
LeaderAbility::builder(
"Proconsul",

View file

@ -1,30 +1,16 @@
use crate::advance::{Advance, base_advance_cost};
use crate::city::{City, MoodState};
use crate::content::advances::autocracy::{use_absolute_power, use_forced_labor};
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::ability::Ability;
use crate::content::persistent_events::{
PersistentEventType, TriggerPersistentEventParams, trigger_persistent_event_with_listener,
};
use crate::content::wonders::{
great_lighthouse_city, great_lighthouse_spawns, use_great_library, use_great_lighthouse,
use_great_statue,
};
use crate::leader::leader_position;
use crate::events::EventOrigin;
use crate::player::Player;
use crate::playing_actions::{ActionResourceCost, PlayingActionType};
use crate::position::Position;
use crate::wonder::Wonder;
use crate::{game::Game, playing_actions::ActionCost, resource_pile::ResourcePile};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Display;
use std::fmt::{Debug, Display};
use std::sync::Arc;
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct CustomAction {
@ -65,7 +51,7 @@ pub struct CustomActionInfo {
impl CustomActionInfo {
#[must_use]
fn new(
pub(crate) fn new(
free: bool,
once_per_turn: Option<CustomActionType>,
cost: ActionResourceCost,
@ -77,6 +63,76 @@ impl CustomActionInfo {
}
}
#[derive(Clone)]
pub struct CustomActionCommand {
pub action: CustomActionType,
pub execution: CustomActionExecution,
pub event_origin: EventOrigin,
pub info: CustomActionInfo,
}
impl CustomActionCommand {
#[must_use]
pub fn new(
action: CustomActionType,
execution: CustomActionExecution,
event_origin: EventOrigin,
info: CustomActionInfo,
) -> CustomActionCommand {
CustomActionCommand {
action,
execution,
event_origin,
info,
}
}
#[must_use]
pub fn is_city_available(&self, game: &Game, city: &City) -> bool {
self.city_bound().is_some_and(|checker| checker(game, city))
}
#[must_use]
pub fn city_bound(&self) -> Option<&CustomActionCityChecker> {
if let CustomActionExecution::Action(a) = &self.execution {
a.city_checker.as_ref()
} else {
None
}
}
}
type CustomActionChecker = Arc<dyn Fn(&Game, &Player) -> bool + Sync + Send>;
type CustomActionCityChecker = Arc<dyn Fn(&Game, &City) -> bool + Sync + Send>;
#[derive(Clone)]
pub struct CustomActionActionExecution {
pub checker: CustomActionChecker,
pub execution: Ability,
pub city_checker: Option<CustomActionCityChecker>,
}
impl CustomActionActionExecution {
#[must_use]
pub fn new(
execution: Ability,
checker: CustomActionChecker,
city_checker: Option<CustomActionCityChecker>,
) -> Self {
Self {
checker,
execution,
city_checker,
}
}
}
#[derive(Clone)]
pub enum CustomActionExecution {
Modifier(PlayingActionType),
Action(CustomActionActionExecution),
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Hash, Debug)]
pub enum CustomActionType {
// Advances
@ -106,106 +162,44 @@ pub enum CustomActionType {
HellenisticInfluenceCultureAttempt,
Idol,
Master,
// China
ImperialArmy,
}
impl CustomActionType {
#[must_use]
pub fn info(&self) -> CustomActionInfo {
match self {
CustomActionType::AbsolutePower => {
self.free_and_once_per_turn(ResourcePile::mood_tokens(2))
}
CustomActionType::CivilLiberties | CustomActionType::Sports => {
CustomActionType::regular()
}
CustomActionType::GreatLighthouse | CustomActionType::StatesmanIncreaseHappiness => {
CustomActionType::free(ResourcePile::empty())
}
CustomActionType::Bartering
| CustomActionType::Theaters
| CustomActionType::GreatLibrary
| CustomActionType::GreatStatue => self.free_and_once_per_turn(ResourcePile::empty()),
CustomActionType::ArtsInfluenceCultureAttempt => {
self.free_and_once_per_turn(ResourcePile::culture_tokens(1))
}
CustomActionType::HellenisticInfluenceCultureAttempt => {
CustomActionType::free_and_once_per_turn_mutually_exclusive(
ResourcePile::mood_tokens(2),
CustomActionType::ArtsInfluenceCultureAttempt,
)
}
CustomActionType::VotingIncreaseHappiness => {
CustomActionType::cost(ResourcePile::mood_tokens(1))
}
CustomActionType::Princeps => CustomActionType::cost(ResourcePile::culture_tokens(1)),
CustomActionType::FreeEconomyCollect | CustomActionType::ForcedLabor => {
self.free_and_once_per_turn(ResourcePile::mood_tokens(1))
}
CustomActionType::Taxes => self.once_per_turn(ResourcePile::mood_tokens(1)),
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))
}
}
}
#[must_use]
pub fn is_available(&self, game: &Game, player_index: usize) -> bool {
self.playing_action_type()
.is_available(game, player_index)
.is_ok()
}
#[must_use]
pub fn is_available_city(&self, player: &Player, city: &City) -> bool {
match self {
CustomActionType::Sports => {
sports_options(player, city).is_some_and(|c| c.can_afford(&player.resources))
}
_ => false,
}
}
#[must_use]
pub fn is_city_bound(&self) -> bool {
matches!(self, CustomActionType::Sports)
}
#[must_use]
pub fn playing_action_type(&self) -> PlayingActionType {
PlayingActionType::Custom(*self)
}
#[must_use]
fn regular() -> CustomActionInfo {
pub(crate) fn regular() -> CustomActionInfo {
CustomActionInfo::new(false, None, ActionResourceCost::free())
}
#[must_use]
fn cost(cost: ResourcePile) -> CustomActionInfo {
pub(crate) fn cost(cost: ResourcePile) -> CustomActionInfo {
CustomActionInfo::new(true, None, ActionResourceCost::resources(cost))
}
#[must_use]
fn once_per_turn(self, cost: ResourcePile) -> CustomActionInfo {
pub(crate) fn once_per_turn(self, cost: ResourcePile) -> CustomActionInfo {
CustomActionInfo::new(false, Some(self), ActionResourceCost::resources(cost))
}
#[must_use]
fn free(cost: ResourcePile) -> CustomActionInfo {
pub(crate) fn free(cost: ResourcePile) -> CustomActionInfo {
CustomActionInfo::new(true, None, ActionResourceCost::resources(cost))
}
#[must_use]
fn free_and_once_per_turn(self, cost: ResourcePile) -> CustomActionInfo {
pub(crate) fn free_and_once_per_turn(self, cost: ResourcePile) -> CustomActionInfo {
CustomActionInfo::new(true, Some(self), ActionResourceCost::resources(cost))
}
#[must_use]
fn free_and_once_per_turn_mutually_exclusive(
pub(crate) fn free_and_once_per_turn_mutually_exclusive(
cost: ResourcePile,
mutually_exclusive: CustomActionType,
) -> CustomActionInfo {
@ -217,16 +211,9 @@ impl CustomActionType {
}
#[must_use]
fn free_and_advance_cost_without_discounts() -> CustomActionInfo {
pub(crate) fn free_and_advance_cost_without_discounts() -> CustomActionInfo {
CustomActionInfo::new(true, None, ActionResourceCost::AdvanceCostWithoutDiscount)
}
#[must_use]
pub fn is_modifier(&self) -> bool {
collect_modifiers().contains(self)
|| influence_modifiers().contains(self)
|| happiness_modifiers().contains(self)
}
}
impl Display for CustomActionType {
@ -257,39 +244,28 @@ impl Display for CustomActionType {
}
CustomActionType::Idol => write!(f, "Idol"),
CustomActionType::Master => write!(f, "Master"),
CustomActionType::ImperialArmy => write!(f, "Imperial Army"),
}
}
}
pub(crate) fn custom_action_builtins() -> HashMap<CustomActionType, Builtin> {
HashMap::from([
(CustomActionType::AbsolutePower, use_absolute_power()),
(CustomActionType::ForcedLabor, use_forced_labor()),
(CustomActionType::CivilLiberties, use_civil_liberties()),
(CustomActionType::Bartering, use_bartering()),
(CustomActionType::Sports, use_sports()),
(CustomActionType::Taxes, use_taxes()),
(CustomActionType::Theaters, use_theaters()),
(CustomActionType::GreatLibrary, use_great_library()),
(CustomActionType::GreatLighthouse, use_great_lighthouse()),
(CustomActionType::GreatStatue, use_great_statue()),
(CustomActionType::Aqueduct, use_aqueduct()),
(CustomActionType::Princeps, use_princeps()),
(CustomActionType::Idol, use_idol()),
(CustomActionType::Master, use_master()),
])
}
pub(crate) fn execute_custom_action(
game: &mut Game,
player_index: usize,
a: CustomActionActivation,
) {
let CustomActionExecution::Action(e) = game
.player(player_index)
.custom_action_command(a.action.action)
.execution
else {
panic!("Custom action {:?} is not an action", &a.action);
};
let _ = trigger_persistent_event_with_listener(
game,
&[player_index],
|e| &mut e.custom_action,
&custom_action_builtins()[&a.action.action.clone()].listeners,
&e.execution.listeners,
a,
PersistentEventType::CustomAction,
TriggerPersistentEventParams::default(),
@ -305,77 +281,41 @@ pub(crate) fn can_play_custom_action(
return Err("Custom action not available".to_string());
}
if let Some(key) = c.info().once_per_turn {
let command = p.custom_action_command(c);
if let Some(key) = command.info.once_per_turn {
if p.played_once_per_turn_actions.contains(&key) {
return Err("Custom action already played this turn".to_string());
}
}
let can_play = match c {
CustomActionType::Bartering => !p.action_cards.is_empty(),
CustomActionType::Sports => can_use_sports(p),
CustomActionType::Theaters => p.resources.culture_tokens > 0 || p.resources.mood_tokens > 0,
CustomActionType::ForcedLabor => any_angry(p),
CustomActionType::GreatStatue => !p.objective_cards.is_empty(),
CustomActionType::GreatLighthouse => {
great_lighthouse_city(p).can_activate()
&& p.available_units().ships > 0
&& !great_lighthouse_spawns(game, p.index).is_empty()
if let CustomActionExecution::Action(e) = &command.execution {
if !(e.checker)(game, p) {
return Err("Custom action cannot be played".to_string());
}
CustomActionType::Aqueduct => {
!p.has_advance(Advance::Sanitation) && p.can_afford(&base_advance_cost(p))
}
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 {
return Err("Cannot play custom action".to_string());
}
Ok(())
}
fn can_use_sports(p: &Player) -> bool {
if !any_non_happy(p) {
return false;
}
if p.resources.culture_tokens > 0 {
return true;
}
p.wonders_owned.contains(Wonder::Colosseum) && p.resources.mood_tokens > 0
}
fn any_non_happy(player: &Player) -> bool {
pub(crate) fn any_non_happy(player: &Player) -> bool {
player
.cities
.iter()
.any(|city| city.mood_state != MoodState::Happy)
}
fn any_angry(player: &Player) -> bool {
player
.cities
.iter()
.any(|city| city.mood_state == MoodState::Angry)
}
pub(crate) fn influence_modifiers() -> Vec<CustomActionType> {
vec![
CustomActionType::ArtsInfluenceCultureAttempt,
CustomActionType::HellenisticInfluenceCultureAttempt,
]
}
pub(crate) fn happiness_modifiers() -> Vec<CustomActionType> {
vec![
CustomActionType::VotingIncreaseHappiness,
CustomActionType::StatesmanIncreaseHappiness,
]
}
pub(crate) fn collect_modifiers() -> Vec<CustomActionType> {
vec![CustomActionType::FreeEconomyCollect]
pub(crate) fn is_base_or_modifier(
action_type: &PlayingActionType,
p: &Player,
base_type: &PlayingActionType,
) -> bool {
match base_type {
PlayingActionType::Custom(c) => {
if let CustomActionExecution::Modifier(t) = &p.custom_action_command(*c).execution {
t == action_type
} else {
false
}
}
action_type => action_type == base_type,
}
}

View file

@ -2,7 +2,7 @@ use crate::ability_initializer::{AbilityInitializerSetup, SelectedChoice};
use crate::advance::Advance;
use crate::city::non_angry_cites;
use crate::city::{City, MoodState};
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::UnitsRequest;
use crate::game::Game;
@ -85,8 +85,8 @@ pub(crate) fn additional_sanitation_damage(p: &Player) -> bool {
|| p.can_use_advance(Advance::TradeRoutes)
}
pub(crate) fn pestilence_permanent_effect() -> Builtin {
Builtin::builder(
pub(crate) fn pestilence_permanent_effect() -> Ability {
Ability::builder(
"Pestilence",
"You cannot construct buildings or wonders until you research Sanitation.",
)

View file

@ -2,7 +2,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::ActionCard;
use crate::card::HandCard;
use crate::construct::available_buildings;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::ConstructEffect;
use crate::content::effects::PermanentEffect::Construct;
use crate::content::incidents::great_persons::{
@ -58,8 +58,8 @@ pub(crate) fn can_construct_anything(game: &Game, p: &Player) -> bool {
.any(|city| !available_buildings(game, p.index, city.position).is_empty())
}
pub(crate) fn construct_only() -> Builtin {
Builtin::builder("construct only", "-")
pub(crate) fn construct_only() -> Ability {
Ability::builder("construct only", "-")
.add_transient_event_listener(
|event| &mut event.is_playing_action_available,
2,

View file

@ -1,6 +1,6 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::ActionCard;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::PermanentEffect;
use crate::content::incidents::great_persons::{
GREAT_PERSON_DESCRIPTION, great_person_action_card,
@ -93,8 +93,8 @@ pub(crate) fn choose_diplomat_partner(b: IncidentBuilder) -> IncidentBuilder {
)
}
pub(crate) fn use_diplomatic_relations() -> Builtin {
Builtin::builder("Diplomatic Relations", "")
pub(crate) fn use_diplomatic_relations() -> Ability {
Ability::builder("Diplomatic Relations", "")
.add_simple_persistent_event_listener(
|e| &mut e.combat_start,
2,

View file

@ -1,7 +1,7 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::ActionCard;
use crate::combat::CombatModifier;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::incidents::great_persons::{
great_person_action_card, great_person_description,
};
@ -38,8 +38,8 @@ pub(crate) fn great_warlord() -> ActionCard {
.build()
}
pub(crate) fn use_great_warlord() -> Builtin {
Builtin::builder("great_warlord", "-")
pub(crate) fn use_great_warlord() -> Ability {
Ability::builder("great_warlord", "-")
.add_simple_persistent_event_listener(
|event| &mut event.combat_start,
9,

View file

@ -3,7 +3,7 @@ use crate::advance::undo_unlock_special_advance;
use crate::advance::{find_government_special_advance, remove_advance};
use crate::combat::{Combat, CombatModifier, CombatRetreatState};
use crate::combat_listeners::CombatResult;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::{Anarchy, PermanentEffect};
use crate::content::persistent_events::{PaymentRequest, PositionRequest, UnitTypeRequest};
use crate::game::Game;
@ -37,8 +37,8 @@ fn trojan_horse() -> Incident {
.build()
}
pub(crate) fn decide_trojan_horse() -> Builtin {
Builtin::builder("Trojan Horse", TROJAN_DESCRIPTION)
pub(crate) fn decide_trojan_horse() -> Ability {
Ability::builder("Trojan Horse", TROJAN_DESCRIPTION)
.add_payment_request_listener(
|event| &mut event.combat_start,
10,
@ -102,8 +102,8 @@ fn solar_eclipse() -> Incident {
.build()
}
pub(crate) fn solar_eclipse_end_combat() -> Builtin {
Builtin::builder("Solar Eclipse", "-")
pub(crate) fn solar_eclipse_end_combat() -> Ability {
Ability::builder("Solar Eclipse", "-")
.add_simple_persistent_event_listener(
|event| &mut event.combat_round_end,
10,
@ -325,8 +325,8 @@ fn anarchy() -> Incident {
.build()
}
pub(crate) fn anarchy_advance() -> Builtin {
Builtin::builder("Anarchy", "-")
pub(crate) fn anarchy_advance() -> Ability {
Ability::builder("Anarchy", "-")
.add_simple_persistent_event_listener(
|event| &mut event.advance,
10,

View file

@ -4,7 +4,7 @@ use crate::advance::{Advance, init_great_library};
use crate::card::{HandCard, all_objective_hand_cards};
use crate::city::{City, MoodState};
use crate::combat_listeners::CombatRoundEnd;
use crate::content::builtin::Builtin;
use crate::content::ability::{Ability, AbilityBuilder};
use crate::content::custom_actions::CustomActionType;
use crate::content::persistent_events::{
AdvanceRequest, HandCardsRequest, PaymentRequest, PositionRequest,
@ -78,19 +78,20 @@ fn great_statue() -> WonderInfo {
PaymentOptions::fixed_resources(ResourcePile::new(3, 4, 5, 0, 0, 0, 5)),
Advance::Monuments,
)
.add_custom_action(CustomActionType::GreatStatue)
.add_custom_action(
CustomActionType::GreatStatue,
|a| a.free_and_once_per_turn(ResourcePile::empty()),
use_great_statue,
|_game, p| !p.objective_cards.is_empty(),
)
.add_one_time_ability_initializer(|game, player_index| {
gain_objective_card_from_pile(game, player_index);
})
.build()
}
pub(crate) fn use_great_statue() -> Builtin {
Builtin::builder(
"Great Statue",
"Discard an objectives card from your hand: Gain 1 action.",
)
.add_hand_card_request(
fn use_great_statue(b: AbilityBuilder) -> AbilityBuilder {
b.add_hand_card_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
@ -114,7 +115,6 @@ pub(crate) fn use_great_statue() -> Builtin {
game.actions_left += 1;
},
)
.build()
}
fn great_mausoleum() -> WonderInfo {
@ -130,8 +130,8 @@ fn great_mausoleum() -> WonderInfo {
.build()
}
pub(crate) fn use_great_mausoleum() -> Builtin {
Builtin::builder("Great Mausoleum", "")
pub(crate) fn use_great_mausoleum() -> Ability {
Ability::builder("Great Mausoleum", "")
.add_bool_request(
|event| &mut event.choose_action_card,
0,
@ -210,7 +210,16 @@ fn great_lighthouse() -> WonderInfo {
.placement_requirement(Arc::new(|pos, game| {
game.get_any_city(pos).pieces.port.is_some()
}))
.add_custom_action(CustomActionType::GreatLighthouse)
.add_custom_action(
CustomActionType::GreatLighthouse,
|_| CustomActionType::free(ResourcePile::empty()),
use_great_lighthouse,
|game, p| {
great_lighthouse_city(p).can_activate()
&& p.available_units().ships > 0
&& !great_lighthouse_spawns(game, p.index).is_empty()
},
)
.build()
}
@ -231,12 +240,8 @@ pub(crate) fn great_lighthouse_spawns(game: &Game, player: usize) -> Vec<Positio
.collect_vec()
}
pub(crate) fn use_great_lighthouse() -> Builtin {
Builtin::builder(
"Great Lighthouse",
"Activate the city: Place a ship on any sea space without enemy ships.",
)
.add_position_request(
fn use_great_lighthouse(b: AbilityBuilder) -> AbilityBuilder {
b.add_position_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
@ -261,55 +266,55 @@ pub(crate) fn use_great_lighthouse() -> Builtin {
.activate();
},
)
.build()
}
const GREAT_LIBRARY: &str = "Once per turn, as a free action, \
you may choose a non-government, non-civilization advance: \
Use the effect until the end of your turn.";
fn library() -> WonderInfo {
WonderInfo::builder(
Wonder::GreatLibrary,
"Great Library",
GREAT_LIBRARY,
"Once per turn, as a free action, \
you may choose a non-government, non-civilization advance: \
Use the effect until the end of your turn.",
PaymentOptions::fixed_resources(ResourcePile::new(3, 6, 3, 0, 0, 0, 5)),
Advance::Philosophy,
)
.add_custom_action(CustomActionType::GreatLibrary)
.add_custom_action(
CustomActionType::GreatLibrary,
|a| a.free_and_once_per_turn(ResourcePile::empty()),
use_great_library,
|_, _| true,
)
.build()
}
pub(crate) fn use_great_library() -> Builtin {
Builtin::builder("Great Library", GREAT_LIBRARY)
.add_advance_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
let player = game.player(player_index);
Some(AdvanceRequest::new(
game.cache
.get_advances()
.iter()
.filter_map(|a| {
(a.government.is_none() && !player.has_advance(a.advance))
.then_some(a.advance)
})
.collect_vec(),
))
},
|game, s, _| {
let advance = s.choice;
game.add_info_log_item(&format!(
"{} used the Great Library to use {} for the turn",
s.player_name,
advance.name(game)
));
game.player_mut(s.player_index).great_library_advance = Some(advance);
init_great_library(game, s.player_index);
},
)
.build()
fn use_great_library(b: AbilityBuilder) -> AbilityBuilder {
b.add_advance_request(
|event| &mut event.custom_action,
0,
|game, player_index, _| {
let player = game.player(player_index);
Some(AdvanceRequest::new(
game.cache
.get_advances()
.iter()
.filter_map(|a| {
(a.government.is_none() && !player.has_advance(a.advance))
.then_some(a.advance)
})
.collect_vec(),
))
},
|game, s, _| {
let advance = s.choice;
game.add_info_log_item(&format!(
"{} used the Great Library to use {} for the turn",
s.player_name,
advance.name(game)
));
game.player_mut(s.player_index).great_library_advance = Some(advance);
init_great_library(game, s.player_index);
},
)
}
fn great_gardens() -> WonderInfo {

View file

@ -3,8 +3,7 @@ use crate::action::Action;
use crate::city::City;
use crate::city_pieces::Building;
use crate::consts::INFLUENCE_MIN_ROLL;
use crate::content::builtin::Builtin;
use crate::content::custom_actions::influence_modifiers;
use crate::content::ability::Ability;
use crate::content::persistent_events::{
PaymentRequest, PersistentEventType, SelectedStructure, Structure,
};
@ -123,8 +122,8 @@ pub(crate) fn on_cultural_influence(
);
}
pub(crate) fn use_cultural_influence() -> Builtin {
Builtin::builder("Influence Culture", "")
pub(crate) fn use_cultural_influence() -> Ability {
Ability::builder("Influence Culture", "")
.add_payment_request_listener(
|e| &mut e.influence_culture,
2,
@ -459,7 +458,7 @@ pub fn affordable_start_city(
let mut action_cost = ResourcePile::empty();
if let Some(t) = action_type {
// either none (action cost and boost cost) or both can use Colosseum
action_cost = t.cost(game).payment_options(player).default;
action_cost = t.cost(game, player_index).payment_options(player).default;
let c = action_cost.culture_tokens;
if c > 0 {
tokens -= c;
@ -565,10 +564,5 @@ pub(crate) fn format_cultural_influence_attempt_log_item(
#[must_use]
pub fn available_influence_actions(game: &Game, player: usize) -> Vec<PlayingActionType> {
base_or_custom_available(
game,
player,
PlayingActionType::InfluenceCultureAttempt,
influence_modifiers(),
)
base_or_custom_available(game, player, &PlayingActionType::InfluenceCultureAttempt)
}

View file

@ -6,7 +6,7 @@ pub enum EventOrigin {
SpecialAdvance(SpecialAdvance),
LeaderAbility(String),
Wonder(Wonder),
Builtin(String),
Ability(String),
Incident(u8),
CivilCard(u8),
TacticsCard(u8),
@ -23,7 +23,7 @@ impl EventOrigin {
EventOrigin::SpecialAdvance(name) => format!("{name:?}"),
EventOrigin::LeaderAbility(name)
| EventOrigin::Objective(name)
| EventOrigin::Builtin(name) => name.to_string(),
| EventOrigin::Ability(name) => name.to_string(),
EventOrigin::CivilCard(id)
| EventOrigin::TacticsCard(id)
| EventOrigin::Incident(id) => id.to_string(),
@ -39,7 +39,7 @@ impl EventOrigin {
EventOrigin::Wonder(name) => name.name(game).to_string(),
EventOrigin::LeaderAbility(name)
| EventOrigin::Objective(name)
| EventOrigin::Builtin(name) => name.to_string(),
| EventOrigin::Ability(name) => name.to_string(),
EventOrigin::CivilCard(id) => cache.get_civil_card(*id).name.clone(),
EventOrigin::TacticsCard(id) => cache.get_tactics_card(*id).name.clone(),
EventOrigin::Incident(id) => cache.get_incident(*id).name.clone(),

View file

@ -1,6 +1,6 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::advance::Advance;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::persistent_events::{
EventResponse, PersistentEventRequest, PersistentEventType,
};
@ -268,8 +268,8 @@ fn add_block_tiles_with_log(
game.map.add_block_tiles(pos, block, rotation);
}
pub(crate) fn explore_resolution() -> Builtin {
Builtin::builder(
pub(crate) fn explore_resolution() -> Ability {
Ability::builder(
"Explore Resolution",
"Select a rotation for the unexplored tiles",
)

View file

@ -1,12 +1,13 @@
use crate::cache::Cache;
use crate::combat_roll::{COMBAT_DIE_SIDES, CombatDieRoll};
use crate::consts::ACTIONS;
use crate::content::custom_actions::{CustomActionCommand, CustomActionExecution};
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{
PersistentEventHandler, PersistentEventState, PersistentEventType,
TriggerPersistentEventParams, trigger_persistent_event_ext,
};
use crate::events::{Event, EventOrigin};
use crate::events::Event;
use crate::game_data::GameData;
use crate::log::{
ActionLogAge, ActionLogPlayer, ActionLogRound, current_player_turn_log,
@ -22,10 +23,7 @@ use crate::resource::check_for_waste;
use crate::status_phase::enter_status_phase;
use crate::utils::Rng;
use crate::wonder::Wonder;
use crate::{
city::City, content::custom_actions::CustomActionType, game_data, map::Map, player::Player,
position::Position,
};
use crate::{city::City, game_data, map::Map, player::Player, position::Position};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::vec;
@ -495,23 +493,23 @@ impl Game {
}
#[must_use]
pub fn available_custom_actions(
&self,
player_index: usize,
) -> Vec<(CustomActionType, EventOrigin)> {
pub fn available_custom_actions(&self, player_index: usize) -> Vec<CustomActionCommand> {
self.player(self.current_player_index)
.custom_actions
.clone()
.into_iter()
.filter(|(t, _)| {
if t.is_modifier() {
.values()
.filter(|&c| {
if matches!(c.execution, CustomActionExecution::Modifier(_)) {
// returned as part of "base_or_custom_available"
return false;
}
t.is_available(self, player_index)
c.action
.playing_action_type()
.is_available(self, player_index)
.is_ok()
})
.collect()
.cloned()
.collect_vec()
}
///

View file

@ -2,8 +2,8 @@ use crate::advance::{Advance, is_special_advance_active};
use crate::cache::Cache;
use crate::city::{City, CityData};
use crate::city_pieces::{DestroyedStructures, DestroyedStructuresData};
use crate::content::builtin;
use crate::content::builtin::Builtin;
use crate::content::ability;
use crate::content::ability::Ability;
use crate::content::custom_actions::CustomActionType;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::PersistentEventState;
@ -132,7 +132,7 @@ pub fn from_data(data: GameData, cache: Cache, context: GameContext) -> Game {
permanent_effects: data.permanent_effects,
events: data.events,
};
let all = game.cache.get_builtins().clone();
let all = game.cache.get_ability().clone();
for player in data.players {
initialize_player(player, &mut game, &all);
}
@ -288,12 +288,12 @@ pub struct PlayerData {
/// # Panics
///
/// Panics if elements like wonders or advances don't exist
fn initialize_player(data: PlayerData, game: &mut Game, all: &[Builtin]) {
fn initialize_player(data: PlayerData, game: &mut Game, all: &[Ability]) {
let objective_cards = data.objective_cards.clone();
let player = player_from_data(data, game);
let player_index = player.index;
game.players.push(player);
builtin::init_player(game, player_index, all);
ability::init_player(game, player_index, all);
advance::init_player(game, player_index);
if let Some(leader) = game.player(player_index).active_leader() {

View file

@ -3,7 +3,7 @@ use crate::advance::Advance;
use crate::cache::Cache;
use crate::consts::{ACTIONS, JSON_SCHEMA_VERSION, NON_HUMAN_PLAYERS};
use crate::content::civilizations::{BARBARIANS, PIRATES};
use crate::content::{builtin, civilizations};
use crate::content::{ability, civilizations};
use crate::game::{Game, GameContext, GameOptions, GameState};
use crate::map::Map;
use crate::objective_card::gain_objective_card_from_pile;
@ -133,7 +133,7 @@ pub fn setup_game_with_cache(setup: GameSetup, cache: Cache) -> Game {
.map(|i| i.id)
.collect_vec()
.shuffled(&mut rng);
let all = &cache.get_builtins().clone();
let all = &cache.get_ability().clone();
let mut game = Game {
seed: setup.seed.clone(),
context: GameContext::Play,
@ -171,7 +171,7 @@ pub fn setup_game_with_cache(setup: GameSetup, cache: Cache) -> Game {
permanent_effects: Vec::new(),
};
for i in 0..game.players.len() {
builtin::init_player(&mut game, i, all);
ability::init_player(&mut game, i, all);
}
for player_index in 0..setup.player_amount {

View file

@ -1,5 +1,5 @@
use crate::city::MoodState;
use crate::content::custom_actions::{CustomActionType, happiness_modifiers};
use crate::content::custom_actions::CustomActionType;
use crate::game::Game;
use crate::leader::leader_position;
use crate::payment::{PaymentOptions, PaymentReason};
@ -12,12 +12,7 @@ use crate::resource_pile::ResourcePile;
#[must_use]
pub fn available_happiness_actions(game: &Game, player: usize) -> Vec<PlayingActionType> {
base_or_custom_available(
game,
player,
PlayingActionType::IncreaseHappiness,
happiness_modifiers(),
)
base_or_custom_available(game, player, &PlayingActionType::IncreaseHappiness)
}
#[must_use]
@ -89,7 +84,7 @@ pub fn happiness_cost(
&[ResourceType::MoodTokens],
);
// either none or both can use Colosseum
payment_options.default += action_type.cost(game).payment_options(p).default;
payment_options.default += action_type.cost(game, player).payment_options(p).default;
p.trigger_cost_event(|e| &e.happiness_cost, &payment_options, &(), &(), execute)
}

View file

@ -614,6 +614,14 @@ impl AbilityInitializerSetup for IncidentBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::Incident(self.id)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
pub(crate) fn trigger_incident(game: &mut Game, player_index: usize) {

View file

@ -118,6 +118,14 @@ impl AbilityInitializerSetup for LeaderAbilityBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::LeaderAbility(self.name.clone())
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
#[must_use]

View file

@ -3,7 +3,7 @@ use crate::ability_initializer::{
};
use crate::cache::Cache;
use crate::card::{HandCard, draw_card_from_pile};
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::PermanentEffect;
use crate::content::incidents::great_persons::find_great_seer;
use crate::content::persistent_events::{HandCardsRequest, PersistentEventType};
@ -129,6 +129,14 @@ impl AbilityInitializerSetup for ObjectiveBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::Objective(self.name.clone())
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
@ -207,8 +215,8 @@ pub(crate) fn on_objective_cards(game: &mut Game, player_index: usize, info: Sel
);
}
pub(crate) fn select_objectives() -> Builtin {
Builtin::builder(
pub(crate) fn select_objectives() -> Ability {
Ability::builder(
"Select Objective Cards to Complete",
"Select which Objective Cards to use \
(because the requirements are now met)",

View file

@ -1,7 +1,7 @@
use crate::ability_initializer::AbilityInitializerSetup;
use crate::barbarians;
use crate::city::MoodState;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::persistent_events::{
PaymentRequest, PositionRequest, ResourceRewardRequest, UnitsRequest,
};
@ -16,8 +16,8 @@ use crate::tactics_card::CombatRole;
use crate::unit::UnitType;
use itertools::Itertools;
pub(crate) fn pirates_round_bonus() -> Builtin {
Builtin::builder("Pirates bonus", "-")
pub(crate) fn pirates_round_bonus() -> Ability {
Ability::builder("Pirates bonus", "-")
.add_resource_request(
|event| &mut event.combat_round_end,
3,
@ -44,8 +44,8 @@ pub(crate) fn pirates_round_bonus() -> Builtin {
.build()
}
pub(crate) fn pirates_bonus() -> Builtin {
Builtin::builder(
pub(crate) fn pirates_bonus() -> Ability {
Ability::builder(
"Barbarians bonus",
"Select a reward for fighting the Pirates",
)

View file

@ -1,10 +1,12 @@
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::content::custom_actions::{CustomActionCommand, CustomActionExecution};
use crate::events::Event;
use crate::leader::{Leader, LeaderAbility};
use crate::payment::{PaymentOptions, PaymentReason};
use crate::player_events::{CostInfo, TransientEvents};
use crate::playing_actions::PlayingActionType;
use crate::special_advance::SpecialAdvance;
use crate::unit::UnitType;
use crate::wonder::{Wonder, wonders_built_points, wonders_owned_points};
@ -62,7 +64,7 @@ pub struct Player {
pub completed_objectives: Vec<String>,
pub captured_leaders: Vec<Leader>,
pub event_victory_points: f32,
pub custom_actions: HashMap<CustomActionType, EventOrigin>,
pub custom_actions: HashMap<CustomActionType, CustomActionCommand>, // transient
pub wonder_cards: Vec<Wonder>,
pub action_cards: Vec<u8>,
pub objective_cards: Vec<u8>,
@ -603,17 +605,37 @@ impl Player {
/// # Panics
/// Panics if the custom action type does not exist for this player
#[must_use]
pub fn custom_action_origin(&self, custom_action_type: &CustomActionType) -> EventOrigin {
pub fn custom_action_command(
&self,
custom_action_type: CustomActionType,
) -> CustomActionCommand {
self.custom_actions
.get(custom_action_type)
.get(&custom_action_type)
.cloned()
.unwrap_or_else(|| {
panic!(
"Custom action {} not found for player {}",
custom_action_type, self.index
"Custom action {custom_action_type:?} not found for player {}",
self.index
)
})
}
#[must_use]
pub(crate) fn custom_action_modifiers(
&self,
base: &PlayingActionType,
) -> Vec<CustomActionType> {
self.custom_actions
.iter()
.filter_map(move |(t, c)| {
if let CustomActionExecution::Modifier(b) = &c.execution {
(b == base).then_some(*t)
} else {
None
}
})
.collect_vec()
}
}
pub fn gain_unit(player: usize, position: Position, unit_type: UnitType, game: &mut Game) {

View file

@ -6,10 +6,10 @@ use crate::advance::{AdvanceAction, base_advance_cost, gain_advance_without_paym
use crate::city::found_city;
use crate::collect::{PositionCollection, collect};
use crate::construct::Construct;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::custom_actions::{
CustomAction, CustomActionActivation, CustomActionType, can_play_custom_action,
collect_modifiers, execute_custom_action, happiness_modifiers, influence_modifiers,
execute_custom_action,
};
use crate::content::persistent_events::{
PaymentRequest, PersistentEventType, TriggerPersistentEventParams, trigger_persistent_event_ext,
@ -125,7 +125,8 @@ impl PlayingActionType {
return Err("Game is not in playing state".to_string());
}
self.cost(game).is_available(game, player_index)?;
self.cost(game, player_index)
.is_available(game, player_index)?;
let p = game.player(player_index);
@ -162,9 +163,14 @@ impl PlayingActionType {
}
#[must_use]
pub fn cost(&self, game: &Game) -> ActionCost {
pub fn cost(&self, game: &Game, player: usize) -> ActionCost {
match self {
PlayingActionType::Custom(custom_action) => custom_action.info().action_type.clone(),
PlayingActionType::Custom(custom_action) => game
.player(player)
.custom_action_command(*custom_action)
.info
.action_type
.clone(),
PlayingActionType::ActionCard(id) => game.cache.get_civil_card(*id).action_type.clone(),
PlayingActionType::EndTurn => ActionCost::cost(ResourcePile::empty()),
_ => ActionCost::regular(),
@ -194,11 +200,11 @@ impl PlayingAction {
player_index: usize,
redo: bool,
) -> Result<(), String> {
let playing_action_type = self.playing_action_type();
let playing_action_type = self.playing_action_type(game.player(player_index));
if !redo {
playing_action_type.is_available(game, player_index)?;
}
let action_cost = playing_action_type.cost(game);
let action_cost = playing_action_type.cost(game, player_index);
if !action_cost.free {
game.actions_left -= 1;
}
@ -211,14 +217,23 @@ impl PlayingAction {
game: &mut Game,
player_index: usize,
) -> Result<(), String> {
let origin_override = match self.playing_action_type() {
let origin_override = match self.playing_action_type(game.player(player_index)) {
PlayingActionType::Custom(c) => {
if let Some(key) = c.info().once_per_turn {
if let Some(key) = &game
.player(player_index)
.custom_action_command(c)
.info
.once_per_turn
{
game.players[player_index]
.played_once_per_turn_actions
.push(key);
.push(*key);
}
Some(game.player(player_index).custom_action_origin(&c))
Some(
game.player(player_index)
.custom_action_command(c)
.event_origin,
)
}
PlayingActionType::ActionCard(c) => Some(EventOrigin::CivilCard(c)),
_ => None,
@ -287,26 +302,24 @@ impl PlayingAction {
}
#[must_use]
pub fn playing_action_type(&self) -> PlayingActionType {
pub fn playing_action_type(&self, player: &Player) -> PlayingActionType {
match self {
PlayingAction::Advance(_) => PlayingActionType::Advance,
PlayingAction::FoundCity { .. } => PlayingActionType::FoundCity,
PlayingAction::Construct(_) => PlayingActionType::Construct,
PlayingAction::Collect(c) => assert_allowed(
&c.action_type,
&PlayingActionType::Collect,
&collect_modifiers(),
),
PlayingAction::Collect(c) => {
assert_allowed_action_type(&c.action_type, &PlayingActionType::Collect, player)
}
PlayingAction::Recruit(_) => PlayingActionType::Recruit,
PlayingAction::IncreaseHappiness(h) => assert_allowed(
PlayingAction::IncreaseHappiness(h) => assert_allowed_action_type(
&h.action_type,
&PlayingActionType::IncreaseHappiness,
&happiness_modifiers(),
player,
),
PlayingAction::InfluenceCultureAttempt(i) => assert_allowed(
PlayingAction::InfluenceCultureAttempt(i) => assert_allowed_action_type(
&i.action_type,
&PlayingActionType::InfluenceCultureAttempt,
&influence_modifiers(),
player,
),
PlayingAction::ActionCard(a) => PlayingActionType::ActionCard(*a),
PlayingAction::WonderCard(name) => PlayingActionType::WonderCard(*name),
@ -316,14 +329,14 @@ impl PlayingAction {
}
}
fn assert_allowed(
fn assert_allowed_action_type(
playing_action_type: &PlayingActionType,
base_type: &PlayingActionType,
allowed_modifiers: &[CustomActionType],
player: &Player,
) -> PlayingActionType {
match playing_action_type {
PlayingActionType::Custom(c) => {
assert!(allowed_modifiers.contains(c));
assert!(player.custom_action_modifiers(base_type).contains(c));
}
_ => {
assert!(base_type == playing_action_type);
@ -415,12 +428,16 @@ impl ActionCost {
pub(crate) fn base_or_custom_available(
game: &Game,
player: usize,
action: PlayingActionType,
custom: Vec<CustomActionType>,
base: &PlayingActionType,
) -> Vec<PlayingActionType> {
vec![action]
vec![base.clone()]
.into_iter()
.chain(custom.into_iter().map(|c| c.playing_action_type()))
.chain(
game.player(player)
.custom_action_modifiers(base)
.iter()
.map(CustomActionType::playing_action_type),
)
.filter_map(|a| a.is_available(game, player).map(|()| a).ok())
.collect()
}
@ -466,8 +483,8 @@ impl ActionPayment {
}
}
pub(crate) fn pay_for_action() -> Builtin {
Builtin::builder("Pay for action card", "")
pub(crate) fn pay_for_action() -> Ability {
Ability::builder("Pay for action card", "")
.add_payment_request_listener(
|e| &mut e.pay_action,
0,
@ -479,8 +496,8 @@ pub(crate) fn pay_for_action() -> Builtin {
let payment_options = a
.action
.playing_action_type()
.cost(game)
.playing_action_type(game.player(player_index))
.cost(game, player_index)
.payment_options(game.player(player_index));
if payment_options.is_free() {
return None;

View file

@ -134,4 +134,12 @@ impl AbilityInitializerSetup for SpecialAdvanceBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::SpecialAdvance(self.advance)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}

View file

@ -2,7 +2,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::action_card::gain_action_card_from_pile;
use crate::advance::{Advance, do_advance, gain_advance_without_payment, remove_advance};
use crate::consts::AGES;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::persistent_events::{
AdvanceRequest, EventResponse, PaymentRequest, PersistentEventRequest, PersistentEventType,
PlayerRequest, PositionRequest, TriggerPersistentEventParams,
@ -126,8 +126,8 @@ pub(crate) fn play_status_phase(game: &mut Game, mut phase: StatusPhaseState) {
}
}
pub(crate) fn complete_objectives() -> Builtin {
Builtin::builder(
pub(crate) fn complete_objectives() -> Ability {
Ability::builder(
"Complete Objectives",
"Select Status Phase Objectives to Complete",
)
@ -147,8 +147,8 @@ pub(crate) fn complete_objectives() -> Builtin {
.build()
}
pub(crate) fn free_advance() -> Builtin {
Builtin::builder("Free Advance", "Advance for free")
pub(crate) fn free_advance() -> Ability {
Ability::builder("Free Advance", "Advance for free")
.add_advance_request(
|event| &mut event.status_phase,
0,
@ -183,8 +183,8 @@ pub(crate) fn free_advance() -> Builtin {
.build()
}
pub(crate) fn draw_cards() -> Builtin {
Builtin::builder("Draw Cards", "-")
pub(crate) fn draw_cards() -> Ability {
Ability::builder("Draw Cards", "-")
.add_simple_persistent_event_listener(
|event| &mut event.status_phase,
0,
@ -196,8 +196,8 @@ pub(crate) fn draw_cards() -> Builtin {
.build()
}
pub(crate) fn raze_city() -> Builtin {
Builtin::builder("Raze city", "Raze size 1 city for 1 gold")
pub(crate) fn raze_city() -> Ability {
Ability::builder("Raze city", "Raze size 1 city for 1 gold")
.add_position_request(
|event| &mut event.status_phase,
0,
@ -233,9 +233,9 @@ pub(crate) fn raze_city() -> Builtin {
.build()
}
pub(crate) fn may_change_government() -> Builtin {
pub(crate) fn may_change_government() -> Ability {
add_change_government(
Builtin::builder("Change Government", "Change your government"),
Ability::builder("Change Government", "Change your government"),
|event| &mut event.status_phase,
ChangeGovernmentOption::NotFreeAndOptional,
|_, _, _| true,
@ -434,8 +434,8 @@ pub(crate) fn can_change_government_for_free(player: &Player, game: &Game) -> bo
})
}
pub(crate) fn determine_first_player() -> Builtin {
Builtin::builder("Determine First Player", "Determine the first player")
pub(crate) fn determine_first_player() -> Ability {
Ability::builder("Determine First Player", "Determine the first player")
.add_player_request(
|event| &mut event.status_phase,
0,

View file

@ -273,6 +273,14 @@ impl AbilityInitializerSetup for TacticsCardBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::TacticsCard(self.id)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
pub(crate) fn play_tactics_card(b: AdvanceBuilder) -> AdvanceBuilder {

View file

@ -8,7 +8,7 @@ use crate::ability_initializer::AbilityInitializerSetup;
use crate::city::is_valid_city_terrain;
use crate::combat_roll::COMBAT_DIE_SIDES;
use crate::consts::SHIP_CAPACITY;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::persistent_events::{KilledUnits, PersistentEventType, UnitsRequest};
use crate::explore::is_any_ship;
use crate::game::GameState;
@ -613,8 +613,8 @@ fn save_carried_units(game: &mut Game, player: usize, pos: Position) {
}
}
pub(crate) fn choose_carried_units_to_remove() -> Builtin {
Builtin::builder(
pub(crate) fn choose_carried_units_to_remove() -> Ability {
Ability::builder(
"Choose Casualties (carried units)",
"Choose which carried units to remove.",
)

View file

@ -4,7 +4,7 @@ use crate::card::draw_card_from_pile;
use crate::city::{City, MoodState};
use crate::construct::can_construct_anything;
use crate::consts::WONDER_VICTORY_POINTS;
use crate::content::builtin::Builtin;
use crate::content::ability::Ability;
use crate::content::effects::PermanentEffect;
use crate::content::persistent_events::{PaymentRequest, PersistentEventType, PositionRequest};
use crate::events::EventOrigin;
@ -151,6 +151,14 @@ impl AbilityInitializerSetup for WonderBuilder {
fn get_key(&self) -> EventOrigin {
EventOrigin::Wonder(self.wonder)
}
fn name(&self) -> String {
self.name.clone()
}
fn description(&self) -> String {
self.description.clone()
}
}
pub(crate) fn draw_wonder_card(game: &mut Game, player_index: usize) {
@ -176,8 +184,8 @@ fn gain_wonder(game: &mut Game, player_index: usize, wonder: Wonder) {
game.players[player_index].wonder_cards.push(wonder);
}
pub(crate) fn on_draw_wonder_card() -> Builtin {
Builtin::builder("Draw Wonder Card", "Draw a wonder card")
pub(crate) fn on_draw_wonder_card() -> Ability {
Ability::builder("Draw Wonder Card", "Draw a wonder card")
.add_bool_request(
|e| &mut e.draw_wonder_card,
0,
@ -324,8 +332,8 @@ impl Default for WonderDiscount {
}
}
pub(crate) fn build_wonder() -> Builtin {
Builtin::builder("Build Wonder", "Build a wonder")
pub(crate) fn build_wonder() -> Ability {
Ability::builder("Build Wonder", "Build a wonder")
.add_position_request(
|e| &mut e.play_wonder_card,
11,

View file

@ -228,7 +228,7 @@
},
{
"op": "add",
"path": "/events/0/handler/origin/Builtin",
"path": "/events/0/handler/origin/Ability",
"value": "Pay for action card"
},
{
@ -415,4 +415,4 @@
"action_cards_discarded": [
2
]
}
}

View file

@ -263,7 +263,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -420,7 +420,7 @@
},
"handler": {
"origin": {
"Builtin": "Explore Resolution"
"Ability": "Explore Resolution"
},
"priority": 0,
"request": "ExploreResolution"

View file

@ -228,7 +228,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -240,7 +240,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -280,7 +280,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -246,7 +246,7 @@
},
"handler": {
"origin": {
"Builtin": "Bartering"
"Ability": "Bartering"
},
"priority": 0,
"request": {

View file

@ -282,7 +282,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -321,7 +321,7 @@
},
"handler": {
"origin": {
"Builtin": "Influence Culture"
"Ability": "Influence Culture"
},
"priority": 0,
"request": {

View file

@ -277,7 +277,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -296,7 +296,7 @@
},
"handler": {
"origin": {
"Builtin": "Sports"
"Ability": "Sports"
},
"priority": 0,
"request": {

View file

@ -296,7 +296,7 @@
},
"handler": {
"origin": {
"Builtin": "Sports"
"Ability": "Sports"
},
"priority": 0,
"request": {

View file

@ -325,7 +325,7 @@
},
{
"op": "replace",
"path": "/events/0/handler/origin/Builtin",
"path": "/events/0/handler/origin/Ability",
"value": "Pay for action card"
},
{
@ -410,7 +410,7 @@
},
"handler": {
"origin": {
"Builtin": "Taxes"
"Ability": "Taxes"
},
"priority": 0,
"request": {
@ -524,4 +524,4 @@
"wonders_left": [
"Pyramids"
]
}
}

View file

@ -315,7 +315,7 @@
},
"handler": {
"origin": {
"Builtin": "Theaters"
"Ability": "Theaters"
},
"priority": 0,
"request": {

View file

@ -319,7 +319,7 @@
},
"handler": {
"origin": {
"Builtin": "Influence Culture"
"Ability": "Influence Culture"
},
"priority": 0,
"request": {

View file

@ -284,7 +284,7 @@
},
"handler": {
"origin": {
"Builtin": "Select Objective Cards to Complete"
"Ability": "Select Objective Cards to Complete"
},
"priority": 0,
"request": {

View file

@ -407,7 +407,7 @@
"path": "/events/0/handler",
"value": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {
@ -507,7 +507,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -49,7 +49,7 @@
}
},
"origin": {
"Builtin": "Place Settler"
"Ability": "Place Settler"
}
}
}

View file

@ -252,7 +252,7 @@
},
"handler": {
"origin": {
"Builtin": "Pay for action card"
"Ability": "Pay for action card"
},
"priority": 0,
"request": {

View file

@ -394,7 +394,7 @@
},
{
"op": "replace",
"path": "/events/0/handler/origin/Builtin",
"path": "/events/0/handler/origin/Ability",
"value": "Barbarians bonus"
},
{
@ -473,7 +473,7 @@
},
"handler": {
"origin": {
"Builtin": "Select Objective Cards to Complete"
"Ability": "Select Objective Cards to Complete"
},
"priority": 0,
"request": {
@ -593,4 +593,4 @@
10,
1
]
}
}

View file

@ -76,7 +76,7 @@
}
},
"origin": {
"Builtin": "Choose Casualties"
"Ability": "Choose Casualties"
}
}
}

View file

@ -254,7 +254,7 @@
},
"handler": {
"origin": {
"Builtin": "Choose Casualties"
"Ability": "Choose Casualties"
},
"priority": 1,
"request": {

View file

@ -54,7 +54,7 @@
"BoolRequest": "Do you want to retreat?"
},
"origin": {
"Builtin": "Offer Retreat"
"Ability": "Offer Retreat"
}
}
}

View file

@ -260,7 +260,7 @@
},
"handler": {
"origin": {
"Builtin": "Offer Retreat"
"Ability": "Offer Retreat"
},
"priority": 0,
"request": {

View file

@ -54,7 +54,7 @@
"BoolRequest": "Do you want to retreat?"
},
"origin": {
"Builtin": "Offer Retreat"
"Ability": "Offer Retreat"
}
}
}

View file

@ -81,7 +81,7 @@
}
},
"origin": {
"Builtin": "Choose Casualties (carried units)"
"Ability": "Choose Casualties (carried units)"
}
}
}

View file

@ -60,7 +60,7 @@
"BoolRequest": "Do you want to retreat?"
},
"origin": {
"Builtin": "Offer Retreat"
"Ability": "Offer Retreat"
}
}
}

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -12,7 +12,7 @@
"BoolRequest": "Do you want to draw the public wonder card Pyramids?"
},
"origin": {
"Builtin": "Draw Wonder Card"
"Ability": "Draw Wonder Card"
}
}
}

View file

@ -310,7 +310,7 @@
"event_type": "DrawWonderCard",
"handler": {
"origin": {
"Builtin": "Draw Wonder Card"
"Ability": "Draw Wonder Card"
},
"priority": 0,
"request": {

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -407,7 +407,7 @@
},
"handler": {
"origin": {
"Builtin": "Build Wonder"
"Ability": "Build Wonder"
},
"priority": 10,
"request": {

View file

@ -435,7 +435,7 @@
},
"handler": {
"origin": {
"Builtin": "Explore Resolution"
"Ability": "Explore Resolution"
},
"priority": 0,
"request": "ExploreResolution"

View file

@ -19,7 +19,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
}
},
"origin": {
"Builtin": "Free Advance"
"Ability": "Free Advance"
}
}
}

View file

@ -33,7 +33,7 @@
"priority": 0,
"request": "ExploreResolution",
"origin": {
"Builtin": "Explore Resolution"
"Ability": "Explore Resolution"
}
}
}

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