From beaf84e0c20bb6033e2dfe14c3591ffa0850c6ff Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 23:57:33 +0100 Subject: [PATCH] Mostly missing entity fields & refactor --- bin_efo/src/commands/entity_generic.rs | 137 ++++++------ .../entity_generic/helper_functions.rs | 197 ++++-------------- lib_efo/src/entity/implementations.rs | 28 ++- ...y__test__snapshot_delta_stat_positive.snap | 1 + ...entity__test__snapshot_entity_delta-2.snap | 3 +- ...entity__test__snapshot_entity_delta-3.snap | 5 +- ...__entity__test__snapshot_entity_delta.snap | 5 +- ...test__snapshot_full_oneline_display-2.snap | 4 +- ...__test__snapshot_full_oneline_display.snap | 2 +- ...ty__test__snapshot_meta_stats_delta-2.snap | 7 +- ...ty__test__snapshot_meta_stats_delta-3.snap | 3 +- ...tity__test__snapshot_meta_stats_delta.snap | 5 +- ...ntity__test__snapshot_modify_duration.snap | 1 + ...t__snapshot_modify_effect_application.snap | 1 + ...__test__snapshot_modify_effect_bounds.snap | 1 + lib_efo/src/entity/test.rs | 40 ++-- lib_efo/src/stats.rs | 26 ++- .../src/stats/implementations/from_impl.rs | 50 +++++ ...stats__implementations__test__parse_f.snap | 10 + ...ats__implementations__test__parse_f:3.snap | 11 + ...plementations__test__parse_faction:42.snap | 11 + ...stats__implementations__test__parse_g.snap | 7 + ...__implementations__test__parse_global.snap | 7 + ...stats__implementations__test__parse_l.snap | 10 + ...ats__implementations__test__parse_l:5.snap | 9 + ...implementations__test__parse_local:12.snap | 9 + ...stats__implementations__test__parse_n.snap | 7 + ...ts__implementations__test__parse_none.snap | 7 + ..._implementations__test__parse_unknown.snap | 10 + lib_efo/src/stats/implementations/test.rs | 27 +++ 30 files changed, 383 insertions(+), 258 deletions(-) create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f:3.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_faction:42.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_g.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_global.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l:5.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_local:12.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_n.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_none.snap create mode 100644 lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_unknown.snap diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index adc0e5e..edc19dd 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -65,8 +65,10 @@ //! > **Tip** – ` diff` automatically loads the current epoch and the previous one, so you don’t need to specify epoch numbers. //! //! *All changes are persisted immediately to the epoch file after the command finishes.* +#![warn(unused_attributes)] use clap::{Args, Subcommand}; +use lib_efo::stats::{PositionIdentifier, Symbols}; use lib_efo::{ Displayable, entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier}, @@ -75,7 +77,7 @@ use lib_efo::{ epoch_traits::{ConfigWritable, Diffable}, }, error::EpochError, - stats::{EntityType, FactionId, PositionIdentifier, StatPair, Symbols}, + stats, utils::RngLevel, }; use log::info; @@ -133,7 +135,7 @@ pub(crate) struct ShowArgs { /// Filter by faction id (used only when an identifier is supplied) #[arg(long, short)] - pub faction: Option, + pub faction: Option, } /// Common arguments used for *add* and *edit* operations. @@ -154,30 +156,9 @@ pub struct AddArgs { #[arg(value_enum, long, short, default_value_t = RngLevel::Med)] pub rng: RngLevel, - /// A position Identifier, either a grid position, and exact position or a tag - #[arg(short, long)] - pub position: Option, - - /// Updates the reach of the entity - #[arg(long, short = 'R')] - pub reach: Option, - - /// Lifespan of the entity – see the `--duration` description. - #[arg(long, short)] - pub duration: Option, - - /// Effect bounds in the form `min,max`. See the `--bounds` - /// description for details. - #[arg(long, short)] - pub bounds: Option, - - /// How the effect is applied – see the `--effect` description. - #[arg(long, short = 'a')] - pub effect: Option, - - /// One or more `key:value` pairs that set the entity’s stats. - #[arg(short, long)] - pub stats: Vec, + #[command(flatten)] + /// Common arguments between adding and editing + pub common_args: CommonArgs, } #[derive(Args, Debug)] @@ -194,29 +175,48 @@ pub struct EditArgs { #[arg(long, short='D', action = clap::ArgAction::SetTrue, default_value_t = false)] pub delta: bool, - /// A position Identifier, either a grid position, and exact position or a tag - #[arg(short, long)] + #[command(flatten)] + /// Common arguments between adding and editing + pub common_args: CommonArgs, +} + +#[derive(Args, Debug)] +pub struct CommonArgs { + /// A position Identifier, either a grid position (~x,y), exact position (x,y) or a tag (@uuid) + #[arg(short = 'p', long)] pub position: Option, - /// Updates the reach of the entity - #[arg(long, short = 'R')] - pub reach: Option, - /// New duration for the entity. - #[arg(long, short)] + #[arg(long, short = 'd')] pub duration: Option, /// New effect bounds. - #[arg(long, short)] + #[arg(long, short = 'b')] pub bounds: Option, /// New effect application mode. - #[arg(short, long)] + #[arg(short = 's', long)] pub effect: Option, /// One or more `key:value` pairs that modify the entity’s stats. - #[arg(short, long, num_args = 1..)] - pub stats: Vec, + #[arg(short = 's', long, num_args = 1..)] + pub stats: Vec, + + #[arg(short = 'f', long, group = "faction_group")] + /// The faction to which the entity should belong. + pub faction: Option, + + #[arg(short = 'n', long, action = clap::ArgAction::SetTrue, default_value_t = false, group="faction_group")] + /// The entity doens't belong to any faction. + pub no_faction: bool, + + /// Updates the reach of the entity + #[arg(long, short = 'R')] + pub reach: Option, + + /// The description of the Entity + #[arg(long, short = 'D')] + pub description: Option, } /// Handles an entity subcommand. @@ -233,7 +233,7 @@ pub struct EditArgs { /// A `Result` indicating success (`Ok(())`) or the encountered `AppError`. pub fn handle_entity_commands( entity_sub_commands: &EntitySubCommands, - e_type: &EntityType, + e_type: &stats::EntityType, ) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; match entity_sub_commands { @@ -262,23 +262,35 @@ pub fn handle_entity_commands( /// Function handler for the create subcommand pub(crate) fn handle_create_entity( entity_args: &AddArgs, - e_type: &EntityType, + e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; + // Early extract position + let position = if let Some(position) = &entity_args.common_args.position { + Some(epoch_info.resolve_position(position)?) + } else { + None + }; let ident = entity_args.identifier.clone().map(EntityIdentifier::Name); if epoch_info.find_entity_of_type(&ident, e_type).is_ok() { Err(EpochError::EntityAlreadyExist(ident))?; }; + // Create new (rng) entity let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; - if let Some(position) = &entity_args.position { - epoch_info.resolve_position(position)?; - } - helper_functions::update_stats(&entity_args.stats, false, &mut entity); + // Update entity with sensible defaults + helper_functions::update_stats(&entity_args.common_args.stats, false, &mut entity); helper_functions::update_defaults(entity_args, &mut entity); + // Do all updates from the common args + if let Some(position) = &entity_args.common_args.position { + entity.modify_position(epoch_info.resolve_position(position)?); + } + helper_functions::update_common_values(&entity_args.common_args, position, &mut entity); + + // Show success let vec_entities: &mut Vec = epoch_info.vec_entities_mut(e_type); info!("Created character: {:#?}", entity); entity.print_full(); @@ -289,7 +301,7 @@ pub(crate) fn handle_create_entity( ); vec_entities.push(entity); - // No need to change main epoch that didn't change a serialized field + // Save changes epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?; display_success(message); @@ -299,7 +311,7 @@ pub(crate) fn handle_create_entity( /// Function handler for the delete subcommand fn handle_delete_entity( entity_args: &DelArgs, - e_type: &EntityType, + e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; @@ -328,7 +340,7 @@ fn handle_delete_entity( /// Function handler for the diff subcommand fn handle_diff_entity( entity_args: &DiffArgs, - e_type: &EntityType, + e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { // Load the epochs to diff @@ -357,7 +369,7 @@ fn handle_diff_entity( /// Function handler for the show subcommand fn handle_show_entity( entity_args: &ShowArgs, - e_type: &EntityType, + e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current()?; @@ -372,23 +384,14 @@ fn handle_show_entity( Ok(()) } -// /// Function handler for the find subcommand -// fn handle_find_entity( -// entity_args: &EntityArgs, -// e_type: &EntityType, -// main_epoch: &mut EpochConfig, -// ) -> Result<(), EpochError> { -// handle_show_entity(entity_args, e_type, main_epoch) -// } - /// Function handler for the edit subcommand fn handle_edit_entity( entity_args: &EditArgs, - e_type: &EntityType, + e_type: &stats::EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let position = if let Some(position) = &entity_args.position { + let position = if let Some(position) = &entity_args.common_args.position { Some(epoch_info.resolve_position(position)?) } else { None @@ -403,23 +406,13 @@ fn handle_edit_entity( Some(entity_args.identifier.clone()), ))?; - helper_functions::update_stats(&entity_args.stats, entity_args.delta, entity); - - if let Some(position) = position { - entity.modify_position(position); - } - if let Some(duration) = &entity_args.duration { - entity.modify_duration(duration.clone()); - } + helper_functions::update_stats(&entity_args.common_args.stats, entity_args.delta, entity); + // Update name if needed if let Some(ref name) = entity_args.new_name { entity.name = name.clone(); } - if let Some(effect) = &entity_args.effect { - entity.modify_effect_application(effect.clone()); - } - if let Some(bounds) = &entity_args.bounds { - entity.modify_effect_bounds(bounds.clone()); - } + + helper_functions::update_common_values(&entity_args.common_args, position, entity); entity.print_full(); let message = &crate::success::SuccessMessages::EditedEntity( diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs index 347310f..4af7e92 100644 --- a/bin_efo/src/commands/entity_generic/helper_functions.rs +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -3,10 +3,10 @@ use lib_efo::{ entity::{EffectBounds, Entity}, naming::NAMING, - stats::{EntityType, StatPair}, + stats::{self, EntityType, StatPair}, }; -use crate::commands::entity_generic::AddArgs; +use crate::commands::entity_generic::{AddArgs, CommonArgs}; /// 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, is_a_delta: bool, e: &mut Entity) { @@ -15,109 +15,6 @@ pub(crate) fn update_stats(pair_list: &Vec, is_a_delta: bool, e: &mut } } -// /// Looks up an entity inside the given `epoch_info` according to the -// /// supplied arguments. -// /// -// /// The function returns a reference to the matching entity or an -// /// `EpochError::EntityNotFound` if no entity matches. -// /// -// /// # Arguments -// /// * `entity_args` - The arguments that identify the entity. -// /// * `e_type` - The type of entity to look for. -// /// * `epoch_info` - The epoch that contains all entities. -// /// -// /// # Returns -// /// * `Ok(&Entity)` - The entity that matches the arguments. -// /// * `Err(EpochError::EntityNotFound)` - No matching entity was found. -// #[deprecated(note = "Use epoch_info.find_entity_of_type instead")] -// pub(crate) fn find_entity<'a>( -// entity_to_find: &'a Option, -// e_type: &'a EntityType, -// epoch_info: &'a lib_efo::epoch::EpochInfo, -// ) -> Result<&'a Entity, EpochError> { -// epoch_info -// .vec_entities(e_type) -// .iter() -// .find(|&entity| entity.match_identifier(entity_to_find)) -// .ok_or(EpochError::EntityNotFound( -// e_type.clone(), -// entity_to_find.clone(), -// )) -// } - -// /// Returns a slice over the entities of the requested type from the given `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 -// /// * `e_type` - The type of entities to retrieve. -// /// * `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`. -// #[inline] -// #[deprecated(note = "Use epoch_info.vec_entities instead")] -// pub(crate) fn vec_entities<'a>( -// e_type: &'a EntityType, -// epoch_info: &'a lib_efo::epoch::EpochInfo, -// ) -> &'a Vec { -// match e_type { -// EntityType::Character => &epoch_info.characters, -// EntityType::Player => unimplemented!("No players for now"), -// EntityType::Town => &epoch_info.towns, -// EntityType::Monster => &epoch_info.calamities, -// EntityType::Blocker => &epoch_info.blockers, -// EntityType::Event => &epoch_info.events, -// } -// } - -// #[inline] -// /// Returns a mutable slice over the entities of the requested type from the given -// /// `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`. -// #[deprecated(note = "Use epoch_info.vec_entities_mut instead")] -// pub(crate) fn vec_entities_mut<'a>( -// e_type: &'a EntityType, -// epoch_info: &'a mut lib_efo::epoch::EpochInfo, -// ) -> &'a mut Vec { -// match e_type { -// EntityType::Character => &mut epoch_info.characters, -// EntityType::Player => unimplemented!("No players for now"), -// EntityType::Town => &mut epoch_info.towns, -// EntityType::Monster => &mut epoch_info.calamities, -// EntityType::Blocker => &mut epoch_info.blockers, -// EntityType::Event => &mut epoch_info.events, -// } -// } - -// /// Helper function finding by name, note that a lot more helpers could be done to find by other criterias -// #[deprecated(note = "Use entity.match_identifier instead")] -// pub(crate) fn find_by_args( -// entity_to_match: &Entity, -// entity_identifier: &Option, -// ) -> bool { -// match entity_identifier { -// Some(EntityIdentifier::Name(name)) => entity_to_match.name.starts_with(name), -// Some(EntityIdentifier::Id(id)) => { -// entity_to_match.id.hyphenated().to_string().starts_with(id) -// } -// None => false, -// } -// } - /// Update the default values of the entity with sensible defaults pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) { let entity_type = &e.entity_type; @@ -161,7 +58,7 @@ pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) { ), }; // This is the sensible default for all creatures & characters - if let Some(duration) = &entity_args.duration { + if let Some(duration) = &entity_args.common_args.duration { e.modify_duration(duration.clone()); } else { e.modify_duration(duration); @@ -174,63 +71,55 @@ pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) { } // This is the sensible default for all creatures & characters - if let Some(effect) = &entity_args.effect { + if let Some(effect) = &entity_args.common_args.effect { e.modify_effect_application(effect.clone()); } else { e.modify_effect_application(effect); } // This is the sensible default for characters - if let Some(bounds) = &entity_args.bounds { + if let Some(bounds) = &entity_args.common_args.bounds { e.modify_effect_bounds(bounds.clone()); } else { e.modify_effect_bounds(bounds); } } -// /// Get the position of an entity either directly or cloning one from an epoch -// // TODO: This should be a method of epochinfo to avoid all borrow shenenigans -// #[deprecated(note = "Use epoch.resolve_position instead")] -// pub(crate) fn get_pos( -// position: &PositionIdentifier, -// epoch: &EpochInfo, -// ) -> Result { -// Ok(match position { -// PositionIdentifier::Exact(pos) => pos.clone(), -// PositionIdentifier::Grid(pos) => pos.to_position(), -// PositionIdentifier::Id(ident) => epoch.find_any_entity(ident.clone())?.position().clone(), -// }) -// } -// /// Find an entity by its UUID. -// /// -// /// This function searches the currently loaded epoch for an entity whose -// /// `id` matches the supplied `Uuid`. It looks in both the `events`, `towns` -// /// and `characters` collections of the epoch. -// /// -// /// # Arguments -// /// * `id` - The `Uuid` of the entity to locate. -// /// -// /// # Returns -// /// * `Ok(&Entity)` - Reference to the entity if it is present in the -// /// current epoch. -// /// * `Err(EpochError::EntityNotFoundById(id))` - No entity with the -// /// supplied UUID exists in the epoch. -// #[deprecated(note = "Use epoch_info.find_any_entity instead")] -// pub fn find_any_entity( -// epoch_info: &EpochInfo, -// id: EntityIdentifier, -// ) -> Result<&Entity, EpochError> { -// let predicate = |entity: &&Entity| match &id { -// EntityIdentifier::Name(name) => entity.name.starts_with(name), -// EntityIdentifier::Id(id) => entity.id.to_string().starts_with(id), -// }; -// epoch_info -// .events -// .iter() -// .find(predicate) -// .or(epoch_info.characters.iter().find(predicate)) -// .or(epoch_info.towns.iter().find(predicate)) -// .or(epoch_info.blockers.iter().find(predicate)) -// .or(epoch_info.calamities.iter().find(predicate)) -// .ok_or(EpochError::EntityNotFoundById(id)) -// } +/// Apply a `CommonArgs` bundle to an existing entity. +/// +/// # Parameters +/// * `entity_args` – A set of common arguments that may specify +/// duration, effect application, bounds, position, and faction. +/// * `position` – An optional `stats::Position`. If `Some`, it +/// overrides the position supplied in `entity_args`. Passing +/// `None` leaves the entity’s position untouched. +/// * `entity` – The mutable entity to update. +pub fn update_common_values( + entity_args: &CommonArgs, + position: Option, + entity: &mut Entity, +) { + if let Some(position) = position { + entity.modify_position(position); + } + if let Some(duration) = &entity_args.duration { + entity.modify_duration(duration.clone()); + } + if let Some(effect) = &entity_args.effect { + entity.modify_effect_application(effect.clone()); + } + if let Some(bounds) = &entity_args.bounds { + entity.modify_effect_bounds(bounds.clone()); + } + if let Some(faction) = &entity_args.faction { + entity.modify_faction(Some(*faction)); + } else if entity_args.no_faction { + entity.modify_faction(None); + } + if let Some(reach) = &entity_args.reach { + entity.modify_reach(reach.clone()); + } + if let Some(desciption) = &entity_args.description { + entity.modify_description(desciption.clone()); + } +} diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 0ba41d2..50c3ad6 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -13,8 +13,8 @@ use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, Ent use crate::epoch::epoch_traits::Diffable; use crate::error::EpochError; use crate::stats::{ - EntityType, GenericStat, ListStats, MetaStats, OverallStats, Position, PositionGrid, StatPair, - Symbols, + self, EntityType, FactionId, GenericStat, ListStats, MetaStats, OverallStats, Position, + PositionGrid, StatPair, Symbols, }; use crate::utils::RngLevel; use crate::{Displayable, items_table}; @@ -428,6 +428,24 @@ impl Entity { 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 @@ -436,6 +454,11 @@ impl Entity { self.metadata.position = pos.to_position(); } + /// Sets the entity’s description as a String. + pub fn modify_description(&mut self, descritption: String) { + self.description = descritption; + } + /// Returns a **read‑only reference** to the entity’s current position. pub fn position(&self) -> &Position { &self.metadata.position @@ -545,6 +568,7 @@ impl Diffable for MetaStats { .filter(|t1| other.links.iter().any(|t2| t1 == t2)) .collect(), prestige: self.prestige - other.prestige, + reach: stats::Reach::None, } } } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap index ee4827b..6f5d45c 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap @@ -81,6 +81,7 @@ Entity { prestige: GenericStat( 0, ), + reach: None, }, entity_type: Event, duration: 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 07a4d68..a72ff83 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,12 +146,13 @@ Entity { ), links: [ TownId( - 00000000-0000-0000-0000-000000000079, + 79000000-0000-0000-0000-000000000000, ), ], prestige: GenericStat( 0, ), + reach: None, }, entity_type: Town, duration: Permanent, diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap index 6f1174c..f0a7520 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap @@ -139,12 +139,12 @@ Entity { ), capital: Some( TownId( - 00000000-0000-0000-0000-00000000007c, + 7c000000-0000-0000-0000-000000000000, ), ), governor: Some( CharacterId( - 2000, + 0c000000-0000-0000-0000-000000000000, ), ), faction: Some( @@ -156,6 +156,7 @@ Entity { prestige: GenericStat( 2, ), + reach: None, }, entity_type: Monster, duration: Permanent, diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap index 8b7671c..c8e8e63 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap @@ -139,12 +139,12 @@ Entity { ), capital: Some( TownId( - 00000000-0000-0000-0000-000000000079, + 79000000-0000-0000-0000-000000000000, ), ), governor: Some( CharacterId( - 1500, + 12000000-0000-0000-0000-000000000000, ), ), faction: Some( @@ -156,6 +156,7 @@ Entity { prestige: GenericStat( -2, ), + reach: None, }, entity_type: Town, duration: Permanent, diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap index c0c47bb..af4e455 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap @@ -4,11 +4,11 @@ expression: e.to_pretty_tree() --- [ Hero 󰻾[0c000000-0000-0000-0000-000000000000]] ├─ metadata - │ ├─ capital: "\u{f0efe}[0000000]" + │ ├─ capital: "\u{f0efe}[7900000]" │ ├─ prestige: 3 │ └─ position: ( 2, 4)⚓ ├─ links - │ └─ 󰻾[0000000] + │ └─ 󰻾[7900000] ├─ duration: ⧗10 ├─ effect_nature: Recurring └─ effect_bounds: (1 ⭾ 5) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap index 428bbca..abc9b08 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -4,5 +4,5 @@ expression: e.oneline_display() --- ├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10 │ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3 -│ └─  󰻾[0000000]  󰻾[11] +│ └─  󰻾[7900000]  󰻾[0b000000-0000-0000-0000-000000000000] │ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap index 6eed292..7cad862 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap @@ -8,7 +8,11 @@ MetaStats { 0, ), capital: None, - governor: None, + governor: Some( + CharacterId( + c5040000-0000-0000-0000-000000000000, + ), + ), faction: Some( FactionId( 33, @@ -18,4 +22,5 @@ MetaStats { prestige: GenericStat( 0, ), + reach: None, } 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 51a88db..a592517 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,10 +16,11 @@ MetaStats { ), links: [ TownId( - 00000000-0000-0000-0000-000000000002, + 02000000-0000-0000-0000-000000000000, ), ], prestige: GenericStat( 0, ), + reach: None, } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap index 21a0f97..7b0becf 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap @@ -9,12 +9,12 @@ MetaStats { ), capital: Some( TownId( - 00000000-0000-0000-0000-00000000000c, + 0c000000-0000-0000-0000-000000000000, ), ), governor: Some( CharacterId( - 400, + 72030000-0000-0000-0000-000000000000, ), ), faction: Some( @@ -26,4 +26,5 @@ MetaStats { prestige: GenericStat( 2, ), + reach: None, } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap index f997384..90ec16c 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap @@ -81,6 +81,7 @@ Entity { prestige: GenericStat( 0, ), + reach: None, }, entity_type: Event, duration: Duration( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap index da16fa0..b6b11bc 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap @@ -81,6 +81,7 @@ Entity { prestige: GenericStat( 0, ), + reach: None, }, entity_type: Event, duration: Done, diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap index 3138636..9d29246 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap @@ -81,6 +81,7 @@ Entity { prestige: GenericStat( 0, ), + reach: None, }, entity_type: Event, duration: Done, diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index c68c1cb..a8c2ba3 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -232,12 +232,13 @@ fn full_entity() -> Entity { name: "Hero".into(), entity_type: EntityType::Character, metadata: MetaStats { - capital: Some(stats::TownId(Uuid::from_u128(121))), - governor: Some(stats::CharacterId(11)), + capital: Some(stats::TownId(Uuid::from_u128_le(121))), + governor: Some(stats::CharacterId(Uuid::from_u128_le(11))), prestige: stats::GenericStat(3), position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), - links: vec![TownId(Uuid::from_u128(121))], + links: vec![TownId(Uuid::from_u128_le(121))], + reach: stats::Reach::Global, }, duration: EntityDuration::Duration(10), effect_nature: EffectApplication::Recurring, @@ -370,11 +371,12 @@ fn snapshot_entity_delta() { temp_stats: None, metadata: MetaStats { position: Position::from((44, 666)), - capital: Some(stats::TownId(Uuid::from_u128(124))), - governor: Some(stats::CharacterId(2000)), + 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![TownId(Uuid::from_u128(141))], + links: vec![TownId(Uuid::from_u128_le(141))], prestige: stats::GenericStat(3), + reach: stats::Reach::Local(12), }, entity_type: EntityType::Monster, duration: EntityDuration::Permanent, @@ -390,11 +392,12 @@ fn snapshot_entity_delta() { temp_stats: Some(OverallStats::linear(4)), metadata: MetaStats { position: Position::from_str("33,4").unwrap(), - capital: Some(stats::TownId(Uuid::from_u128(121))), - governor: Some(stats::CharacterId(1500)), + 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![TownId(Uuid::from_u128(121))], + links: vec![TownId(Uuid::from_u128_le(121))], prestige: stats::GenericStat(5), + reach: stats::Reach::Faction(stats::FactionId(2)), }, entity_type: EntityType::Town, duration: EntityDuration::Permanent, @@ -455,28 +458,31 @@ fn snapshot_meta_stats_delta() { let meta1 = MetaStats { position: Position::from((1, 11)), - capital: Some(stats::TownId(Uuid::from_u128(1000))), - governor: Some(stats::CharacterId(500)), + 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![TownId(Uuid::from_u128(12))], + links: vec![TownId(Uuid::from_u128_le(12))], prestige: stats::GenericStat(3), + reach: stats::Reach::Global, }; let meta2 = MetaStats { position: Position::from((44, 555)), - capital: Some(stats::TownId(Uuid::from_u128(12))), - governor: Some(stats::CharacterId(400)), + 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![TownId::from(Uuid::from_u128(42))], + links: vec![TownId::from(Uuid::from_u128_le(42))], prestige: stats::GenericStat(1), + reach: stats::Reach::None, }; let meta3 = MetaStats { position: Position::from((44, 555)), capital: None, - governor: Some(stats::CharacterId(400)), + governor: Some(stats::CharacterId(Uuid::from_u128_le(1221))), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(Uuid::from_u128(2))], + links: vec![TownId::from(Uuid::from_u128_le(2))], prestige: stats::GenericStat(1), + reach: stats::Reach::Faction(stats::FactionId(12)), }; let delta = meta1.delta(&meta2); diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 0219ac2..201ca9d 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -10,6 +10,7 @@ //! * **Source** - Formula or function that generates the stat value. #![deny(clippy::missing_docs_in_private_items)] + use crate::{entity::EntityIdentifier, error::EpochError, thin_newtype, utils::RngLevel}; use cli_table::{CellStruct, Color, Style, Table}; use colored::Colorize; @@ -406,6 +407,11 @@ pub struct MetaStats { /// and event outcomes. /// **Source** - `prestige = calculate_prestige(...)`. pub prestige: GenericStat, + + /// The reach of the entity, wether local or worldly + /// + /// **Purpose** - Event validation + pub reach: Reach, } /// A generic stat pair with (ListStats, GenericStat), used mainly for clap @@ -588,7 +594,7 @@ pub trait Symbols { // A stat that is shown to the player *and* can be modified manually. thin_newtype!(GenericStat, isize, derives: [Add, Sub]); thin_newtype!(TownId, Uuid); -thin_newtype!(CharacterId, usize, derives: [Add, Sub]); +thin_newtype!(CharacterId, Uuid); thin_newtype!(FactionId, usize, derives: [Add, Sub]); // --- TRAITS --------------------------------------------------------------- @@ -661,3 +667,21 @@ pub enum PositionIdentifier { /// Reference to an epoch by UUID, written as `@{uuid}`. Id(EntityIdentifier), } + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +/// The reach of the entity +pub enum Reach { + /// The entity can affect **any** target – no positional or faction + /// restrictions. Use this when the effect is truly global. + Global, + /// The entity has a *limited* area of effect. The `usize` usually + /// represents the radius around the entity’s position that the effect covers. + Local(usize), + /// The entity can only affect members of a particular faction. + Faction(FactionId), + // /// The entity only affect a specific entity + // Entity(EntityIdentifier), + /// No reach – the entity should not be applied globally. + #[default] + None, +} diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs index a6b134c..77525ff 100644 --- a/lib_efo/src/stats/implementations/from_impl.rs +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -138,3 +138,53 @@ impl From<(isize, isize)> for Position { Self(value.0, value.1) } } +impl std::str::FromStr for stats::Reach { + type Err = EpochError; // Clap accepts any type that implements `Display` + + fn from_str(s: &str) -> Result { + let s = s.trim().to_ascii_lowercase(); + + match s.as_str() { + "g" | "global" => return Ok(stats::Reach::Global), + "n" | "none" => return Ok(stats::Reach::None), + _ => {} + } + + if s.starts_with('l') { + if let Some(idx) = s.find(':') { + let rad_str = &s[idx + 1..]; + let radius: usize = rad_str.parse().map_err(|_| EpochError::ParsingArgument { + argument_parsed: s, + while_parsing: "Reach::Local", + })?; + return Ok(stats::Reach::Local(radius)); + } else { + return Err(EpochError::ParsingArgument { + argument_parsed: s, + while_parsing: "Local reach requires a radius, e.g. `l:5` or `local:5`", + }); + } + } + + if s.starts_with('f') { + if let Some(idx) = s.find(':') { + let id_str = &s[idx + 1..]; + let id: usize = id_str.parse().map_err(|_| EpochError::ParsingArgument { + argument_parsed: s, + while_parsing: "Reach::Faction", + })?; + return Ok(stats::Reach::Faction(stats::FactionId(id))); + } else { + return Err(EpochError::ParsingArgument { + argument_parsed: s, + while_parsing: "Faction reach requires an id, e.g. `f:3` or `faction:3`", + }); + } + } + + Err(EpochError::ParsingArgument { + argument_parsed: s, + while_parsing: "Unknown error", + }) + } +} diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f.snap new file mode 100644 index 0000000..611636f --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Err( + ParsingArgument { + argument_parsed: "f", + while_parsing: "Faction reach requires an id, e.g. `f:3` or `faction:3`", + }, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f:3.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f:3.snap new file mode 100644 index 0000000..df4c038 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_f:3.snap @@ -0,0 +1,11 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Faction( + FactionId( + 3, + ), + ), +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_faction:42.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_faction:42.snap new file mode 100644 index 0000000..315aa6e --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_faction:42.snap @@ -0,0 +1,11 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Faction( + FactionId( + 42, + ), + ), +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_g.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_g.snap new file mode 100644 index 0000000..3487fa9 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_g.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Global, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_global.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_global.snap new file mode 100644 index 0000000..3487fa9 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_global.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Global, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l.snap new file mode 100644 index 0000000..eac8f20 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Err( + ParsingArgument { + argument_parsed: "l", + while_parsing: "Local reach requires a radius, e.g. `l:5` or `local:5`", + }, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l:5.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l:5.snap new file mode 100644 index 0000000..b3cdee6 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_l:5.snap @@ -0,0 +1,9 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Local( + 5, + ), +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_local:12.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_local:12.snap new file mode 100644 index 0000000..9dd87ff --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_local:12.snap @@ -0,0 +1,9 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + Local( + 12, + ), +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_n.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_n.snap new file mode 100644 index 0000000..c71ea20 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_n.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + None, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_none.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_none.snap new file mode 100644 index 0000000..c71ea20 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_none.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Ok( + None, +) diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_unknown.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_unknown.snap new file mode 100644 index 0000000..2a29d24 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__parse_unknown.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: parsed +--- +Err( + ParsingArgument { + argument_parsed: "unknown", + while_parsing: "Unknown error", + }, +) diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 90bfad7..960d041 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -1,7 +1,9 @@ #![allow(clippy::unwrap_used)] +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; @@ -322,3 +324,28 @@ fn test_entity_duration_to_symbol() { .join("\n"); assert_snapshot!(out); } + +#[test] +fn test_reach_parsing() { + // A collection of inputs we want to snapshot + let cases = vec![ + ("g"), + ("global"), + ("n"), + ("none"), + ("l:5"), + ("local:12"), + ("f:3"), + ("faction:42"), + ("unknown"), + ("l"), + ("f"), + ]; + + for input in cases { + let parsed = input.parse::(); + // `assert_debug_snapshot!` will serialize the `Result` + // (Ok or Err) using its `Debug` impl. + assert_debug_snapshot!(format!("parse_{}", input), parsed); + } +}