diff --git a/Cargo.lock b/Cargo.lock index 00d03ac..261e72c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -276,6 +276,7 @@ dependencies = [ "serde", "serde_json", "thiserror", + "uuid", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 3807cf7..37fd960 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,5 +12,6 @@ miette = { version = "7.6.0", features = ["fancy"] } env_logger = "0.11.8" log = "0.4.28" derive_more = { version = "2.0.1", features = ["display", "add", "mul"] } +uuid = { version = "1.18.1", features = ["serde", "v4"] } colored = "3.0.0" insta = "1.44.3" diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index 652059b..cae5578 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -14,6 +14,7 @@ env_logger = {workspace = true} log = {workspace = true} derive_more = {workspace = true} colored = {workspace = true} +uuid = {workspace = true} [dev-dependencies] insta = {workspace = true} diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 42137d3..7b2e398 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -81,7 +81,7 @@ use lib_efo::{ stats, utils::RngLevel, }; -use log::info; +use log::{info, trace}; use crate::error::AppError; use crate::success::{SuccessMessages, display_success}; @@ -154,8 +154,8 @@ pub struct AddArgs { /// How to initialise *missing* stats. See the `--rng` option /// description for the valid values. - #[arg(value_enum, long, short, default_value_t = RngLevel::Med)] - pub rng: RngLevel, + #[arg(value_enum, long, short)] + pub rng: Option, #[command(flatten)] /// Common arguments between adding and editing @@ -244,6 +244,36 @@ pub struct CommonArgs { pub prestige_add: Option, } +impl CommonArgs { + /// Validate the parser usage + fn validate(&self, e_type: &stats::EntityType) -> Result<(), EpochError> { + if (self.capital.is_some() || self.no_capital) && !matches!(e_type, stats::EntityType::Town) + { + Err(EpochError::IncorrectArgumentCombinaison { + category: "Capital", + e_type: *e_type, + advice: Some( + "Capitals are reserved to town, maybe you used the wrong subcommand?" + .to_string(), + ), + }) + } else if (self.governor.is_some() || self.no_governor) + && !matches!(e_type, stats::EntityType::Town) + { + Err(EpochError::IncorrectArgumentCombinaison { + category: "Governor", + e_type: *e_type, + advice: Some( + "Governors are reserved to towns, maybe you used the wrong subcommand?" + .to_owned(), + ), + }) + } else { + Ok(()) + } + } +} + /// Handles an entity subcommand. /// /// This function loads the main epoch configuration, then dispatches the @@ -290,6 +320,7 @@ pub(crate) fn handle_create_entity( e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { + entity_args.common_args.validate(e_type)?; let epoch_info = main_epoch.try_load_current_as_mut()?; // Early extract position let position = if let Some(position) = &entity_args.common_args.position { @@ -304,7 +335,12 @@ pub(crate) fn handle_create_entity( }; // Create new (rng) entity - let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; + let mut entity = Entity::create_rng( + e_type, + &entity_args + .rng + .unwrap_or_else(|| helper_functions::default_rng_for(e_type)), + )?; // Update entity with sensible defaults helper_functions::update_stats( &entity_args.common_args.stats, @@ -322,7 +358,8 @@ pub(crate) fn handle_create_entity( // Show success let vec_entities: &mut Vec = epoch_info.vec_entities_mut(e_type); - info!("Created character: {:#?}", entity); + info!("Created {}: {:?}", entity.name, entity.id); + trace!("{entity:#?}"); let message = &crate::success::SuccessMessages::CreatedEntity( entity.name.clone(), entity.entity_type.to_shortest(), @@ -352,12 +389,10 @@ fn handle_delete_entity( let index = vec_entities .iter() .position(|entity| entity.match_identifier(&entity_identifier)) - .ok_or(EpochError::EntityNotFound( - e_type.clone(), - entity_identifier, - ))?; + .ok_or(EpochError::EntityNotFound(*e_type, entity_identifier))?; let entity = vec_entities.swap_remove(index); + // TODO: Clean all the links from it's presence // for l in entity.links(){ // // Figure out what the link is @@ -428,6 +463,7 @@ fn handle_edit_entity( e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { + entity_args.common_args.validate(e_type)?; let epoch_info = main_epoch.try_load_current_as_mut()?; let mut entity = epoch_info .find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)? diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs index a55d75d..5974a52 100644 --- a/bin_efo/src/commands/entity_generic/helper_functions.rs +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -5,11 +5,16 @@ use lib_efo::{ epoch::EpochInfo, error::EpochError, naming::NAMING, - stats::{self, EntityType, StatPair}, + stats::{self, CharacterId, EntityType, StatPair, Symbols, TypedLink}, + utils::RngLevel, }; use log::info; +use uuid::Uuid; -use crate::commands::entity_generic::{AddArgs, CommonArgs}; +use crate::{ + commands::entity_generic::{AddArgs, CommonArgs}, + success::{WarningMessages, display_warning}, +}; /// Update the given stats with the given argumenbts /// Note that this function will not change name & id due to the usage variance between caller pub(crate) fn update_stats(pair_list: &Vec, delta: stats::Modification, e: &mut Entity) { @@ -140,41 +145,119 @@ pub fn update_advanced_values( epoch_info: &mut EpochInfo, ) -> Result<(), EpochError> { if let Some(governor) = &entity_args.governor { - info!("Adding {} to {}{}", governor, entity.id, entity.name); - let governor = - epoch_info.find_entity_of_type(&Some(governor.clone()), &EntityType::Character)?; - let old_gov = entity.change_governor(stats::CharacterId(governor.id)); - let new_gov = governor.id; - // If there was a governor, tell it it's no longer the big boy in town - if let Some(gov) = old_gov { - epoch_info.del_from_links(*gov, &EntityType::Town, entity.id)?; - } - // Since I added a governor, I now need to add the link to the governor, - // note that if you add an entity to itself this will subtly break but the - // link usage being only for deletion, this breakage will not matter - // This double lookup is only done since the update is not done by the owning structure - epoch_info.add_to_links(new_gov, &EntityType::Character, entity.id)?; + let AddingDoneStruct { old_id, new_id } = add_entity(entity, epoch_info, governor)?; + remove_link_from_old(entity, epoch_info, old_id, stats::Role::Govern); + add_link_to_new(entity, epoch_info, new_id, stats::Role::Govern)?; } else if entity_args.no_governor - && let Some(g) = entity.remove_governor() + && let Some(old_gov) = entity.remove_governor() { - info!("Removing {}{} from {}", entity.id, entity.name, g); - epoch_info.del_from_links(*g, &EntityType::Character, entity.id)?; + remove_link_from_old(entity, epoch_info, Some(old_gov), stats::Role::Govern); } - if let Some(capital) = &entity_args.capital { - let capital = epoch_info.find_entity_of_type(&Some(capital.clone()), &EntityType::Town)?; - let old_cap = entity.change_capital(stats::TownId(capital.id)); - let new_cap = capital.id; - if let Some(cap) = old_cap { - epoch_info.del_from_links(*cap, &EntityType::Character, entity.id)?; - } + // if let Some(capital) = &entity_args.capital { + // let capital = epoch_info.find_entity_of_type(&Some(capital.clone()), &EntityType::Town)?; + // let old_cap = entity.change_capital(stats::TownId(capital.id)); + // let new_cap = capital.id; - epoch_info.add_to_links(new_cap, &EntityType::Town, entity.id)?; - } else if entity_args.no_capital - && let Some(c) = entity.remove_capital() - { - epoch_info.del_from_links(*c, &EntityType::Town, entity.id)?; - } - // Remove links if needed, updating two ways + // if let Some(cap) = old_cap { + // epoch_info.del_from_links(*cap, &EntityType::Character, entity.id)?; + // } + + // epoch_info.add_to_links(new_cap, &EntityType::Town, entity.id)?; + // } else if entity_args.no_capital + // && let Some(c) = entity.remove_capital() + // { + // epoch_info.del_from_links(*c, &EntityType::Town, entity.id)?; + // } + // // Remove links if needed, updating two ways Ok(()) } + +/// Structure existing only to have sane stranfer +#[allow(clippy::missing_docs_in_private_items)] +struct AddingDoneStruct { + old_id: Option, + new_id: Uuid, +} +/// Add the entity id to the entity, swapping the old one +fn add_entity( + entity: &mut Entity, + epoch_info: &mut EpochInfo, + governor: &lib_efo::entity::EntityIdentifier, +) -> Result { + let governor = + epoch_info.find_entity_of_type(&Some(governor.clone()), &EntityType::Character)?; + let new_id = governor.id; + let old_id = entity.change_governor(stats::CharacterId(new_id)); + info!( + "Adding {}{} to {}{}", + governor.name, + governor.id.to_symbol(), + entity.name, + entity.id.to_symbol(), + ); + Ok(AddingDoneStruct { old_id, new_id }) +} + +/// Safely remove a link from an old entity +fn remove_link_from_old( + entity: &mut Entity, + epoch_info: &mut EpochInfo, + old_id: Option, + role: stats::Role, +) { + if let Some(old_id) = old_id { + info!( + "Deleting {old_id} link to town Town {}{}", + entity.id, entity.name + ); + let destroy_link = TypedLink { + other_id: entity.id, + role, + other_type: entity.entity_type, + }; + + // If the data structure is corrupted, print a message and continue + let _ = epoch_info + .del_from_links(*old_id, &EntityType::Character, destroy_link) + .inspect_err(|_| { + display_warning(&WarningMessages::EntityNotFound { + id: old_id.to_symbol(), + e_type: &EntityType::Character, + }) + }); + } +} + +/// Add a link back to the new entity +fn add_link_to_new( + entity: &mut Entity, + epoch_info: &mut EpochInfo, + new_gov: Uuid, + action: stats::Role, +) -> Result<(), EpochError> { + let link_back = TypedLink { + other_id: entity.id, + role: action, + other_type: entity.entity_type, + }; + info!( + "Creating link-back {link_back} for target {}", + new_gov.to_symbol() + ); + epoch_info.add_to_links(new_gov, &EntityType::Character, link_back)?; + Ok(()) +} + +/// Give a sensible rng level according to the entity type +// TODO: Should be a method tho +pub(crate) fn default_rng_for(e_type: &stats::EntityType) -> RngLevel { + match e_type { + stats::EntityType::Character => RngLevel::Med, + stats::EntityType::Player => RngLevel::High, + stats::EntityType::Town => RngLevel::Med, + stats::EntityType::Monster => RngLevel::Legendary, + stats::EntityType::Blocker => RngLevel::Apocaliptic, + stats::EntityType::Event => RngLevel::Doom, + } +} diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 568832a..a15da1e 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -3,6 +3,7 @@ use colored::*; use derive_more::Display; use lib_efo::epoch::EpochId; +use lib_efo::stats::{EntityType, Symbols}; #[derive(Display, Clone, Debug)] #[allow(missing_docs, clippy::missing_docs_in_private_items)] @@ -40,3 +41,22 @@ pub enum SuccessMessages { pub fn display_success(message: &SuccessMessages) { println!("{}", message.to_string().cyan()) } + +#[derive(Display, Clone, Debug)] +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +pub enum WarningMessages<'a> { + /// The entity `{name}` couldn't be located – we simply skip it. + #[display("The entity {}{} wasn't found, skipping it", id, e_type.to_symbol())] + EntityNotFound { id: String, e_type: &'a EntityType }, +} + +/// Display the warning message to stdout +pub fn display_warning(message: &WarningMessages) { + eprintln!("{}", message.to_string().yellow()) +} + +/// Display the success message to stdout +#[allow(dead_code)] +pub fn display_error(message: &WarningMessages) { + eprintln!("{}", message.to_string().red()) +} diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index b96c3cb..74987e4 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -13,8 +13,8 @@ env_logger = {workspace = true} log = {workspace = true} derive_more = {workspace = true} cli-table = "0.5.0" -uuid = { version = "1.18.1", features = ["serde", "v4"] } colored = {workspace = true} +uuid = {workspace = true} rand = "0.9.2" once_cell = "1.21.3" diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index ae03914..d57cf1d 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -80,6 +80,7 @@ pub struct Entity { /// Limits that clamp any stat changes caused by the entity's effect. effect_bounds: EffectBounds, } +impl Entity {} /// Limits for the maximum and minimum value that an effect may /// modify a statistic. The bounds are applied after the effect has @@ -114,7 +115,7 @@ impl FromStr for EffectApplication { type Err = EpochError; fn from_str(s: &str) -> Result { - match s { + match s.to_ascii_lowercase().as_str() { _ if s.starts_with("re") => Ok(EffectApplication::Recurring), _ if s.starts_with("wh") => Ok(EffectApplication::WhenPresent), _ if s.contains("present") => Ok(EffectApplication::WhenPresent), diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 3cf04f7..757bfe9 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -10,6 +10,7 @@ use crate::{ }; use colored::*; use uuid::Uuid; // [3] - colored-rs examples +mod accesors; mod methods; // ---------- Implementation ---------- @@ -77,7 +78,7 @@ impl Displayable for Entity { /// Short utility to make a symbol for an entity from it's Uuid fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &stats::EntityType) -> String { epoch_info - .find_entity_strict(id, Some(e_type.clone())) + .find_entity_strict(id, Some(*e_type)) .map(|e| e.to_symbol()) .unwrap_or(format!( "{}{} is missing {}", @@ -145,7 +146,7 @@ impl Diffable for Entity { stats: self.stats.clone() - other.stats.clone(), temp_stats: self.temp_stats.delta(&other.temp_stats), metadata: self.metadata.delta(&other.metadata), - entity_type: other.entity_type.clone(), + entity_type: other.entity_type, duration: other.duration.clone(), effect_nature: other.effect_nature.clone(), effect_bounds: other.effect_bounds.clone(), diff --git a/lib_efo/src/entity/implementations/accesors.rs b/lib_efo/src/entity/implementations/accesors.rs new file mode 100644 index 0000000..c5f1ccd --- /dev/null +++ b/lib_efo/src/entity/implementations/accesors.rs @@ -0,0 +1,263 @@ +//! All field accesors for entities +use crate::{ + entity::{Entity, *}, + stats::{self, Symbols}, +}; +use log::debug; +use rand::prelude::IndexedRandom; +use rand::prelude::IteratorRandom; +use std::ops::Add; + +impl Entity { + /// Change one of the entity's statistics. + /// + /// The stat identified by `pair` is replaced with the new value specified in + /// the `StatPair`. This is a direct overwrite and does not apply any delta. + /// + /// # Arguments + /// * `pair` - The stat pair containing the key and new value. + /// + pub fn change_stat_strict(&mut self, pair: stats::StatPair, delta: stats::Modification) { + implementations::overwrite_stat(&mut self.stats, pair, delta); + } + + /// Mutate a statistic in a “fuzzy” way. + /// + /// This method behaves like `change_stat_strict` for ordinary stats, but + /// for *meta-stats* it applies a random modification instead of an + /// outright overwrite. + /// + /// # Parameters + /// * `pair` - a `StatPair` that contains the target statistic and the + /// value that should be used for the fuzzy change. + pub fn change_stat_fuzzy(&mut self, pair: stats::StatPair, delta: stats::Modification) { + let stats_demo = [ + stats::ListStats::Population, + stats::ListStats::Growthrate, + stats::ListStats::Crime, + stats::ListStats::Happiness, + ]; + let stats_eco = [ + stats::ListStats::Food, + stats::ListStats::Industry, + stats::ListStats::Science, + stats::ListStats::Trade, + ]; + let stats_soc = [ + stats::ListStats::Culture, + stats::ListStats::Education, + stats::ListStats::Tourism, + stats::ListStats::Influence, + ]; + let stats_mil = [ + stats::ListStats::Army, + stats::ListStats::Strength, + stats::ListStats::Fortification, + stats::ListStats::Threat, + ]; + let stats_inf = [ + stats::ListStats::Bureaucracy, + stats::ListStats::Transportation, + stats::ListStats::Sprawl, + stats::ListStats::Health, + ]; + + match pair.stat { + stats::ListStats::Demographics => { + self.change_random_stats_by(&stats_demo, pair.value, delta) + } + stats::ListStats::Economy => self.change_random_stats_by(&stats_eco, pair.value, delta), + stats::ListStats::Social => self.change_random_stats_by(&stats_soc, pair.value, delta), + stats::ListStats::Military => { + self.change_random_stats_by(&stats_mil, pair.value, delta) + } + stats::ListStats::Infrastructure => { + self.change_random_stats_by(&stats_inf, pair.value, delta) + } + + _ => self.change_stat_strict(pair, delta), + } + } + + /// Mutates a statistic in a “fuzzy” manner. + /// + /// For ordinary statistics this behaves like `change_stat_strict` and + /// simply assigns the supplied value. For *meta-stats* the function + /// chooses a random subset of the associated sub-statistics and + /// distributes the requested change evenly among them. The selection + /// is performed using a thread-local RNG. + pub(crate) fn change_random_stats_by( + &mut self, + stats_demo: &[stats::ListStats], + amount: stats::GenericStat, + delta: stats::Modification, + ) { + let mut r = rand::rng(); + let nb = (1..stats_demo.len() + 1).choose(&mut r).unwrap_or(1); + let stats = stats_demo.choose_multiple(&mut r, nb); + let (a, b) = (*amount / 2, *amount); + let (a, b) = (std::cmp::min(a, b), std::cmp::max(a, b)); + let mut value = || stats::GenericStat((a..b).choose(&mut r).unwrap_or(1)); + stats.for_each(|stat| { + self.change_stat_strict( + stats::StatPair { + stat: *stat, + value: value(), + }, + delta, + ); + }); + } + /// Change the entity's duration. + /// + /// This simply replaces the current `EntityDuration` with the one supplied. + /// No validation or transformation is performed; it is a direct overwrite. + /// + /// # Arguments + /// * `duration` - The new `EntityDuration` to assign to the entity. + /// + pub fn change_duration(&mut self, duration: EntityDuration) { + self.duration = duration + } + + /// Change the entity's description. + /// + /// Replaces the current description string with the new one supplied. + /// This method performs a direct overwrite; the previous description is dropped. + /// + /// # Arguments + /// * `descritption` - The new description string for the entity. + /// + pub fn change_description(&mut self, descritption: String) { + self.description = descritption + } + + /// Apply a delta to all of the entity's statistics. + /// + /// The delta specified by `pair` is added to each of the statistics in + /// `self.stats`. Positive values increase the stat, negative values + /// decrease it. + /// + /// # Arguments + /// * `pair` - The stat pair representing the change to apply. + #[deprecated] + pub fn delta_stat(&mut self, pair: stats::StatPair) { + implementations::overwrite_stat(&mut self.stats, pair, stats::Modification::Delta); + } + + /// Replace the entity's duration. + /// + /// The method simply overwrites the current `duration` field with the + /// supplied value. It is primarily intended for use when an entity + /// is instantiated from external data that already contains a duration value. + pub fn modify_duration(&mut self, duration: EntityDuration) { + self.duration = duration + } + + /// Set the way the entity's effects are applied. + /// + /// The field `effect_nature` determines how the entity's abilities or + /// status effects interact with the world. + /// This method overwrites the existing value with the supplied `EffectApplication`. + pub fn modify_effect_application(&mut self, effect: EffectApplication) { + self.effect_nature = effect + } + + /// Update the bounds that govern the entity's effects. + /// + /// `effect_bounds` controls the maximum/minimum strength, duration or + /// other limits that can be applied to the entity's effects. This + /// method simply replaces the current bounds with the supplied + /// `EffectBounds`. + pub fn modify_effect_bounds(&mut self, effect: EffectBounds) { + self.effect_bounds = effect + } + + /// Sets the entity's position using a world-space `Position`. + /// + /// This method updates the internal metadata to the specified + /// world coordinates. + pub fn modify_position(&mut self, pos: stats::Position) { + self.metadata.position = pos; + } + + /// Sets the entity's faction identifier. + /// + /// This method updates the internal metadata to reflect the provided + /// `faction`. A `None` value indicates that the entity is not + /// affiliated with any faction. + pub fn modify_faction(&mut self, faction: Option) { + self.metadata.faction = faction; + } + + /// Sets the entity's reach description. + /// + /// The `reach` string typically contains information such as the + /// distance or area the entity can affect. This method replaces + /// the current reach value stored in the entity's metadata. + pub fn modify_reach(&mut self, reach: stats::Reach) { + self.metadata.reach = reach; + } + + /// Sets the entity's position using a grid-space `PositionGrid`. + /// + /// The supplied grid coordinates are converted to world space + /// before being stored. + pub fn modify_position_grid(&mut self, pos: stats::PositionGrid) { + self.metadata.position = pos.to_position(); + } + + /// Changes the entity's description text. + pub fn modify_description(&mut self, descritption: String) { + self.description = descritption; + } + /// Sets the entity's prestige stat to an absolute value. + /// + /// The prestige value is stored directly in the entity's metadata + /// and overwrites any previous value. + pub fn modify_prestige(&mut self, prestige: stats::GenericStat, delta: stats::Modification) { + match delta { + stats::Modification::Delta => { + self.metadata.prestige = self.metadata.prestige.add(prestige) + } + stats::Modification::Replace => self.metadata.prestige = prestige, + stats::Modification::Delete => self.metadata.prestige = stats::GenericStat(0), + } + } + + /// Add a governor to the entity if the id exists and return the old governor if it existed + pub fn change_governor(&mut self, governor: stats::CharacterId) -> Option { + debug!("Swapping the governor with {}", governor.to_symbol()); + self.metadata.governor.replace(governor) + } + /// Remove the entity's governor and return it + pub fn remove_governor(&mut self) -> Option { + self.metadata.governor.take() + } + + /// Add a governor to the entity if the id exists + pub fn change_capital(&mut self, capital: stats::TownId) -> Option { + debug!("Swapping the capital with {}", capital.to_symbol()); + self.metadata.capital.replace(capital) + } + /// Remove the entity's governor and return it + pub fn remove_capital(&mut self) -> Option { + self.metadata.capital.take() + } + + /// Returns a **read-only reference** to the entity's current position. + pub fn position(&self) -> &stats::Position { + &self.metadata.position + } + + /// Returns whether the entity match an optionnal identifier + pub fn match_identifier(&self, entity_identifier: &Option) -> bool { + match entity_identifier { + Some(EntityIdentifier::Name(name)) => { + self.name.to_lowercase().starts_with(&name.to_lowercase()) + } + Some(EntityIdentifier::Id(id)) => self.id.hyphenated().to_string().starts_with(id), + None => false, + } + } +} diff --git a/lib_efo/src/entity/implementations/methods.rs b/lib_efo/src/entity/implementations/methods.rs index 682c421..eeb77a7 100644 --- a/lib_efo/src/entity/implementations/methods.rs +++ b/lib_efo/src/entity/implementations/methods.rs @@ -8,18 +8,18 @@ //! 4. **Entity creation** – deterministic or RNG‑based. //! 5. **Utility helpers** – position handling, identifier matching. -use std::ops::Add; - use cli_table::{Style, WithTitle}; use colored::*; -use rand::{ - distr::Distribution, - prelude::{IndexedRandom, IteratorRandom}, -}; +use rand::distr::Distribution; -use crate::stats::Symbols; -use crate::{entity::*, epoch::EpochInfo, error::EpochError, items_table, stats, utils::RngLevel}; -use log::debug; +use crate::{ + entity::*, + epoch::EpochInfo, + error::EpochError, + items_table, + stats::{self, Symbols}, + utils::RngLevel, +}; use uuid::Uuid; impl Entity { @@ -205,8 +205,12 @@ impl Entity { &format!( "{} {}\n", symbol, - implementations::uuid_to_symbol(link.id, epoch_info, &EntityType::Town) - .yellow() + implementations::uuid_to_symbol( + link.other_id, + epoch_info, + &link.role.infered_type_of_target() + ) + .yellow() ), )); } @@ -260,258 +264,23 @@ impl Entity { position: stats::Position::create_rng(&mut r)?, ..Default::default() }, - entity_type: e_type.clone(), + entity_type: *e_type, ..Default::default() }) } - /// Change one of the entity's statistics. - /// - /// The stat identified by `pair` is replaced with the new value specified in - /// the `StatPair`. This is a direct overwrite and does not apply any delta. - /// - /// # Arguments - /// * `pair` - The stat pair containing the key and new value. - /// - pub fn change_stat_strict(&mut self, pair: stats::StatPair, delta: stats::Modification) { - implementations::overwrite_stat(&mut self.stats, pair, delta); - } - - /// Mutate a statistic in a “fuzzy” way. - /// - /// This method behaves like `change_stat_strict` for ordinary stats, but - /// for *meta-stats* it applies a random modification instead of an - /// outright overwrite. - /// - /// # Parameters - /// * `pair` - a `StatPair` that contains the target statistic and the - /// value that should be used for the fuzzy change. - pub fn change_stat_fuzzy(&mut self, pair: stats::StatPair, delta: stats::Modification) { - let stats_demo = [ - stats::ListStats::Population, - stats::ListStats::Growthrate, - stats::ListStats::Crime, - stats::ListStats::Happiness, - ]; - let stats_eco = [ - stats::ListStats::Food, - stats::ListStats::Industry, - stats::ListStats::Science, - stats::ListStats::Trade, - ]; - let stats_soc = [ - stats::ListStats::Culture, - stats::ListStats::Education, - stats::ListStats::Tourism, - stats::ListStats::Influence, - ]; - let stats_mil = [ - stats::ListStats::Army, - stats::ListStats::Strength, - stats::ListStats::Fortification, - stats::ListStats::Threat, - ]; - let stats_inf = [ - stats::ListStats::Bureaucracy, - stats::ListStats::Transportation, - stats::ListStats::Sprawl, - stats::ListStats::Health, - ]; - - match pair.stat { - stats::ListStats::Demographics => { - self.change_random_stats_by(&stats_demo, pair.value, delta) + /// Increment the time of the entity + pub(crate) fn increment_time(&mut self) { + match self.duration { + EntityDuration::Permanent => (), + EntityDuration::Duration(d) => { + if d <= 1 { + self.duration = EntityDuration::Done; + } else { + self.duration = EntityDuration::Duration(d.saturating_sub(1)) + } } - stats::ListStats::Economy => self.change_random_stats_by(&stats_eco, pair.value, delta), - stats::ListStats::Social => self.change_random_stats_by(&stats_soc, pair.value, delta), - stats::ListStats::Military => { - self.change_random_stats_by(&stats_mil, pair.value, delta) - } - stats::ListStats::Infrastructure => { - self.change_random_stats_by(&stats_inf, pair.value, delta) - } - - _ => self.change_stat_strict(pair, delta), - } - } - - /// Mutates a statistic in a “fuzzy” manner. - /// - /// For ordinary statistics this behaves like `change_stat_strict` and - /// simply assigns the supplied value. For *meta-stats* the function - /// chooses a random subset of the associated sub-statistics and - /// distributes the requested change evenly among them. The selection - /// is performed using a thread-local RNG. - pub(crate) fn change_random_stats_by( - &mut self, - stats_demo: &[stats::ListStats], - amount: stats::GenericStat, - delta: stats::Modification, - ) { - let mut r = rand::rng(); - let nb = (1..stats_demo.len() + 1).choose(&mut r).unwrap_or(1); - let stats = stats_demo.choose_multiple(&mut r, nb); - let (a, b) = (*amount / 2, *amount); - let (a, b) = (std::cmp::min(a, b), std::cmp::max(a, b)); - let mut value = || stats::GenericStat((a..b).choose(&mut r).unwrap_or(1)); - stats.for_each(|stat| { - self.change_stat_strict( - stats::StatPair { - stat: *stat, - value: value(), - }, - delta, - ); - }); - } - /// Change the entity's duration. - /// - /// This simply replaces the current `EntityDuration` with the one supplied. - /// No validation or transformation is performed; it is a direct overwrite. - /// - /// # Arguments - /// * `duration` - The new `EntityDuration` to assign to the entity. - /// - pub fn change_duration(&mut self, duration: EntityDuration) { - self.duration = duration - } - - /// Change the entity's description. - /// - /// Replaces the current description string with the new one supplied. - /// This method performs a direct overwrite; the previous description is dropped. - /// - /// # Arguments - /// * `descritption` - The new description string for the entity. - /// - pub fn change_description(&mut self, descritption: String) { - self.description = descritption - } - - /// Apply a delta to all of the entity's statistics. - /// - /// The delta specified by `pair` is added to each of the statistics in - /// `self.stats`. Positive values increase the stat, negative values - /// decrease it. - /// - /// # Arguments - /// * `pair` - The stat pair representing the change to apply. - #[deprecated] - pub fn delta_stat(&mut self, pair: stats::StatPair) { - implementations::overwrite_stat(&mut self.stats, pair, stats::Modification::Delta); - } - - /// Replace the entity's duration. - /// - /// The method simply overwrites the current `duration` field with the - /// supplied value. It is primarily intended for use when an entity - /// is instantiated from external data that already contains a duration value. - pub fn modify_duration(&mut self, duration: EntityDuration) { - self.duration = duration - } - - /// Set the way the entity's effects are applied. - /// - /// The field `effect_nature` determines how the entity's abilities or - /// status effects interact with the world. - /// This method overwrites the existing value with the supplied `EffectApplication`. - pub fn modify_effect_application(&mut self, effect: EffectApplication) { - self.effect_nature = effect - } - - /// Update the bounds that govern the entity's effects. - /// - /// `effect_bounds` controls the maximum/minimum strength, duration or - /// other limits that can be applied to the entity's effects. This - /// method simply replaces the current bounds with the supplied - /// `EffectBounds`. - pub fn modify_effect_bounds(&mut self, effect: EffectBounds) { - self.effect_bounds = effect - } - - /// Sets the entity's position using a world-space `Position`. - /// - /// This method updates the internal metadata to the specified - /// world coordinates. - pub fn modify_position(&mut self, pos: stats::Position) { - self.metadata.position = pos; - } - - /// Sets the entity's faction identifier. - /// - /// This method updates the internal metadata to reflect the provided - /// `faction`. A `None` value indicates that the entity is not - /// affiliated with any faction. - pub fn modify_faction(&mut self, faction: Option) { - self.metadata.faction = faction; - } - - /// Sets the entity's reach description. - /// - /// The `reach` string typically contains information such as the - /// distance or area the entity can affect. This method replaces - /// the current reach value stored in the entity's metadata. - pub fn modify_reach(&mut self, reach: stats::Reach) { - self.metadata.reach = reach; - } - - /// Sets the entity's position using a grid-space `PositionGrid`. - /// - /// The supplied grid coordinates are converted to world space - /// before being stored. - pub fn modify_position_grid(&mut self, pos: stats::PositionGrid) { - self.metadata.position = pos.to_position(); - } - - /// Changes the entity's description text. - pub fn modify_description(&mut self, descritption: String) { - self.description = descritption; - } - /// Sets the entity's prestige stat to an absolute value. - /// - /// The prestige value is stored directly in the entity's metadata - /// and overwrites any previous value. - pub fn modify_prestige(&mut self, prestige: stats::GenericStat, delta: stats::Modification) { - match delta { - stats::Modification::Delta => { - self.metadata.prestige = self.metadata.prestige.add(prestige) - } - stats::Modification::Replace => self.metadata.prestige = prestige, - stats::Modification::Delete => self.metadata.prestige = stats::GenericStat(0), - } - } - - /// Add a governor to the entity if the id exists and return the old governor if it existed - pub fn change_governor(&mut self, governor: stats::CharacterId) -> Option { - debug!("Swapping the governor with {}", governor.to_symbol()); - self.metadata.governor.replace(governor) - } - /// Remove the entity's governor and return it - pub fn remove_governor(&mut self) -> Option { - self.metadata.governor.take() - } - - /// Add a governor to the entity if the id exists - pub fn change_capital(&mut self, capital: stats::TownId) -> Option { - debug!("Swapping the capital with {}", capital.to_symbol()); - self.metadata.capital.replace(capital) - } - /// Remove the entity's governor and return it - pub fn remove_capital(&mut self) -> Option { - self.metadata.capital.take() - } - - /// Returns a **read-only reference** to the entity's current position. - pub fn position(&self) -> &stats::Position { - &self.metadata.position - } - - /// Returns whether the entity match an optionnal identifier - pub fn match_identifier(&self, entity_identifier: &Option) -> bool { - match entity_identifier { - Some(EntityIdentifier::Name(name)) => self.name.starts_with(name), - Some(EntityIdentifier::Id(id)) => self.id.hyphenated().to_string().starts_with(id), - None => false, + EntityDuration::Done => (), } } } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap index 8623121..3bd3193 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -146,8 +146,9 @@ Entity { ), links: [ TypedLink { - id: 79000000-0000-0000-0000-000000000000, + other_id: 79000000-0000-0000-0000-000000000000, role: Govern, + other_type: Character, }, ], prestige: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap index 6a51e99..ebab4fb 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap @@ -16,8 +16,9 @@ MetaStats { ), links: [ TypedLink { - id: 02000000-0000-0000-0000-000000000000, + other_id: 02000000-0000-0000-0000-000000000000, role: Govern, + other_type: Character, }, ], prestige: GenericStat( diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index 8f7f9fe..cbe7588 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -242,9 +242,21 @@ fn full_entity() -> Entity { position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), links: vec![ - stats::TypedLink::new(Uuid::from_u128_le(1212), stats::Role::Govern), - stats::TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern), - stats::TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern), + stats::TypedLink::new( + Uuid::from_u128_le(1212), + stats::Role::Govern, + EntityType::Character, + ), + stats::TypedLink::new( + Uuid::from_u128_le(121), + stats::Role::Govern, + EntityType::Character, + ), + stats::TypedLink::new( + Uuid::from_u128_le(121), + stats::Role::Govern, + EntityType::Character, + ), ], reach: stats::Reach::Global, }, @@ -398,7 +410,11 @@ fn snapshot_entity_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(124))), governor: Some(stats::CharacterId(Uuid::from_u128_le(12))), faction: Some(stats::FactionId(44)), - links: vec![TypedLink::new(Uuid::from_u128_le(141), stats::Role::Govern)], + links: vec![TypedLink::new( + Uuid::from_u128_le(141), + stats::Role::Govern, + EntityType::Character, + )], prestige: stats::GenericStat(3), reach: stats::Reach::Local(12), }, @@ -419,7 +435,11 @@ fn snapshot_entity_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(121))), governor: Some(stats::CharacterId(Uuid::from_u128_le(18))), faction: Some(stats::FactionId(5)), - links: vec![TypedLink::new(Uuid::from_u128_le(121), stats::Role::Govern)], + links: vec![TypedLink::new( + Uuid::from_u128_le(121), + stats::Role::Govern, + EntityType::Character, + )], prestige: stats::GenericStat(5), reach: stats::Reach::Faction(stats::FactionId(2)), }, @@ -485,7 +505,11 @@ fn snapshot_meta_stats_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(1000))), governor: Some(stats::CharacterId(Uuid::from_u128_le(522))), faction: Some(stats::FactionId(1)), - links: vec![TypedLink::new(Uuid::from_u128_le(12), stats::Role::Govern)], + links: vec![TypedLink::new( + Uuid::from_u128_le(12), + stats::Role::Govern, + EntityType::Character, + )], prestige: stats::GenericStat(3), reach: stats::Reach::Global, }; @@ -495,7 +519,11 @@ fn snapshot_meta_stats_delta() { capital: Some(stats::TownId(Uuid::from_u128_le(12))), governor: Some(stats::CharacterId(Uuid::from_u128_le(882))), faction: Some(stats::FactionId(33)), - links: vec![TypedLink::new(Uuid::from_u128_le(42), stats::Role::Govern)], + links: vec![TypedLink::new( + Uuid::from_u128_le(42), + stats::Role::Govern, + EntityType::Character, + )], prestige: stats::GenericStat(1), reach: stats::Reach::None, }; @@ -504,7 +532,11 @@ fn snapshot_meta_stats_delta() { capital: None, governor: Some(stats::CharacterId(Uuid::from_u128_le(1221))), faction: Some(stats::FactionId(33)), - links: vec![TypedLink::new(Uuid::from_u128_le(2), stats::Role::Govern)], + links: vec![TypedLink::new( + Uuid::from_u128_le(2), + stats::Role::Govern, + EntityType::Character, + )], prestige: stats::GenericStat(1), reach: stats::Reach::Faction(stats::FactionId(12)), }; @@ -637,8 +669,9 @@ fn test_entity_lifecycle() { e.modify_faction(Some(stats::FactionId::from(42))); let link = TypedLink { - id: Uuid::from_u128_le(21), + other_id: Uuid::from_u128_le(21), role: stats::Role::Govern, + other_type: EntityType::Character, }; e.add_to_links(link); diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 69ad5ad..b5067d5 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -105,7 +105,7 @@ impl EpochConfig { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { let id = elt.file_name().to_string_lossy().parse::()?; - info!("Initialized {:?}", id); + info!("Preloaded Epoch {:?}", id); self.list_existing_epochs.insert(id, None); } } @@ -142,6 +142,7 @@ impl EpochConfig { file_name: path.to_string(), help: None, })?; + log::info!("Fully loaded Epoch {:?}", epoch_id); // Overwrite the value *value = Some(maybe_epoch); @@ -307,19 +308,33 @@ impl EpochConfig { // unimplemented!(); // Iter on events, increment time // Iter on character, increment time + // // create a new_towns_values vector, update it with base stats, then all events modifying underlying value // create_new_character_base_v vector, do the same // calculate the temps values (via function) // TODO(1): Implement this warn!("DEBUG LINE: COMPUTING NEXT EPOCH"); - // New fake epoch + // Set base for new epoch let mut new_epoch = self.try_load_current()?.clone(); + let _ = self.increment_time(&mut new_epoch); new_epoch.epoch_id = self.epoch_id.next(); new_epoch.summary = String::new(); new_epoch.tags = TagList::new(); + + // Increment time on all events Ok(new_epoch) } + /// Increment time, can only be called from inside + /// Must be called on initialized data + fn increment_time(&mut self, new_epoch: &mut EpochInfo) -> Result<(), EpochError> { + new_epoch + .iter_all_entities_mut() + .for_each(|f| f.increment_time()); + + Ok(()) + } + /// Update **all** temporary values of every entity in the current epoch. /// /// # Safety diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index 6f1d01e..b43e843 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -19,7 +19,7 @@ use crate::{ epoch_traits::{ConfigWritable, Prettiable}, }, error::EpochError, - stats::{EntityType, Position, PositionIdentifier, Role, TypedLink}, + stats::{EntityType, Position, PositionIdentifier, TypedLink}, }; /// The metadata file stored inside each epoch directory @@ -141,43 +141,28 @@ impl EpochInfo { self.vec_entities(e_type) .iter() .find(|&entity| entity.match_identifier(entity_to_find)) - .ok_or(EpochError::EntityNotFound( - e_type.clone(), - entity_to_find.clone(), - )) + .ok_or(EpochError::EntityNotFound(*e_type, entity_to_find.clone())) } /// Adds a link between two entities inside the epoch. /// /// The link is added to the entity identified by `id_to_add_to`. If the /// target entity is not found, an `EntityNotFoundById` error is returned. - /// - /// # Arguments - /// * `id_to_add_to` - The UUID of the entity that will receive the new link. - /// * `e_type` - The type of the entity that should receive the link. - /// * `id_to_add` - The UUID of the entity that should be linked. pub fn add_to_links( &mut self, - id_to_add_to: Uuid, - e_type: &EntityType, - id_to_add: Uuid, + target_id: Uuid, + target_t: &EntityType, + link_back: TypedLink, ) -> Result<(), EpochError> { + log::info!("Adding {} to {}[{:?}]", link_back, target_id, target_t); let e = self - .vec_entities_mut(e_type) + .vec_entities_mut(target_t) .iter_mut() - .find(|entity| entity.id == id_to_add_to) + .find(|entity| entity.id == target_id) .ok_or(EpochError::EntityNotFoundById(EntityIdentifier::Id( - id_to_add_to.to_string(), + target_id.to_string(), )))?; - let t_link = match e_type { - EntityType::Character => Role::Govern, - EntityType::Player => Role::Govern, - EntityType::Town => Role::Capital, - EntityType::Monster => Role::Undefined, - EntityType::Blocker => Role::Undefined, - EntityType::Event => Role::Undefined, - }; - e.add_to_links(TypedLink::new(id_to_add, t_link)); + e.add_to_links(link_back); Ok(()) } @@ -189,27 +174,19 @@ impl EpochInfo { /// `del_from_links` method, which silently ignores missing links. pub fn del_from_links( &mut self, - id_to_remove_from: Uuid, - e_type: &EntityType, - id_to_remove: Uuid, + target_id: Uuid, + target_t: &EntityType, + link_back: TypedLink, ) -> Result<(), EpochError> { let e = self - .vec_entities_mut(e_type) + .vec_entities_mut(target_t) .iter_mut() - .find(|entity| entity.id == id_to_remove_from) + .find(|entity| entity.id == target_id) .ok_or(EpochError::EntityNotFoundById(EntityIdentifier::Id( - id_to_remove_from.to_string(), + target_id.to_string(), )))?; - let t_link = match e_type { - EntityType::Character => Role::Govern, - EntityType::Player => Role::Govern, - EntityType::Town => Role::Capital, - EntityType::Monster => Role::Undefined, - EntityType::Blocker => Role::Undefined, - EntityType::Event => Role::Undefined, - }; - e.del_from_links(TypedLink::new(id_to_remove, t_link)); + e.del_from_links(link_back); Ok(()) } @@ -229,7 +206,9 @@ impl EpochInfo { /// supplied UUID exists in the epoch. pub fn find_any_entity(&self, id: EntityIdentifier) -> Result<&Entity, EpochError> { let predicate = |entity: &&Entity| match &id { - EntityIdentifier::Name(name) => entity.name.starts_with(name), + EntityIdentifier::Name(name) => { + entity.name.to_lowercase().starts_with(&name.to_lowercase()) + } EntityIdentifier::Id(id) => entity.id.to_string().starts_with(id), }; self.events @@ -253,7 +232,7 @@ impl EpochInfo { .iter() .find(|entity| entity.id == id) .ok_or(EpochError::EntityNotFound( - e_type.clone(), + e_type, Some(EntityIdentifier::Id(id.to_string())), )) } else { @@ -265,7 +244,7 @@ impl EpochInfo { .or(self.blockers.iter().find(predicate)) .or(self.calamities.iter().find(predicate)) .ok_or(EpochError::EntityNotFound( - EntityType::Player.clone(), + EntityType::Player, Some(EntityIdentifier::Id(id.to_string())), )) } @@ -275,13 +254,6 @@ impl EpochInfo { /// The function matches the supplied `e_type` to the appropriate collection /// inside `epoch_info`. For unimplemented entity types the call will panic /// because of the `todo!()` placeholder. - /// - /// # Arguments - /// * `epoch_info` - The epoch information containing the collections. - /// - /// # Returns - /// A reference to the vector containing the requested entities. - /// The lifetime of the returned slice is tied to that of `epoch_info`. pub fn vec_entities(&self, e_type: &EntityType) -> &Vec { match e_type { EntityType::Character => &self.characters, @@ -309,7 +281,7 @@ impl EpochInfo { .iter() .position(|entity| entity.match_identifier(entity_identifier)) .ok_or(EpochError::EntityNotFound( - e_type.clone(), + *e_type, entity_identifier.clone(), ))?; @@ -321,14 +293,6 @@ impl EpochInfo { /// /// Like `vec_entities`, this function selects the appropriate collection /// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. - /// - /// # Arguments - /// * `e_type` - The type of entities to retrieve. - /// * `epoch_info` - The epoch information containing the collections. - /// - /// # Returns - /// A mutable reference to the vector containing the requested entities. - /// The lifetime of the returned slice is tied to that of `epoch_info`. pub fn vec_entities_mut(&mut self, e_type: &EntityType) -> &mut Vec { match e_type { EntityType::Character => &mut self.characters, @@ -340,6 +304,17 @@ impl EpochInfo { } } + /// Returns an iterator over mutable references to **all** entities that are currently + /// stored in the `EpochInfo` container. + pub fn iter_all_entities_mut(&mut self) -> impl Iterator { + self.events + .iter_mut() + .chain(self.characters.iter_mut()) + .chain(self.towns.iter_mut()) + .chain(self.calamities.iter_mut()) + .chain(self.blockers.iter_mut()) + } + /// Get the position of an entity either directly or cloning one from an epoch pub fn resolve_position(&self, position: &PositionIdentifier) -> Result { Ok(match position { @@ -365,7 +340,7 @@ impl EpochInfo { Ok(std::mem::replace(&mut entities[idx], entity)) } None => Err(EpochError::EntityNotFound( - entity.entity_type.clone(), + entity.entity_type, Some(EntityIdentifier::Id(entity.id.to_string())), )), } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 1f24a79..089534d 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -15,7 +15,11 @@ use uuid::Uuid; use thiserror::Error; -use crate::{entity::EntityIdentifier, epoch::EpochId, stats::EntityType}; +use crate::{ + entity::EntityIdentifier, + epoch::EpochId, + stats::{EntityType, Symbols}, +}; use miette::Diagnostic; /// Errors that can be returned by the storage layer. @@ -339,6 +343,24 @@ pub enum EpochError { /// The thing that was being parsed while_parsing: &'static str, }, + /// Indicates that the user supplied **mutually‑exclusive** arguments. + /// + /// The command line parser accepts a number of optional arguments that belong to + /// *argument groups* – e.g. `--force`, `--dry-run`, `--verbose`, etc. + /// Some of these groups are **incompatible** with each other. If the user + /// specifies an argument from one group together with an argument from a + /// conflicting group, this error is returned. + #[error("Can't use any {category} related argument on {}", e_type.to_symbol())] + #[diagnostic(code(EntityError::IncorrectArgumentCombinaison))] + IncorrectArgumentCombinaison { + /// The argument category that was involved in the conflict + category: &'static str, + /// The entity type for which the conflict was detected. + e_type: EntityType, + /// Optional, user‑friendly guidance on how to fix the issue. + #[help] + advice: Option, + }, } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 6d46625..52cb12c 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -558,7 +558,7 @@ pub enum ListStats { /// The list of all types of entities #[allow(missing_docs)] -#[derive(Serialize, Deserialize, Debug, Clone, Default)] +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum EntityType { Character, Player, @@ -598,24 +598,33 @@ thin_newtype!(FactionId, usize, derives: [Add, Sub]); /// (`id`) to a *semantic role* (`role`). The role is expressed by the /// [`Role`] enum and defines what the link actually means in the /// domain model. -#[display("{id}:{role}")] +#[display("{}{}({}{})",role, role.to_symbol(),other_id.to_symbol(), other_type.to_symbol())] pub struct TypedLink { /// The UUID of the entity that is linked. /// /// The link is *unidirectional*; the `TypedLink` itself does not /// keep a back-reference to the source entity. - pub id: Uuid, + pub other_id: Uuid, /// The semantic role that this link plays. /// /// For example, a link with `Role::Capital` indicates that the entity /// identified by `id` is the capital of the entity that owns the link. pub role: Role, + /// The Type of the entity linked + /// + /// Even if it can mostly be inferred, some edge cases can be squashed + /// early in exchange of some data storred + pub other_type: EntityType, } impl TypedLink { /// Simple initializer for the TypedLink type - pub fn new(id: Uuid, role: Role) -> Self { - Self { id, role } + pub fn new(other_id: Uuid, role: Role, other_type: EntityType) -> Self { + Self { + other_id, + role, + other_type, + } } } diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index bee181f..b6fb6ba 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -1,15 +1,9 @@ //! All traits implementatition for the main structs are deffered here #![allow(dead_code)] -use crate::stats::{CharacterId, GameStat, TownId}; -use colored::Colorize; -use std::str::FromStr; - -use crate::entity::{EffectApplication, EffectBounds, EntityDuration}; -use crate::error::EpochError; -use crate::stats::{ - EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols, -}; +use crate::stats::{self, EntityType, GameStat, GenericStat, ListStats, OverallStats, Role}; +mod from_impl; +mod symb_impl; /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. @@ -92,74 +86,6 @@ field_accessor!(OverallStats { health }); -impl FromStr for ListStats { - type Err = EpochError; - - /// Convert an acronym (e.g. `"cri"`) into the corresponding enum variant. - fn from_str(s: &str) -> Result { - match s.to_ascii_lowercase().as_str() { - "dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics), - "pop" | "popul" | "populations" => Ok(ListStats::Population), - "grow" | "grw" | "growth" => Ok(ListStats::Growthrate), - "cri" | "crim" | "crimes" => Ok(ListStats::Crime), - "hapn" | "happines" | "hap" => Ok(ListStats::Happiness), - "eco" | "economy" | "econ" => Ok(ListStats::Economy), - "food" | "fo" | "agr" | "agri" | "fod" => Ok(ListStats::Food), - "industry" | "indus" | "ind" => Ok(ListStats::Industry), - "science" | "sci" | "sc" => Ok(ListStats::Science), - "trade" | "trd" | "tr" => Ok(ListStats::Trade), - "social" | "soc" | "sl" => Ok(ListStats::Social), - "culture" | "cul" | "cl" => Ok(ListStats::Culture), - "education" | "edu" | "ed" => Ok(ListStats::Education), - "tourism" | "tour" | "tm" => Ok(ListStats::Tourism), - "influence" | "infl" | "influ" => Ok(ListStats::Influence), - "military" | "mil" | "mt" => Ok(ListStats::Military), - "army" | "arm" | "ar" => Ok(ListStats::Army), - "strength" | "str" | "st" => Ok(ListStats::Strength), - "fortification" | "fort" | "ft" => Ok(ListStats::Fortification), - "threat" | "thr" | "th" => Ok(ListStats::Threat), - "ifr" | "inf" | "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure), - "bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy), - "transportation" | "trans" | "trns" => Ok(ListStats::Transportation), - "sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl), - "health" | "hlth" | "hlt" => Ok(ListStats::Health), - _ => Err(EpochError::UnknownStatAcronim(s.to_owned())), - } - } -} - -impl From for &str { - fn from(value: ListStats) -> Self { - match value { - ListStats::Demographics => "demographics", - ListStats::Population => "population", - ListStats::Growthrate => "growthrate", - ListStats::Crime => "crime", - ListStats::Happiness => "happiness", - ListStats::Economy => "economy", - ListStats::Food => "food", - ListStats::Industry => "industry", - ListStats::Science => "science", - ListStats::Trade => "trade", - ListStats::Social => "social", - ListStats::Culture => "culture", - ListStats::Education => "education", - ListStats::Tourism => "tourism", - ListStats::Influence => "influence", - ListStats::Military => "military", - ListStats::Army => "army", - ListStats::Strength => "strength", - ListStats::Fortification => "fortification", - ListStats::Threat => "threat", - ListStats::Infrastructure => "infrastructure", - ListStats::Bureaucracy => "bureaucracy", - ListStats::Transportation => "transportation", - ListStats::Sprawl => "sprawl", - ListStats::Health => "health", - } - } -} - impl OverallStats { /// Retrieve a reference to a statistic field by its `ListStats` key. /// @@ -250,191 +176,6 @@ impl OverallStats { } } -impl Symbols for EntityType { - fn to_shortest(&self) -> String { - match self { - EntityType::Character => "[C]".to_string(), - EntityType::Player => "[P]".to_string(), - EntityType::Town => "[T]".to_string(), - EntityType::Monster => "[M]".to_string(), - EntityType::Blocker => "[B]".to_string(), - EntityType::Event => "[E]".to_string(), - } - } - fn to_symbol(&self) -> String { - match self { - EntityType::Character => "".to_string(), - EntityType::Player => " ".to_string(), - EntityType::Town => "󱡵 ".to_string(), - EntityType::Monster => " ".to_string(), - EntityType::Blocker => " ".to_string(), - EntityType::Event => "".to_string(), - } - } -} - -impl Symbols for EffectApplication { - fn to_symbol(&self) -> String { - match self { - EffectApplication::Recurring => "⟳".to_string(), - EffectApplication::WhenPresent => "⥯".to_string(), - EffectApplication::PermanentEffectToApply => "☈".to_string(), - EffectApplication::PermanentEffectApplied => "✓".to_string(), - } - } -} - -impl Symbols for Position { - fn to_symbol(&self) -> String { - format!("({:4},{:4})⚓", self.0, self.1) - } - fn to_shortest(&self) -> String { - format!("{},{}", self.0, self.1) - } -} - -impl Symbols for EntityDuration { - fn to_symbol(&self) -> String { - match self { - EntityDuration::Permanent => "∞".to_string(), - EntityDuration::Duration(t) => format!("⧗{}", t), - EntityDuration::Done => "✔".to_string(), - } - } -} - -impl Symbols for EffectBounds { - fn to_symbol(&self) -> String { - format!("({} ⭾ {})", self.min, self.max) - } -} - -impl Symbols for OverallStats { - fn to_symbol(&self) -> String { - format!( - "{:2}{} {:2}{} {:2}{} {:2}{}", - self.demographics, - " ".green(), - self.economy, - "💰".yellow(), - self.military, - " ".red(), - self.infrastructure, - "󰡢".cyan(), - ) - } -} - -impl Symbols for ListStats { - fn to_shortest(&self) -> String { - match self { - ListStats::Demographics => "Dem".blue(), - ListStats::Population => "Pop".green(), - ListStats::Growthrate => "Gro".green(), - ListStats::Crime => "Cri".green(), - ListStats::Happiness => "Hap".green(), - ListStats::Economy => "Eco".blue(), - ListStats::Food => "Foo".yellow(), - ListStats::Industry => "Ind".yellow(), - ListStats::Science => "Sci".yellow(), - ListStats::Trade => "Tra".yellow(), - ListStats::Social => "Soc".blue(), - ListStats::Culture => "Cul".purple(), - ListStats::Education => "Edu".purple(), - ListStats::Tourism => "Tou".purple(), - ListStats::Influence => "Inf".purple(), - ListStats::Military => "Mil".blue(), - ListStats::Army => "Arm".red(), - ListStats::Strength => "Str".red(), - ListStats::Fortification => "For".red(), - ListStats::Threat => "Thr".red(), - ListStats::Infrastructure => "Inf".blue(), - ListStats::Bureaucracy => "Bur".cyan(), - ListStats::Transportation => "Tra".cyan(), - ListStats::Sprawl => "Spr".cyan(), - ListStats::Health => "Hea".cyan(), - } - .to_string() - } - fn to_symbol(&self) -> String { - match self { - ListStats::Demographics => " ".blue(), - ListStats::Population => " ".green(), - ListStats::Growthrate => " ".green(), - ListStats::Crime => "󱀣".green(), - ListStats::Happiness => " ".green(), - ListStats::Economy => "💰".blue(), - ListStats::Food => "󰔬".yellow(), - ListStats::Industry => "🏭".yellow(), - ListStats::Science => "󰧑 ".yellow(), - ListStats::Trade => " ".yellow(), - ListStats::Social => "󱕹 ".blue(), - ListStats::Culture => "🎭".purple(), - ListStats::Education => "📚".purple(), - ListStats::Tourism => "🏖️".purple(), - ListStats::Influence => "🌍".purple(), - ListStats::Military => "🪖".blue(), - ListStats::Army => " ".red(), - ListStats::Strength => "󰞇 ".red(), - ListStats::Fortification => "🔒".red(), - ListStats::Threat => "⚡".red(), - ListStats::Infrastructure => "🏗️ ".blue(), - ListStats::Bureaucracy => "🏛️ ".cyan(), - ListStats::Transportation => "󰔬 ".cyan(), - ListStats::Sprawl => "🏙️".cyan(), - ListStats::Health => "".cyan(), - } - .to_string() - } -} - -impl Symbols for Option { - fn to_symbol(&self) -> String { - if let Some(faction) = self { - format!("{faction}") - } else { - "Ø".to_string() - } - } -} - -impl Symbols for TownId { - fn to_symbol(&self) -> String { - self.0.to_symbol() - } - - fn to_shortest(&self) -> String { - self.0.to_shortest() - } -} - -impl Symbols for CharacterId { - fn to_symbol(&self) -> String { - self.0.to_symbol() - } - - fn to_shortest(&self) -> String { - self.0.to_shortest() - } -} - -impl FromStr for FactionId { - type Err = EpochError; // the error we get from `usize::parse` - - /// Parse a string slice into a `FactionId`. - fn from_str(s: &str) -> Result { - // Trim whitespace just in case and attempt to parse. - let inner = s - .trim() - .parse::() - .map_err(|_| EpochError::ParsingArgument { - argument_parsed: s.to_string(), - while_parsing: "FactionId", - })?; - Ok(FactionId(inner)) - } -} - /// Thin wrapper that derefs to the inner type. /// /// By default the wrapper derives a common set of traits (`Debug`, `Clone`, `Copy`, @@ -552,7 +293,25 @@ macro_rules! thin_newtype { } }; } -mod from_impl; + +impl Role { + /// The role inferred of the entity targeted by the role + pub fn infered_type_of_target(&self) -> stats::EntityType { + match self { + Role::Govern => EntityType::Town, + Role::Capital => EntityType::Character, + Role::Undefined => EntityType::Event, + } + } + /// The role inferred of the entity since it has this role + pub fn infered_type_of_self(&self) -> stats::EntityType { + match self { + Role::Govern => EntityType::Character, + Role::Capital => EntityType::Town, + Role::Undefined => EntityType::Event, + } + } +} #[cfg(test)] pub(crate) mod test; diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs index 0bd74b1..ccff46a 100644 --- a/lib_efo/src/stats/implementations/from_impl.rs +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -1,5 +1,6 @@ //! All from implementations +use crate::stats::FactionId; use crate::{ error::EpochError, stats::{self, GenericStat, ListStats, Position, PositionGrid, PositionIdentifier, StatPair}, @@ -238,3 +239,88 @@ impl From for stats::Modification { } } } + +impl FromStr for FactionId { + type Err = EpochError; // the error we get from `usize::parse` + + /// Parse a string slice into a `FactionId`. + fn from_str(s: &str) -> Result { + // Trim whitespace just in case and attempt to parse. + let inner = s + .trim() + .parse::() + .map_err(|_| EpochError::ParsingArgument { + argument_parsed: s.to_string(), + while_parsing: "FactionId", + })?; + Ok(FactionId(inner)) + } +} + +impl FromStr for ListStats { + type Err = EpochError; + + /// Convert an acronym (e.g. `"cri"`) into the corresponding enum variant. + fn from_str(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics), + "pop" | "popul" | "populations" => Ok(ListStats::Population), + "grow" | "grw" | "growth" => Ok(ListStats::Growthrate), + "cri" | "crim" | "crimes" => Ok(ListStats::Crime), + "hapn" | "happines" | "hap" => Ok(ListStats::Happiness), + "eco" | "economy" | "econ" => Ok(ListStats::Economy), + "food" | "fo" | "agr" | "agri" | "fod" => Ok(ListStats::Food), + "industry" | "indus" | "ind" => Ok(ListStats::Industry), + "science" | "sci" | "sc" => Ok(ListStats::Science), + "trade" | "trd" | "tr" => Ok(ListStats::Trade), + "social" | "soc" | "sl" => Ok(ListStats::Social), + "culture" | "cul" | "cl" => Ok(ListStats::Culture), + "education" | "edu" | "ed" => Ok(ListStats::Education), + "tourism" | "tour" | "tm" => Ok(ListStats::Tourism), + "influence" | "infl" | "influ" => Ok(ListStats::Influence), + "military" | "mil" | "mt" => Ok(ListStats::Military), + "army" | "arm" | "ar" => Ok(ListStats::Army), + "strength" | "str" | "st" => Ok(ListStats::Strength), + "fortification" | "fort" | "ft" => Ok(ListStats::Fortification), + "threat" | "thr" | "th" => Ok(ListStats::Threat), + "ifr" | "inf" | "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure), + "bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy), + "transportation" | "trans" | "trns" => Ok(ListStats::Transportation), + "sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl), + "health" | "hlth" | "hlt" => Ok(ListStats::Health), + _ => Err(EpochError::UnknownStatAcronim(s.to_owned())), + } + } +} + +impl From for &str { + fn from(value: ListStats) -> Self { + match value { + ListStats::Demographics => "demographics", + ListStats::Population => "population", + ListStats::Growthrate => "growthrate", + ListStats::Crime => "crime", + ListStats::Happiness => "happiness", + ListStats::Economy => "economy", + ListStats::Food => "food", + ListStats::Industry => "industry", + ListStats::Science => "science", + ListStats::Trade => "trade", + ListStats::Social => "social", + ListStats::Culture => "culture", + ListStats::Education => "education", + ListStats::Tourism => "tourism", + ListStats::Influence => "influence", + ListStats::Military => "military", + ListStats::Army => "army", + ListStats::Strength => "strength", + ListStats::Fortification => "fortification", + ListStats::Threat => "threat", + ListStats::Infrastructure => "infrastructure", + ListStats::Bureaucracy => "bureaucracy", + ListStats::Transportation => "transportation", + ListStats::Sprawl => "sprawl", + ListStats::Health => "health", + } + } +} diff --git a/lib_efo/src/stats/implementations/symb_impl.rs b/lib_efo/src/stats/implementations/symb_impl.rs new file mode 100644 index 0000000..5aa080b --- /dev/null +++ b/lib_efo/src/stats/implementations/symb_impl.rs @@ -0,0 +1,188 @@ +//! All symbol implementations +//! +use crate::{ + entity::{EffectApplication, EffectBounds, EntityDuration}, + stats::{ + CharacterId, EntityType, FactionId, ListStats, OverallStats, Position, Role, Symbols, + TownId, + }, +}; +use colored::Colorize; + +impl Symbols for Role { + fn to_symbol(&self) -> String { + match self { + Role::Govern => " ".to_string(), + Role::Capital => " ".to_string(), + Role::Undefined => "󱣩".to_string(), + } + } +} + +impl Symbols for EntityType { + fn to_shortest(&self) -> String { + match self { + EntityType::Character => "[C]".to_string(), + EntityType::Player => "[P]".to_string(), + EntityType::Town => "[T]".to_string(), + EntityType::Monster => "[M]".to_string(), + EntityType::Blocker => "[B]".to_string(), + EntityType::Event => "[E]".to_string(), + } + } + fn to_symbol(&self) -> String { + match self { + EntityType::Character => "".to_string(), + EntityType::Player => " ".to_string(), + EntityType::Town => "󱡵 ".to_string(), + EntityType::Monster => " ".to_string(), + EntityType::Blocker => " ".to_string(), + EntityType::Event => "".to_string(), + } + } +} + +impl Symbols for EffectApplication { + fn to_symbol(&self) -> String { + match self { + EffectApplication::Recurring => "⟳".to_string(), + EffectApplication::WhenPresent => "⥯".to_string(), + EffectApplication::PermanentEffectToApply => "☈".to_string(), + EffectApplication::PermanentEffectApplied => "✓".to_string(), + } + } +} + +impl Symbols for Position { + fn to_symbol(&self) -> String { + format!("({:4},{:4})⚓", self.0, self.1) + } + fn to_shortest(&self) -> String { + format!("{},{}", self.0, self.1) + } +} + +impl Symbols for EntityDuration { + fn to_symbol(&self) -> String { + match self { + EntityDuration::Permanent => "∞".to_string(), + EntityDuration::Duration(t) => format!("⧗{}", t), + EntityDuration::Done => "✔".to_string(), + } + } +} + +impl Symbols for EffectBounds { + fn to_symbol(&self) -> String { + format!("({} ⭾ {})", self.min, self.max) + } +} + +impl Symbols for OverallStats { + fn to_symbol(&self) -> String { + format!( + "{:2}{} {:2}{} {:2}{} {:2}{}", + self.demographics, + " ".green(), + self.economy, + "💰".yellow(), + self.military, + " ".red(), + self.infrastructure, + "󰡢".cyan(), + ) + } +} + +impl Symbols for ListStats { + fn to_shortest(&self) -> String { + match self { + ListStats::Demographics => "Dem".blue(), + ListStats::Population => "Pop".green(), + ListStats::Growthrate => "Gro".green(), + ListStats::Crime => "Cri".green(), + ListStats::Happiness => "Hap".green(), + ListStats::Economy => "Eco".blue(), + ListStats::Food => "Foo".yellow(), + ListStats::Industry => "Ind".yellow(), + ListStats::Science => "Sci".yellow(), + ListStats::Trade => "Tra".yellow(), + ListStats::Social => "Soc".blue(), + ListStats::Culture => "Cul".purple(), + ListStats::Education => "Edu".purple(), + ListStats::Tourism => "Tou".purple(), + ListStats::Influence => "Inf".purple(), + ListStats::Military => "Mil".blue(), + ListStats::Army => "Arm".red(), + ListStats::Strength => "Str".red(), + ListStats::Fortification => "For".red(), + ListStats::Threat => "Thr".red(), + ListStats::Infrastructure => "Inf".blue(), + ListStats::Bureaucracy => "Bur".cyan(), + ListStats::Transportation => "Tra".cyan(), + ListStats::Sprawl => "Spr".cyan(), + ListStats::Health => "Hea".cyan(), + } + .to_string() + } + fn to_symbol(&self) -> String { + match self { + ListStats::Demographics => " ".blue(), + ListStats::Population => " ".green(), + ListStats::Growthrate => " ".green(), + ListStats::Crime => "󱀣".green(), + ListStats::Happiness => " ".green(), + ListStats::Economy => "💰".blue(), + ListStats::Food => "󰔬".yellow(), + ListStats::Industry => "🏭".yellow(), + ListStats::Science => "󰧑 ".yellow(), + ListStats::Trade => " ".yellow(), + ListStats::Social => "󱕹 ".blue(), + ListStats::Culture => "🎭".purple(), + ListStats::Education => "📚".purple(), + ListStats::Tourism => "🏖️".purple(), + ListStats::Influence => "🌍".purple(), + ListStats::Military => "🪖".blue(), + ListStats::Army => " ".red(), + ListStats::Strength => "󰞇 ".red(), + ListStats::Fortification => "🔒".red(), + ListStats::Threat => "⚡".red(), + ListStats::Infrastructure => "🏗️ ".blue(), + ListStats::Bureaucracy => "🏛️ ".cyan(), + ListStats::Transportation => "󰔬 ".cyan(), + ListStats::Sprawl => "🏙️".cyan(), + ListStats::Health => "".cyan(), + } + .to_string() + } +} + +impl Symbols for Option { + fn to_symbol(&self) -> String { + if let Some(faction) = self { + format!("{faction}") + } else { + "Ø".to_string() + } + } +} + +impl Symbols for TownId { + fn to_symbol(&self) -> String { + self.0.to_symbol() + } + + fn to_shortest(&self) -> String { + self.0.to_shortest() + } +} + +impl Symbols for CharacterId { + fn to_symbol(&self) -> String { + self.0.to_symbol() + } + + fn to_shortest(&self) -> String { + self.0.to_shortest() + } +} diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 34fd434..087c44b 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -1,18 +1,22 @@ #![allow(clippy::unwrap_used)] + +use crate::entity; +use crate::entity::EntityDuration; +use crate::error::EpochError; +use crate::stats::GameStat; +use crate::stats::Symbols; use insta::assert_debug_snapshot; use insta::assert_snapshot; -use super::*; -use crate::stats; -use crate::stats::GameStat; -use crate::stats::GenericStat; -use crate::stats::StatPair; +// use super::*; use std::str::FromStr; +use crate::stats; + struct Person { - name: GenericStat, - age: GenericStat, - email: GenericStat, + name: stats::GenericStat, + age: stats::GenericStat, + email: stats::GenericStat, } // /// Helper that asserts that a string parses to the expected ListStats variant. @@ -20,15 +24,14 @@ struct Person { // let parsed = ListStats::from_str(input).expect("should parse"); // assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); // } - field_accessor!(Person { name, age, email }); #[test] fn test_field_accessors() { let mut person = Person { - name: GenericStat(10), - age: GenericStat(20), - email: GenericStat(120), + name: stats::GenericStat(10), + age: stats::GenericStat(20), + email: stats::GenericStat(120), }; let age = person.get_field_mut_from_str("age").unwrap(); @@ -43,72 +46,72 @@ fn test_field_accessors() { #[test] fn test_clap_serialisation() {} /// Helper that asserts that a stat pair string parses to the expected `StatPair`. -fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { - let pair = StatPair::from_str(input).expect("should parse"); +fn assert_pair_ok(input: &str, expected_stat: stats::ListStats, expected_val: isize) { + let pair = stats::StatPair::from_str(input).expect("should parse"); assert_eq!(pair.stat, expected_stat, "stat mismatch"); assert_eq!(pair.value.0, expected_val, "value mismatch"); } #[test] fn test_stat_pair_parsing() { // Colon syntax - assert_pair_ok("cri:10", ListStats::Crime, 10); - assert_pair_ok("POP:-5", ListStats::Population, -5); - assert_pair_ok("growth:0", ListStats::Growthrate, 0); + assert_pair_ok("cri:10", stats::ListStats::Crime, 10); + assert_pair_ok("POP:-5", stats::ListStats::Population, -5); + assert_pair_ok("growth:0", stats::ListStats::Growthrate, 0); // Space syntax (clap concatenates two separate args into one string) - assert_pair_ok("cri 10", ListStats::Crime, 10); - assert_pair_ok("Pop -5", ListStats::Population, -5); - assert_pair_ok("grow 0", ListStats::Growthrate, 0); + assert_pair_ok("cri 10", stats::ListStats::Crime, 10); + assert_pair_ok("Pop -5", stats::ListStats::Population, -5); + assert_pair_ok("grow 0", stats::ListStats::Growthrate, 0); } #[test] fn stat_pair_ill_formed_errors_are_detected() { // 1️⃣ No separator at all - let err = StatPair::from_str("justastring").unwrap_err(); + let err = stats::StatPair::from_str("justastring").unwrap_err(); assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); // 2️⃣ Separator but missing the value - let err = StatPair::from_str("cri:").unwrap_err(); + let err = stats::StatPair::from_str("cri:").unwrap_err(); assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); // 3️⃣ Separator but missing the stat name - let err = StatPair::from_str(":10").unwrap_err(); + let err = stats::StatPair::from_str(":10").unwrap_err(); assert!(matches!(err, EpochError::UnknownStatAcronim(_))); // 4️⃣ Two spaces (splits into > 2 parts) - let err = StatPair::from_str("cri 10 20").unwrap_err(); + let err = stats::StatPair::from_str("cri 10 20").unwrap_err(); assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); // 5️⃣ Value part is not an integer - let err = StatPair::from_str("cri:abc").unwrap_err(); + let err = stats::StatPair::from_str("cri:abc").unwrap_err(); assert!(matches!(err, EpochError::IllFormedStatQualifier(_))); // 6️⃣ Unknown stat - this is caught by the `ListStats::parse()` call, // which already returns `IllFormedStatQualifier` - let err = StatPair::from_str("unknown:5").unwrap_err(); + let err = stats::StatPair::from_str("unknown:5").unwrap_err(); assert!(matches!(err, EpochError::UnknownStatAcronim(_))); } #[test] fn position_invalid_format_errors_are_detected() { // 1️⃣ No comma - let err = Position::from_str("123 456").unwrap_err(); + let err = stats::Position::from_str("123 456").unwrap_err(); assert!(matches!(err, EpochError::InvalidPositionFormat(_))); // 2️⃣ Too many commas - let err = Position::from_str("1,2,3").unwrap_err(); + let err = stats::Position::from_str("1,2,3").unwrap_err(); assert!(matches!(err, EpochError::InvalidPositionFormat(_))); // 3️⃣ Leading/trailing comma - let err = Position::from_str(",5").unwrap_err(); + let err = stats::Position::from_str(",5").unwrap_err(); assert!(matches!(err, EpochError::ParsePositionError(_))); - let err = Position::from_str("5,").unwrap_err(); + let err = stats::Position::from_str("5,").unwrap_err(); assert!(matches!(err, EpochError::ParsePositionError(_))); // 4️⃣ Non-integer components - let err = Position::from_str("x,5").unwrap_err(); + let err = stats::Position::from_str("x,5").unwrap_err(); assert!(matches!(err, EpochError::ParsePositionError(_))); - let err = Position::from_str("5,y").unwrap_err(); + let err = stats::Position::from_str("5,y").unwrap_err(); assert!(matches!(err, EpochError::ParsePositionError(_))); } #[test] @@ -116,113 +119,113 @@ fn test_liststats_aliases() { // Each tuple: (alias, expected enum variant) let cases = vec![ // Demographics - ("dem", ListStats::Demographics), - ("DEMOg", ListStats::Demographics), - ("demoGRAphicS", ListStats::Demographics), - ("demo", ListStats::Demographics), + ("dem", stats::ListStats::Demographics), + ("DEMOg", stats::ListStats::Demographics), + ("demoGRAphicS", stats::ListStats::Demographics), + ("demo", stats::ListStats::Demographics), // Population - ("Pop", ListStats::Population), - ("POPUl", ListStats::Population), - ("populations", ListStats::Population), + ("Pop", stats::ListStats::Population), + ("POPUl", stats::ListStats::Population), + ("populations", stats::ListStats::Population), // Growth rate - ("grow", ListStats::Growthrate), - ("grW", ListStats::Growthrate), - ("Growth", ListStats::Growthrate), + ("grow", stats::ListStats::Growthrate), + ("grW", stats::ListStats::Growthrate), + ("Growth", stats::ListStats::Growthrate), // Crime - ("CRI", ListStats::Crime), - ("crim", ListStats::Crime), - ("Crimes", ListStats::Crime), + ("CRI", stats::ListStats::Crime), + ("crim", stats::ListStats::Crime), + ("Crimes", stats::ListStats::Crime), // Happiness - ("hapN", ListStats::Happiness), - ("HAPPiNeS", ListStats::Happiness), - ("hap", ListStats::Happiness), + ("hapN", stats::ListStats::Happiness), + ("HAPPiNeS", stats::ListStats::Happiness), + ("hap", stats::ListStats::Happiness), // Economy - ("eco", ListStats::Economy), - ("EconomY", ListStats::Economy), - ("econ", ListStats::Economy), + ("eco", stats::ListStats::Economy), + ("EconomY", stats::ListStats::Economy), + ("econ", stats::ListStats::Economy), // Food - ("Food", ListStats::Food), - ("fo", ListStats::Food), - ("agr", ListStats::Food), - ("Agri", ListStats::Food), - ("Fod", ListStats::Food), + ("Food", stats::ListStats::Food), + ("fo", stats::ListStats::Food), + ("agr", stats::ListStats::Food), + ("Agri", stats::ListStats::Food), + ("Fod", stats::ListStats::Food), // Industry - ("industry", ListStats::Industry), - ("IndUs", ListStats::Industry), - ("ind", ListStats::Industry), + ("industry", stats::ListStats::Industry), + ("IndUs", stats::ListStats::Industry), + ("ind", stats::ListStats::Industry), // Science - ("science", ListStats::Science), - ("SCI", ListStats::Science), - ("Sc", ListStats::Science), + ("science", stats::ListStats::Science), + ("SCI", stats::ListStats::Science), + ("Sc", stats::ListStats::Science), // Trade - ("trade", ListStats::Trade), - ("TrD", ListStats::Trade), - ("tr", ListStats::Trade), + ("trade", stats::ListStats::Trade), + ("TrD", stats::ListStats::Trade), + ("tr", stats::ListStats::Trade), // // Social - // ("social", ListStats::Social), - // ("soc", ListStats::Social), - // ("sl", ListStats::Social), + // ("social", stats::ListStats::Social), + // ("soc", stats::ListStats::Social), + // ("sl", stats::ListStats::Social), // // Culture - // ("culture", ListStats::Culture), - // ("CUL", ListStats::Culture), - // ("cl", ListStats::Culture), + // ("culture", stats::ListStats::Culture), + // ("CUL", stats::ListStats::Culture), + // ("cl", stats::ListStats::Culture), // // Education - // ("education", ListStats::Education), - // ("edu", ListStats::Education), - // ("ed", ListStats::Education), + // ("education", stats::ListStats::Education), + // ("edu", stats::ListStats::Education), + // ("ed", stats::ListStats::Education), // // Tourism - // ("tourism", ListStats::Tourism), - // ("tour", ListStats::Tourism), - // ("tm", ListStats::Tourism), + // ("tourism", stats::ListStats::Tourism), + // ("tour", stats::ListStats::Tourism), + // ("tm", stats::ListStats::Tourism), // // Influence - // ("influence", ListStats::Influence), - // ("infl", ListStats::Influence), - // ("influ", ListStats::Influence), + // ("influence", stats::ListStats::Influence), + // ("infl", stats::ListStats::Influence), + // ("influ", stats::ListStats::Influence), // Military - ("military", ListStats::Military), - ("mil", ListStats::Military), - ("mt", ListStats::Military), + ("military", stats::ListStats::Military), + ("mil", stats::ListStats::Military), + ("mt", stats::ListStats::Military), // Army - ("army", ListStats::Army), - ("arm", ListStats::Army), - ("ar", ListStats::Army), + ("army", stats::ListStats::Army), + ("arm", stats::ListStats::Army), + ("ar", stats::ListStats::Army), // Strength - ("strength", ListStats::Strength), - ("str", ListStats::Strength), - ("st", ListStats::Strength), + ("strength", stats::ListStats::Strength), + ("str", stats::ListStats::Strength), + ("st", stats::ListStats::Strength), // Fortification - ("fortification", ListStats::Fortification), - ("fort", ListStats::Fortification), - ("ft", ListStats::Fortification), + ("fortification", stats::ListStats::Fortification), + ("fort", stats::ListStats::Fortification), + ("ft", stats::ListStats::Fortification), // Threat - ("threat", ListStats::Threat), - ("thr", ListStats::Threat), - ("th", ListStats::Threat), + ("threat", stats::ListStats::Threat), + ("thr", stats::ListStats::Threat), + ("th", stats::ListStats::Threat), // Infrastructure - ("infrastructure", ListStats::Infrastructure), - ("infra", ListStats::Infrastructure), - ("infr", ListStats::Infrastructure), + ("infrastructure", stats::ListStats::Infrastructure), + ("infra", stats::ListStats::Infrastructure), + ("infr", stats::ListStats::Infrastructure), // Bureaucracy - ("bureaucracy", ListStats::Bureaucracy), - ("bureau", ListStats::Bureaucracy), - ("bur", ListStats::Bureaucracy), + ("bureaucracy", stats::ListStats::Bureaucracy), + ("bureau", stats::ListStats::Bureaucracy), + ("bur", stats::ListStats::Bureaucracy), // Transportation - ("transportation", ListStats::Transportation), - ("trans", ListStats::Transportation), - ("trns", ListStats::Transportation), + ("transportation", stats::ListStats::Transportation), + ("trans", stats::ListStats::Transportation), + ("trns", stats::ListStats::Transportation), // Sprawl - ("sprawl", ListStats::Sprawl), - ("spr", ListStats::Sprawl), - ("spra", ListStats::Sprawl), + ("sprawl", stats::ListStats::Sprawl), + ("spr", stats::ListStats::Sprawl), + ("spra", stats::ListStats::Sprawl), // Health - ("health", ListStats::Health), - ("hlth", ListStats::Health), - ("hlt", ListStats::Health), + ("health", stats::ListStats::Health), + ("hlth", stats::ListStats::Health), + ("hlt", stats::ListStats::Health), ]; - let mut s = OverallStats::linear(33); + let mut s = stats::OverallStats::linear(33); let mut output = String::new(); for (alias, expected_variant) in cases { - let val = alias.parse::().unwrap(); + let val = alias.parse::().unwrap(); s.get_field_mut_from_str(val.into()); assert_eq!( val, expected_variant, @@ -249,7 +252,7 @@ fn test_liststats_unknown_alias() { let unknown = "unknown_stat_123"; // Verify the error type and payload directly. - let err = unknown.parse::().unwrap_err(); + let err = unknown.parse::().unwrap_err(); match err { EpochError::UnknownStatAcronim(msg) => { assert_eq!(msg, unknown); @@ -261,12 +264,12 @@ fn test_liststats_unknown_alias() { #[test] fn test_entity_type_to_shortest() { let out = [ - EntityType::Character, - EntityType::Player, - EntityType::Town, - EntityType::Monster, - EntityType::Blocker, - EntityType::Event, + stats::EntityType::Character, + stats::EntityType::Player, + stats::EntityType::Town, + stats::EntityType::Monster, + stats::EntityType::Blocker, + stats::EntityType::Event, ] .iter() .map(|v| format!("{}:{}", v.to_symbol(), v.to_shortest())) @@ -285,10 +288,10 @@ fn test_entity_type_to_shortest() { #[test] fn test_effect_application_to_symbol() { let out = [ - EffectApplication::Recurring, - EffectApplication::WhenPresent, - EffectApplication::PermanentEffectToApply, - EffectApplication::PermanentEffectApplied, + entity::EffectApplication::Recurring, + entity::EffectApplication::WhenPresent, + entity::EffectApplication::PermanentEffectToApply, + entity::EffectApplication::PermanentEffectApplied, ] .iter() .map(|v| format!("{}:{}", v.to_symbol(), v.to_shortest())) @@ -302,7 +305,7 @@ fn test_effect_application_to_symbol() { // --------------------------------------------------------------------------- #[test] fn test_position_to_symbol() { - let out = [Position(12, 34), Position(0, 0)] + let out = [stats::Position(12, 34), stats::Position(0, 0)] .iter() .map(|p| format!("{}{}", p.to_shortest(), p.to_symbol())) .collect::>() @@ -359,7 +362,7 @@ fn generic_stat_from_str_snapshots() { ]; let mut collect = String::new(); for (snapshot_name, input) in test_cases { - let result: Result = GenericStat::from_str(input); + let result: Result = stats::GenericStat::from_str(input); collect = format!("{}\n{} = {:?}", collect, snapshot_name, result); } assert_snapshot!(collect);