dev-ci #7

Merged
Dandaedre merged 22 commits from dev-ci into main 2025-12-16 03:19:53 +01:00
71 changed files with 3481 additions and 1163 deletions

View File

@ -1,8 +1,8 @@
[last_run_clean]
run_status = "Success"
lines_parsed = 83
coverage = 50.17
lines_parsed = 110
coverage = 49.76
[last_run_clean.run_duration]
secs = 25
nanos = 72743368
secs = 26
nanos = 637749582

21
Cargo.lock generated
View File

@ -276,6 +276,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror",
"uuid",
]
[[package]]
@ -317,6 +318,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "getrandom"
version = "0.3.4"
@ -420,6 +427,7 @@ dependencies = [
"rand",
"serde",
"serde_json",
"tempfile",
"thiserror",
"uuid",
]
@ -753,6 +761,19 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"

View File

@ -11,6 +11,7 @@ serde_json = "1.0.145"
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"] }
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"

View File

@ -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}

View File

@ -12,8 +12,8 @@ pub mod entity_generic;
pub mod epoch;
pub mod generate;
pub mod init;
// pub mod roll;
pub mod show;
pub mod status;
// pub mod diff;
// pub mod utils;
// pub mod event;
// pub mod town;

View File

@ -4,37 +4,7 @@
//! An *epoch* is a snapshot of the game state that can be written to disk or rolled back to an earlier one.
//! Every entity type (`character`, `town`, `event`, …) has the same set of operations:
//!
//! ## Summary
//!
//! | Sub‑command | Usage | What it changes |
//! |-------------|-------|-----------------|
//! | **add** | `<entity> add [OPTIONS] [IDENTIFIER]` | Creates a new `<entity>`, pushes it to the epoch’s list, and writes the epoch. |
//! | **del** | `<entity> del <IDENTIFIER>` | Removes the matching `<entity>` from the list and writes the epoch. |
//! | **edit** | `<entity> edit <IDENTIFIER> [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `<entity>` and writes the epoch. |
//! | **find** | `<entity> find <IDENTIFIER>` | Prints full details of a single `<entity>`. |
//! | **show** | `<entity> show [<IDENTIFIER>]` | Lists all entities on one line, or shows one `<entity>` in full detail. |
//! | **diff** | `<entity> diff <IDENTIFIER>` | Prints the difference between the current and previous epoch for that `<entity>`. |
//!
//! *`IDENTIFIER`* is either a **name** or a **@tag** (`@1234`).
//! If omitted, a random name is generated for the type you are working on.
//!
//! ### Options
//!
//! | Flag | Group | Description |
//! |------|-------|-------------|
//! | `-d, --delta` | *edit* | Treat the supplied `stats` values as a delta (add/subtract)
//! instead of an absolute overwrite. |
//! | `-v, --verbose…` | *global* | Increases the amount of diagnostic output. |
//! | `--rng <RNG>` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. |
//! | `--pos-exact <POS>` / `--pos <POS>` | *add/edit* | Set the entity’s coordinates. `--pos-exact` forces the coordinates to be used verbatim; `--pos` applies the map’s current position transformation (if any). |
//! | `--duration <DURATION>` | *add/edit* | Lifespan of the entity – e.g. `Permanent`, `Temporary` or `Duration(1)` for a one‑turn event. |
//! | `--bounds <BOUNDS>` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). |
//! | `--effect <EFFECT>` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. |
//! | `-s, --stats <STATS>` | *add/edit* | One or more `key:value` pairs – e.g. `fod:10 military:8`. |
//! | `--rng-name` | *add* | If set, the tool generates a random name instead of using the supplied identifier. |
//!
//! All changes are **persisted immediately** to the epoch file after the
//! command completes.//!
//! ## Usage
//! All the following example use `chr` as a choice of entity but can be safely substitued to any entity: `event`, `town`, `blocker` etc...
//!
@ -62,11 +32,44 @@
//! chr diff Aria
//! ```
//!
//! > **Tip** – `<entity> diff` automatically loads the current epoch and the previous one, so you don’t need to specify epoch numbers.
//! > **Tip** - `<entity> 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.*
//!
//! ## Summary
//!
//! | Sub-command | Usage | What it changes |
//! |-------------|------- |----------------- |
//! | **add** | `<entity> add [OPTIONS] [IDENTIFIER]` | Creates a new `<entity>`, pushes it to the epoch's list, and writes the epoch. |
//! | **del** | `<entity> del <IDENTIFIER>` | Removes the matching `<entity>` from the list and writes the epoch. |
//! | **edit** | `<entity> edit <IDENTIFIER> [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `<entity>` and writes the epoch. |
//! | **find** | `<entity> find <IDENTIFIER>` | Prints full details of a single `<entity>`. |
//! | **show** | `<entity> show [<IDENTIFIER>]` | Lists all entities on one line, or shows one `<entity>` in full detail. |
//! | **diff** | `<entity> diff <IDENTIFIER>` | Prints the difference between the current and previous epoch for that `<entity>`. |
//!
//! *`IDENTIFIER`* is either a **name** or a **@tag** (`@1234`).
//! If omitted, a random name is generated for the type you are working on.
//!
//! ### Options
//!
//! | Flag | Group | Description |
//! |------ |------- |------------- |
//! | `-d, --delta` | *edit* | Treat the supplied `stats` values as a delta (add/subtract) instead of an absolute overwrite. |
//! | `-v, --verbose…` | *global* | Increases the amount of diagnostic output. |
//! | `--rng <RNG>` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. |
//! | `--pos-exact <POS>` / `--pos <POS>` | *add/edit* | Set the entity's coordinates. `--pos-exact` forces the coordinates to be used verbatim; `--pos` applies the map's current position transformation (if any). |
//! | `--duration <DURATION>` | *add/edit* | Lifespan of the entity - e.g. `Permanent`, `Temporary` or `Duration(1)` for a one-turn event. |
//! | `--bounds <BOUNDS>` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). |
//! | `--effect <EFFECT>` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. |
//! | `-s, --stats <STATS>` | *add/edit* | One or more `key:value` pairs - e.g. `fod:10 military:8`. |
//! | `--rng-name` | *add* | If set, the tool generates a random name instead of using the supplied identifier. |
//!
//! All changes are **persisted immediately** to the epoch file after the
//! command completes.
#![warn(unused_attributes)]
use clap::{Args, Subcommand};
use lib_efo::stats::{GenericStat, PositionIdentifier, Symbols};
use lib_efo::{
Displayable,
entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier},
@ -75,13 +78,13 @@ use lib_efo::{
epoch_traits::{ConfigWritable, Diffable},
},
error::EpochError,
stats::{EntityType, FactionId, Position, StatPair, Symbols},
stats,
utils::RngLevel,
};
use log::info;
use log::{info, trace};
use crate::error::AppError;
use crate::success::display_success;
use crate::success::{SuccessMessages, display_success};
mod helper_functions;
@ -89,7 +92,7 @@ mod helper_functions;
///
/// Each variant contains the arguments that are common to that
/// operation. The enum itself is used by `clap` to dispatch
/// the user‑provided sub‑command.
/// the user-provided sub-command.
#[derive(Subcommand, Debug)]
pub(crate) enum EntitySubCommands {
// /// Find an entity by its identifier
@ -106,7 +109,7 @@ pub(crate) enum EntitySubCommands {
Diff(DiffArgs),
}
/// Arguments used only for the `diff` sub‑command.
/// Arguments used only for the `diff` sub-command.
#[derive(Args, Debug)]
pub(crate) struct DiffArgs {
/// Identifier (name or `@tag`) of the entity to diff
@ -128,12 +131,12 @@ pub(crate) struct DelArgs {
/// Arguments for showing entities.
#[derive(Args, Debug)]
pub(crate) struct ShowArgs {
/// Optional identifier – when omitted all entities are listed.
/// Optional identifier - when omitted all entities are listed.
pub identifier: Option<EntityIdentifier>,
/// Filter by faction id (used only when an identifier is supplied)
#[arg(long, short)]
pub faction: Option<FactionId>,
pub faction: Option<stats::FactionId>,
}
/// Common arguments used for *add* and *edit* operations.
@ -151,34 +154,12 @@ 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::Zero)]
pub rng: RngLevel,
#[arg(value_enum, long, short)]
pub rng: Option<RngLevel>,
/// Place the new entity at an exact position – this ignores
/// any map‑specific coordinate transformations.
#[arg(long, short = 'P', group = "position")]
pub pos_exact: Option<Position>,
/// Place the new entity using the map’s position rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
/// Lifespan of the entity – see the `--duration` description.
#[arg(long, short)]
pub duration: Option<EntityDuration>,
/// Effect bounds in the form `min,max`. See the `--bounds`
/// description for details.
#[arg(long, short)]
pub bounds: Option<EffectBounds>,
/// How the effect is applied – see the `--effect` description.
#[arg(long, short)]
pub effect: Option<EffectApplication>,
/// One or more `key:value` pairs that set the entity’s stats.
#[arg(short, long)]
pub stats: Vec<StatPair>,
#[command(flatten)]
/// Common arguments between adding and editing
pub common_args: CommonArgs,
}
#[derive(Args, Debug)]
@ -195,29 +176,102 @@ pub struct EditArgs {
#[arg(long, short='D', action = clap::ArgAction::SetTrue, default_value_t = false)]
pub delta: bool,
/// Update the entity’s exact position – ignores map transforms.
#[arg(long, short = 'P', group = "position")]
pub pos_exact: Option<Position>,
#[command(flatten)]
/// Common arguments between adding and editing
pub common_args: CommonArgs,
}
/// Update the entity’s position using the map rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
#[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<PositionIdentifier>,
/// New duration for the entity.
#[arg(long, short)]
#[arg(long, short = 'd')]
pub duration: Option<EntityDuration>,
/// New effect bounds.
#[arg(long, short)]
#[arg(long, short = 'b')]
pub bounds: Option<EffectBounds>,
/// New effect application mode.
#[arg(short, long)]
#[arg(short = 'e', long)]
pub effect: Option<EffectApplication>,
/// One or more `key:value` pairs that modify the entity’s stats.
#[arg(short, long, num_args = 1..)]
pub stats: Vec<StatPair>,
/// One or more `key:value` pairs that modify the entity's stats.
#[arg(short = 's', long, num_args = 1..)]
pub stats: Vec<stats::StatPair>,
#[arg(short = 'f', long, group = "faction_group")]
/// The faction to which the entity should belong.
pub faction: Option<stats::FactionId>,
#[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<stats::Reach>,
/// The description of the Entity
#[arg(long, long = "desc")]
pub description: Option<String>,
/// Link to a governor
#[arg(long, short = 'g', group = "governor_group")]
pub governor: Option<EntityIdentifier>,
#[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="governor_group")]
/// The entity doens't belong to any faction.
pub no_governor: bool,
/// Link to a town to set as capital
#[arg(long, short = 'c', group = "capital_group")]
pub capital: Option<EntityIdentifier>,
/// The entity doens't have a capital.
#[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="capital_group")]
pub no_capital: bool,
/// Change the prestige
#[arg(long, group = "capital_group")]
pub prestige: Option<GenericStat>,
/// Change the prestige by a delta
#[arg(long, group = "capital_group", allow_negative_numbers = true)]
pub prestige_add: Option<GenericStat>,
}
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.
@ -234,7 +288,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 {
@ -263,35 +317,59 @@ 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> {
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 {
Some(epoch_info.resolve_position(position)?)
} else {
None
};
let ident = entity_args.identifier.clone().map(EntityIdentifier::Name);
if helper_functions::find_entity(&ident, e_type, epoch_info).is_ok() {
if epoch_info.find_entity_of_type(&ident, e_type).is_ok() {
Err(EpochError::EntityAlreadyExist(ident))?;
};
let vec_entities: &mut Vec<Entity> = helper_functions::vec_entities_mut(e_type, epoch_info);
let mut entity = Entity::create_rng(e_type, &entity_args.rng)?;
helper_functions::update_stats(&entity_args.stats, false, &mut entity);
// Specifying a name means the name needs to be changed
// Specifying an id however means nothing and should be ignored
// Create new (rng) entity
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,
stats::Modification::Replace,
&mut entity,
);
helper_functions::update_defaults(entity_args, &mut entity);
info!("Created character: {:#?}", entity);
entity.print_full();
// 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);
helper_functions::update_advanced_values(&entity_args.common_args, &mut entity, epoch_info)?;
// Show success
let vec_entities: &mut Vec<Entity> = epoch_info.vec_entities_mut(e_type);
info!("Created {}: {:?}", entity.name, entity.id);
trace!("{entity:#?}");
let message = &crate::success::SuccessMessages::CreatedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
vec_entities.push(entity);
// TODO: Rather bad
vec_entities.push(entity.clone());
// No need to change main epoch that didn't change a serialized field
entity.print_full(epoch_info);
// Save changes
epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
@ -301,22 +379,26 @@ 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()?;
let entity_identifier = Some(entity_args.identifier.clone());
let vec_entities: &mut Vec<Entity> = helper_functions::vec_entities_mut(e_type, epoch_info);
let vec_entities: &mut Vec<Entity> = epoch_info.vec_entities_mut(e_type);
let index = vec_entities
.iter()
.position(|entity| helper_functions::find_by_args(entity, &entity_identifier))
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
entity_identifier,
))?;
.position(|entity| entity.match_identifier(&entity_identifier))
.ok_or(EpochError::EntityNotFound(*e_type, entity_identifier))?;
let entity = vec_entities.swap_remove(index);
entity.remove_all_links(epoch_info)?;
// TODO: Clean all the links from it's presence
// for l in entity.links(){
// // Figure out what the link is
// // Delete either a governor or capital
// }
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&crate::success::SuccessMessages::DeletedEntity(
@ -330,7 +412,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
@ -345,87 +427,79 @@ fn handle_diff_entity(
let epoch_current = unsafe { main_epoch.try_load_id(id) }?;
let epoch_past = unsafe { main_epoch.try_load_id(id2) }?;
let binding = Some(entity_args.identifier.clone());
let current_entity = helper_functions::find_entity(&binding, e_type, epoch_current)?;
let past_entity = helper_functions::find_entity(&binding, e_type, epoch_past)?;
let current_entity =
epoch_current.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?;
let past_entity =
epoch_past.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?;
let diff = current_entity.delta(past_entity);
display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2));
diff.print_full();
diff.print_full(epoch_current);
Ok(())
}
/// Function handler for the show subcommand
// TODO: Add filters else this will become very clustered
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()?;
if entity_args.identifier.is_none() {
for entity in helper_functions::vec_entities(e_type, epoch_info) {
entity.print_oneline();
}
println!(
"{}",
epoch_info.vec_entities(e_type).short_display(epoch_info)
);
} else {
let entity = helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info)?;
entity.print_full();
let entity = epoch_info.find_entity_of_type(&entity_args.identifier, e_type)?;
entity.print_full(epoch_info);
}
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> {
entity_args.common_args.validate(e_type)?;
let epoch_info = main_epoch.try_load_current_as_mut()?;
let vec_entities = helper_functions::vec_entities_mut(e_type, epoch_info);
let entity = vec_entities
.iter_mut()
.find(|entity| {
helper_functions::find_by_args(entity, &Some(entity_args.identifier.clone()))
})
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
Some(entity_args.identifier.clone()),
))?;
let mut entity = epoch_info
.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?
.clone();
// TODO(9): Use COW and a flag
// let mut entity = std::borrow::Cow::Borrowed(
// epoch_info.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?,
// );
for stat in &entity_args.stats {
entity.change_stat(stat.clone());
}
if let Some(duration) = &entity_args.duration {
entity.modify_duration(duration.clone());
}
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());
}
entity.print_full();
let message = &crate::success::SuccessMessages::EditedEntity(
let edited_entity = SuccessMessages::EditedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
// Update name if needed
if let Some(ref name) = entity_args.new_name {
entity.name = name.clone();
}
helper_functions::update_stats(
&entity_args.common_args.stats,
entity_args.delta.into(),
&mut entity,
);
let position = if let Some(position) = &entity_args.common_args.position {
Some(epoch_info.resolve_position(position)?)
} else {
None
};
helper_functions::update_common_values(&entity_args.common_args, position, &mut entity);
helper_functions::update_advanced_values(&entity_args.common_args, &mut entity, epoch_info)?;
entity.print_full(epoch_info);
// Only swap if a swap is needed
epoch_info.swap_entity(entity)?;
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
display_success(&edited_entity);
Ok(())
}

View File

@ -1,137 +1,32 @@
//! All helper functions
use lib_efo::{
entity::{EffectBounds, Entity, EntityIdentifier},
entity::{EffectBounds, Entity},
epoch::EpochInfo,
error::EpochError,
naming::NAMING,
stats::{EntityType, StatPair},
stats::{self, EntityType, Symbols},
utils::RngLevel,
};
use log::info;
use uuid::Uuid;
use crate::commands::entity_generic::AddArgs;
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<StatPair>, is_a_delta: bool, e: &mut Entity) {
if is_a_delta {
for stat in pair_list {
e.delta_stat(stat.clone());
}
} else {
for stat in pair_list {
e.change_stat(stat.clone());
}
pub(crate) fn update_stats(
pair_list: &Vec<stats::StatPair>,
delta: stats::Modification,
e: &mut Entity,
) {
for stat in pair_list {
e.change_stat_fuzzy(stat.clone(), delta);
}
}
/// 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.
pub(crate) fn find_entity<'a>(
entity_to_find: &'a Option<EntityIdentifier>,
e_type: &'a EntityType,
epoch_info: &'a lib_efo::epoch::EpochInfo,
) -> Result<&'a Entity, EpochError> {
vec_entities(e_type, epoch_info)
.iter()
.find(|&entity| find_by_args(entity, 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]
pub(crate) fn vec_entities<'a>(
e_type: &'a EntityType,
epoch_info: &'a lib_efo::epoch::EpochInfo,
) -> &'a Vec<Entity> {
match e_type {
EntityType::Character => &epoch_info.characters,
EntityType::Player => todo!(),
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`.
pub(crate) fn vec_entities_mut<'a>(
e_type: &'a EntityType,
epoch_info: &'a mut lib_efo::epoch::EpochInfo,
) -> &'a mut Vec<Entity> {
match e_type {
EntityType::Character => &mut epoch_info.characters,
EntityType::Player => todo!(),
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
pub(crate) fn find_by_args(
entity_to_match: &Entity,
entity_identifier: &Option<EntityIdentifier>,
) -> 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,
}
}
// /// Find an entity matching a tag
// pub(crate) fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> {
// entities
// .iter()
// .find(|e| e.id.hyphenated().to_string().starts_with(id))
// }
// /// Find an entity matching a name
// pub(crate) fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> {
// entities.iter().find(|e| e.name.starts_with(id))
// }
/// 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;
@ -175,7 +70,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);
@ -188,16 +83,236 @@ 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);
}
}
/// 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<stats::Position>,
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(description) = &entity_args.description {
entity.modify_description(description.clone());
}
if let Some(prestige) = &entity_args.prestige {
entity.modify_prestige(*prestige, stats::Modification::Replace)
}
if let Some(prestige) = &entity_args.prestige_add {
entity.modify_prestige(*prestige, stats::Modification::Delta)
}
}
/// Try to update all advanced values
pub fn update_advanced_values(
entity_args: &CommonArgs,
entity: &mut Entity,
epoch_info: &mut EpochInfo,
) -> Result<(), EpochError> {
update_link(
entity_args.governor.as_ref(),
entity_args.no_governor,
|e| e.remove_governor().map(|i| *i),
add_entity,
entity,
epoch_info,
stats::Role::Govern,
&EntityType::Character,
)?;
update_link(
entity_args.capital.as_ref(),
entity_args.no_capital,
|e| e.remove_capital().map(|i| *i),
add_entity,
entity,
epoch_info,
stats::Role::Capital,
&EntityType::Town,
)?;
Ok(())
}
/// Update a single “link” (governor, capital, …) in a DRY way.
///
/// * `opt_new` – `Some(&T)` if the caller supplied a new value, `None` otherwise.
/// * `no_flag` – `entity_args.no_xxx` (true if we are allowed to delete the old link).
/// * `remove_old` – closure that removes the old value and returns `Option<Id>`.
/// * `add_new` – closure that inserts the new value and returns `AddingDoneStruct`.
/// * `role` – the `stats::Role` belonging to this link.
/// * `etype` – the `EntityType` belonging to this link.
///
/// All operations are performed on the supplied `entity` and `epoch_info`.
///
/// Returns `Ok(())` or propagates any `EpochError` that occurs.
#[allow(clippy::too_many_arguments)]
fn update_link<T, FRemove, FAdd>(
opt_new: Option<&T>,
no_flag: bool,
remove_old: FRemove,
add_new: FAdd,
entity: &mut Entity,
epoch_info: &mut EpochInfo,
role: stats::Role,
etype: &EntityType,
) -> Result<(), EpochError>
where
FRemove: FnOnce(&mut Entity) -> Option<Uuid>,
FAdd: Fn(
&mut Entity,
&mut EpochInfo,
&T,
&EntityType,
stats::Role,
) -> Result<AddingDoneStruct, EpochError>,
{
if let Some(new_val) = opt_new {
let AddingDoneStruct { old_id, new_id } =
add_new(entity, epoch_info, new_val, etype, role)?;
remove_link_from_old(entity, epoch_info, old_id, role, etype);
add_link_to_new(entity, epoch_info, new_id, role, etype)?;
} else if no_flag && let Some(old_id) = remove_old(entity) {
remove_link_from_old(entity, epoch_info, Some(old_id), role, etype);
}
Ok(())
}
/// Structure existing only to have sane stranfer
#[allow(clippy::missing_docs_in_private_items)]
struct AddingDoneStruct {
old_id: Option<Uuid>,
new_id: Uuid,
}
/// Add the entity id to the entity, swapping the old one
fn add_entity(
entity: &mut Entity,
epoch_info: &mut EpochInfo,
target: &lib_efo::entity::EntityIdentifier,
target_t: &EntityType,
action: stats::Role,
) -> Result<AddingDoneStruct, EpochError> {
let target = epoch_info.find_entity_of_type(&Some(target.clone()), target_t)?;
let new_id = target.id;
let old_id = match action {
stats::Role::Govern => entity
.change_governor(stats::CharacterId(new_id))
.map(|v| *v),
stats::Role::Capital => entity.change_capital(stats::TownId(new_id)).map(|v| *v),
stats::Role::Undefined => None,
};
info!(
"Adding {}{} [{}] to {}{}",
target.name,
target.id.to_symbol(),
action.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<Uuid>,
role: stats::Role,
target_t: &EntityType,
) {
if let Some(old_id) = old_id {
info!(
"Deleting {} link to {} {}{}",
old_id.to_symbol(),
entity.id.to_symbol(),
entity.entity_type.to_symbol(),
entity.name
);
let destroy_link = stats::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, target_t, destroy_link)
.inspect_err(|_| {
display_warning(&WarningMessages::EntityNotFound {
id: old_id.to_symbol(),
e_type: target_t,
})
});
}
}
/// 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,
target_t: &EntityType,
) -> Result<(), EpochError> {
let link_back = stats::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, target_t, 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,
}
}

View File

@ -1,9 +1,9 @@
//! # `epoch` sub-command
//!
//! The `epoch` sub‑command is the single entry point for all epoch‑related
//! The `epoch` sub-command is the single entry point for all epoch-related
//! operations in **efo**.
//! An *epoch* represents a point in the simulated world’s history.
//! The command lets you inspect, advance, modify and sanity‑check the epoch
//! An *epoch* represents a point in the simulated world's history.
//! The command lets you inspect, advance, modify and sanity-check the epoch
//! timeline.
//!
//! ### Usage
@ -24,7 +24,7 @@
//! # Add a unique tag to the current epoch
//! efo epoch tag milestone1
//!
//! # Replace the current epoch’s summary
//! # Replace the current epoch's summary
//! efo epoch summary "Reached the new frontier"
//!
//! # (Future) Check consistency
@ -33,16 +33,16 @@
//!
//! ### Summary
//!
//! | Sub‑command | Usage | What it changes |
//! |-------------|-------|-----------------|
//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. |
//! | `switch` | `efo epoch switch <id>` | Sets the current epoch to the specified `<id>` (must already exist). |
//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
//! | `diff` | `efo epoch diff <id1> <id2>` | *Unimplemented* – placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <TAG>` | Adds a unique tag to the current epoch, updating the global tag map. |
//! | `fsck` | `efo epoch fsck` | *Unimplemented* – intended to run a consistency check. |
//! | `summary` | `efo epoch summary <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//! | Sub-command | Usage | What it changes |
//! |-------------|------------------------------|----------------------------------------------------------------------|
//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. |
//! | `switch` | `efo epoch switch <id>` | Sets the current epoch to the specified `<id>` (must already exist). |
//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. |
//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. |
//! | `diff` | `efo epoch diff <id1> <id2>` | *Unimplemented* - placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <TAG>` | Adds a unique tag to the current epoch, updating the global tag map. |
//! | `fsck` | `efo epoch fsck` | *Unimplemented* - intended to run a consistency check. |
//! | `summary` | `efo epoch summary <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//!
#![warn(missing_docs, clippy::missing_docs_in_private_items)]

View File

@ -7,21 +7,21 @@
//!
//! ## Available sub-commands
//!
//! | Sub‑command | What it prints | Typical output |
//! | Sub-command | What it prints | Typical output |
//! |-------------|----------------|----------------|
//! | `character` | Character names (short or long) | `Eldric the Bold` |
//! | `event` | Random event ideas | `A mysterious fog descends over the town` |
//! | `town` | Town names | `Glimmerdale` |
//! | `exotic` | Exotic character names | `Zar‑nith the Wanderer` |
//! | `exotic` | Exotic character names | `Zar-nith the Wanderer` |
//! | `calamity` | Calamity names | `Great Plague of 1743` |
//! | `blocker` | Blocker names | `Stone Wall of the North` |
//!
//! All sub‑commands share the same options:
//! All sub-commands share the same options:
//!
//! * `-n / --number` – how many items to generate (default = 1)
//! * `--short` – print the short form when applicable (ignored for `event`, `exotic`,
//! * `-n / --number` - how many items to generate (default = 1)
//! * `--short` - print the short form when applicable (ignored for `event`, `exotic`,
//! `calamity`, `blocker`)
//! * `--name` – output only the name string, no extra formatting (good for scripting)
//! * `--name` - output only the name string, no extra formatting (good for scripting)
//!
//! # Usage
//! ```bash
@ -44,13 +44,13 @@
//! gen blocker -n 4 --short
//! ```
//!
//! > **Tip** – redirect or pipe the output:
//! > **Tip** - redirect or pipe the output:
//! > `gen character -n 10 > chars.txt`
//!
//! ---
//!
//! # Summary
//! | Sub‑command | Usage example | What it does |
//! | Sub-command | Usage example | What it does |
//! |-------------|---------------|-----------------|
//! | `character` | `gen character -n 5 --short` | Prints 5 short (or long if `--short` omitted) character names |
//! | `event` | `gen event -n 3 --name` | Prints 3 event names only |
@ -59,7 +59,7 @@
//! | `calamity` | `gen calamity -n 2` | Prints 2 calamity names |
//! | `blocker` | `gen blocker -n 4 --short` | Prints 4 blocker names (short form) |
//!
//! *All sub‑commands simply output the generated data; they do not alter any files or state.*
//! *All sub-commands simply output the generated data; they do not alter any files or state.*
use clap::{Args, Subcommand};
use lib_efo::{Displayable, error::EpochError, naming::NAMING};

View File

@ -11,7 +11,7 @@
//!
//! ## Guide
//!
//! The `init` sub‑command bootstraps a new epoch repository:
//! The `init` sub-command bootstraps a new epoch repository:
//!
//! * It creates the default `.epoch` configuration file in the current directory.
//! * It creates an empty **epoch 0** folder (with its metadata file).
@ -20,13 +20,13 @@
//! ### How to use
//!
//! ```bash
//! epoch init # normal init – directory must be empty
//! epoch init --force # skip the empty‑folder check
//! epoch init # normal init - directory must be empty
//! epoch init --force # skip the empty-folder check
//! ```
//!
//! ### Table Entry
//!
//! | Sub‑command | Usage | What it changes |
//! | Sub-command | Usage | What it changes |
//! |-------------|-------|-----------------|
//! | `init` | `epoch init [--force]` | Initialize the current folder as an epoch folder |
@ -44,12 +44,11 @@ use crate::{
success::{SuccessMessages, display_success},
};
#[derive(Args, Debug)]
/// Arguments for the `init` subcommand.
///
/// The `--force` flag forces initialisation even when the target
/// directory already contains files.
#[derive(Args, Debug)]
pub struct InitCmd {
/// Force initialisation even if the directory isn't empty
#[arg(long)]

View File

@ -2,7 +2,7 @@
//! Used to display structures with various degree of verbosity
use clap::Subcommand;
use lib_efo::{Displayable, entity::Entity, naming::NAMING};
use lib_efo::{Displayable, entity::Entity, epoch::EpochInfo, naming::NAMING};
use crate::error::AppError;
#[derive(Subcommand, Debug)]
@ -36,12 +36,12 @@ pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> {
println!("{}", e.oneline_display());
println!("{}", e.oneline_display());
println!("\n\n\n SHORT");
e.print_short();
e.short_display(&EpochInfo::default());
println!("\n\n\n LONG");
e.print_full();
e.print_full(&EpochInfo::default());
println!("\n\n\n TREE");
println!("{}", e.to_pretty_tree());
println!("{}", e.to_pretty_tree(&EpochInfo::default()));
Ok(())
}

View File

@ -0,0 +1,74 @@
//! A very succint status display
use clap::Args;
use colored::Colorize;
use lib_efo::epoch::{EpochConfig, EpochId};
/// Arguments for the `status` subcommand.
#[derive(Args, Debug)]
pub struct StatusCmd {
/// An optionnal EpochId showing another epoch
custom_id: Option<EpochId>,
}
/// Print a short status
pub(crate) fn status(cmd: &StatusCmd) -> Result<(), crate::error::AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
let current_epoch = if let Some(epoch_id) = cmd.custom_id {
main_epoch.try_load(&epoch_id)?;
unsafe { main_epoch.try_load_id(epoch_id)? }
} else {
main_epoch.try_load_current()?
};
let mut out = String::new();
out.push_str(
&format!(
"[{}{} {}]\n",
"󰬌 ".bright_blue(),
"Epoch".blue(),
current_epoch.epoch_id
)
.blue(),
);
if !current_epoch.summary.is_empty() {
out.push_str(&format!(
" ├─ {:12} {}\n",
"Summary".green(),
current_epoch.summary
));
}
if !current_epoch.tags.is_empty() {
out.push_str(&format!(
" ├─ {:12} {}\n",
"Tags".green(),
current_epoch.tags.join(",")
));
}
out.push_str(&format!(" └─ {}\n", "Stats".green()));
out.push_str(&format!(
" ├ {:11} {}\n",
"Events".bright_green(),
current_epoch.events.len()
));
out.push_str(&format!(
" ├ {:11} {}\n",
"Characters".bright_green(),
current_epoch.characters.len()
));
out.push_str(&format!(
" ├ {:11} {}\n",
"Towns".bright_green(),
current_epoch.towns.len()
));
out.push_str(&format!(
" └ {:11} {}",
"Blockers".bright_green(),
current_epoch.blockers.len()
));
println!("{}", out);
Ok(())
}

View File

@ -1,9 +1,9 @@
//! # `epoch_forge` CLI
//!
//! The **command‑line interface** for `epoch_forge`. It exposes a single
//! binary `efo` that supports the following sub‑commands:
//! The **command-line interface** for `epoch_forge`. It exposes a single
//! binary `efo` that supports the following sub-commands:
//!
//! ## Sub‑modules
//! ## Sub-modules
//!
//! * [`epoch`](crate::commands::epoch) - switch / advance time
//! * [`event`](crate::commands::entity_generic) - add / remove events
@ -13,7 +13,7 @@
//! * [`calamity`](crate::commands::entity_generic) - add / remove calamities
//! * [`link`](crate::commands::link) - add / remove links (alliances, wars, roads, etc.)
//!
//! Each sub‑command is implemented in its own module under `commands/`.
//! Each sub-command is implemented in its own module under `commands/`.
//! The `main.rs` file simply parses arguments with `clap` and dispatches
//! to the appropriate handler. The handlers share a common `World`
//! instance that they load from / persist to disk.
@ -30,7 +30,7 @@ use clap::{Parser, Subcommand};
use crate::{
commands::{
entity_generic::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd,
init::InitCmd, show::ShowCmd,
init::InitCmd, show::ShowCmd, status::StatusCmd,
},
error::AppError,
};
@ -62,6 +62,8 @@ struct Cli {
enum TopLevelCmd {
/// Initialise a new epoch folder.
Init(InitCmd),
/// Gives a very simple status.
Status(StatusCmd),
/// Advance or query the current epoch.
#[command(subcommand)]
Epoch(EpochCmd),
@ -147,5 +149,6 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
&cmd,
&lib_efo::stats::EntityType::Blocker,
),
TopLevelCmd::Status(cmd) => commands::status::status(&cmd),
}
}

View File

@ -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())
}

View File

@ -13,11 +13,11 @@ 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"
[dev-dependencies]
insta = {workspace = true}
tempfile = "3.23.0"

View File

@ -13,14 +13,13 @@
use std::str::FromStr;
use clap::ValueEnum;
use derive_more::{Add, Display, Sub};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{
error::EpochError,
stats::{EntityType, MetaStats, OverallStats},
stats::{self, EntityType, MetaStats, OverallStats, Symbols, TypedLink},
};
pub mod implementations;
@ -81,6 +80,40 @@ pub struct Entity {
/// Limits that clamp any stat changes caused by the entity's effect.
effect_bounds: EffectBounds,
}
impl Entity {
/// Iterate over all the links and do the appropriate action
pub fn remove_all_links(
&self,
epoch_info: &mut crate::epoch::EpochInfo,
) -> Result<(), EpochError> {
for TypedLink {
other_id,
role,
other_type,
} in &self.metadata.links
{
let entity: &mut Entity =
epoch_info.find_entity_strict_as_mut(*other_id, Some(*other_type))?;
let id = match role {
stats::Role::Govern => entity.remove_governor().map(|i| *i),
stats::Role::Capital => entity.remove_capital().map(|i| *i),
stats::Role::Undefined => None,
};
// TODO: Add the other way cleaning, not useful for now but if ever links can be two way,
// it needs to be done
log::info!(
"Removed entity {}{} [{}] from {}{}{} -> {id:?}",
other_id.to_symbol(),
other_type.to_symbol(),
role.to_symbol(),
entity.name,
entity.id.to_symbol(),
entity.entity_type.to_symbol()
);
}
Ok(())
}
}
/// Limits for the maximum and minimum value that an effect may
/// modify a statistic. The bounds are applied after the effect has
@ -95,7 +128,7 @@ pub struct EffectBounds {
}
/// How the entity's effect is applied over time.
#[derive(Debug, Serialize, Deserialize, Clone, Default, ValueEnum)]
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
pub enum EffectApplication {
/// Repeatedly applied every turn while the entity is present.
Recurring,
@ -115,7 +148,7 @@ impl FromStr for EffectApplication {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
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),
@ -125,7 +158,7 @@ impl FromStr for EffectApplication {
"todo" => Ok(EffectApplication::PermanentEffectToApply),
_ => Err(EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "The argument could't be made into a EffectApplication",
while_parsing: "EffectApplication",
}),
}
}

View File

@ -1,42 +1,43 @@
//! Implementation of all needed traits for the Entity struct
mod from_impl;
use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
use cli_table::{Style, WithTitle};
use colored::*;
use rand::distr::Distribution;
use uuid::Uuid; // [3] - colored-rs examples
use std::hash::Hash;
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration};
use crate::epoch::epoch_traits::Diffable;
use crate::error::EpochError;
use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols};
use crate::utils::RngLevel;
use crate::{Displayable, items_table};
use crate::{
Displayable,
entity::Entity,
epoch::{EpochInfo, epoch_traits::Diffable},
stats::{self, Symbols},
};
use colored::*;
use uuid::Uuid; // [3] - colored-rs examples
mod accesors;
mod methods;
// ---------- Implementation ----------
impl Displayable for Entity {
// Detailed multi-line view (used e.g. in logs)
fn print_full(&self) {
println!("{}", self.to_pretty_tree(),);
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.to_pretty_tree(epoch_info),);
if let Ok(c) = self.stats_to_table() {
println!("{c}");
}
}
/// One-liner used for auto-generation of `Vec<T>` displays
// TODO: URGENT: Change this display
fn oneline_display(&self) -> String {
let capital = self
.metadata
.capital
.as_ref()
.map(|c| format!("{} ", c.to_symbol()).green())
.map(|c| format!("Capital: {} ", c.to_symbol().blue()))
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!(" 󰻾[{:>2}]", g).red())
.map(|g| format!("Governor:  {}", g.to_symbol().blue()))
.unwrap_or_default();
let prestige = if *self.metadata.prestige > 0 {
@ -74,260 +75,17 @@ impl Displayable for Entity {
}
}
impl Entity {
// Display the entity's statistics in a pretty table.
///
/// The table contains both the permanent and temporary statistics of the
/// entity. The table is formatted with a custom border and separator
/// using the `cli_table` crate.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn full_stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![&self.stats, t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
///
fn stat_to_table(
&self,
items: Vec<&OverallStats>,
) -> Result<cli_table::TableDisplay, EpochError> {
items_table!(items, self.name.clone(), self.id)
}
/// Pretty-print the entity as a coloured tree.
///
/// The output is a `String` that visualises the entity's metadata, type,
/// duration, effect bounds, and any links. Colours are applied using
/// `colored::Colorize`.
///
/// # Returns
/// A `String` containing the formatted tree.
pub fn to_pretty_tree(&self) -> String {
// Helper that prefixes a line with the correct amount of vertical bars.
fn indent(level: usize, line: &str) -> String {
let bars = "│ ".repeat(level);
format!(" {}{}", bars, line)
}
let mut out = String::new();
// ── Top line: <entity_type> <name>
out.push_str(&format!(
"[{} {} 󰻾[{}]]\n",
self.entity_type.to_symbol().blue().bold(),
self.name.cyan().bold(),
self.id.to_string().blue().bold()
));
// ── Metadata section
out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green())));
if self.metadata.capital.is_some() {
out.push_str(&indent(
1,
&format!(
"├─ {}: {:?}\n",
"capital".bright_green(),
self.metadata
.capital
.map(|c| c.to_symbol())
.unwrap_or_default()
),
));
}
if *self.metadata.prestige > 0 {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}\n",
"prestige".bright_green(),
self.metadata.prestige
),
));
}
out.push_str(&indent(
1,
&format!(
"└─ {}: {}\n",
"position".bright_green(),
self.metadata.position.to_symbol()
),
));
// ── Optional links
if !self.metadata.links.is_empty() {
out.push_str(&indent(0, &format!("├─ {}\n", "links".green())));
for (i, link) in self.metadata.links.iter().enumerate() {
let last = i == self.metadata.links.len() - 1;
let symbol = if last { "└─" } else { "├─" };
out.push_str(&indent(
1,
&format!("{} {}\n", symbol, link.to_symbol().yellow()),
));
}
}
// ── Other top-level fields
out.push_str(&indent(
0,
&format!(
"├─ {}: {}\n",
"duration".green(),
self.duration.to_symbol().yellow()
),
));
out.push_str(&indent(
0,
&format!("├─ {}: {:?}\n", "effect_nature".green(), self.effect_nature),
));
out.push_str(&indent(
0,
&format!(
"└─ {}: {}",
"effect_bounds".green(),
self.effect_bounds.to_symbol()
),
));
out
}
/// Create an entity using a specific RNG level.
///
/// The entity is initialised with random statistics, a random position,
/// and a random prestige value derived from the supplied `RngLevel`.
///
/// # Arguments
/// * `e_type` - The type of entity to create.
/// * `rng` - The RNG level to use when generating random values.
///
/// # Returns
/// * `Ok(Self)` - The newly created entity.
/// * `Err(EpochError)` - Propagated from any randomisation failure.
///
pub fn create_rng(e_type: &EntityType, rng: &RngLevel) -> Result<Self, EpochError> {
let mut r = rand::rng();
Ok(Self {
id: Uuid::new_v4(),
stats: OverallStats::create_rng(rng, &mut r)?,
temp_stats: None,
metadata: MetaStats {
prestige: GenericStat(rng.to_rng()?.sample(&mut r) as isize),
position: Position::create_rng(&mut r)?,
..Default::default()
},
entity_type: e_type.clone(),
..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(&mut self, pair: StatPair) {
overwrite_stat(&mut self.stats, pair);
}
/// 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.
pub fn delta_stat(&mut self, pair: StatPair) {
add_to_stat(&mut self.stats, pair);
}
/// 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
}
/// 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))
.map(|e| e.to_symbol())
.unwrap_or(format!(
"{}{} is missing {}",
"".red(),
id.to_symbol().red(),
e_type.clone().to_shortest().blue()
))
}
// impl Entity {
@ -339,20 +97,27 @@ impl Entity {
///
/// This function performs a direct overwrite: the existing value is
/// discarded and the new value from `pair` is written in its place.
fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
/// Add a delta to a statistic in `stats`.
///
/// The delta in `pair.value` is added to the current statistic value
/// using `saturating_add`, so that the result never overflows the
/// underlying integer type.
fn add_to_stat(stats: &mut OverallStats, pair: StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = GenericStat(current_value.saturating_add(*pair.value));
#[inline]
fn overwrite_stat(
stats: &mut stats::OverallStats,
pair: stats::StatPair,
delta: stats::Modification,
) {
match delta {
stats::Modification::Delta => {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = stats::GenericStat(current_value.saturating_add(*pair.value));
}
stats::Modification::Replace => {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
stats::Modification::Delete => {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = stats::GenericStat::default();
}
}
}
/// Compare a field on `self` with the same field on `other`.
@ -381,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(),
@ -391,7 +156,7 @@ impl Diffable for Entity {
}
}
impl Diffable for Option<OverallStats> {
impl Diffable for Option<stats::OverallStats> {
fn delta(&self, other: &Self) -> Self {
match (self, other) {
(None, None) => None,
@ -402,7 +167,7 @@ impl Diffable for Option<OverallStats> {
}
}
impl Diffable for MetaStats {
impl Diffable for stats::MetaStats {
fn delta(&self, other: &Self) -> Self {
diff_fields!(self, other, capital, governor);
Self {
@ -424,6 +189,61 @@ impl Diffable for MetaStats {
.filter(|t1| other.links.iter().any(|t2| t1 == t2))
.collect(),
prestige: self.prestige - other.prestige,
reach: stats::Reach::None,
}
}
}
impl stats::Symbols for Entity {
fn to_symbol(&self) -> String {
format!(
"{} {} {}",
self.entity_type.to_symbol().blue(),
self.id.to_symbol().blue(),
self.name
)
}
}
impl stats::Symbols for Uuid {
fn to_symbol(&self) -> String {
format!("󰻾[{}]", self.to_string().split_at(7).0)
}
fn to_shortest(&self) -> String {
self.to_string().split_at(7).0.to_string()
}
}
impl Hash for Entity {
/// Massive speedup at the cost of collision on updates, making eq for finding but not true equality
/// However a .deep_eq() should be used for this
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// self.name.hash(state);
// self.description.hash(state);
self.id.hash(state);
// self.stats.hash(state);
// self.temp_stats.hash(state);
// self.metadata.hash(state);
// self.entity_type.hash(state);
// self.duration.hash(state);
// self.effect_nature.hash(state);
// self.effect_bounds.hash(state);
}
}
impl PartialEq for Entity {
/// Time save and clash if not .deep_eq
fn eq(&self, other: &Self) -> bool {
// self.name == other.name
// && self.description == other.description
self.id == other.id
// && self.stats == other.stats
// && self.temp_stats == other.temp_stats
// && self.metadata == other.metadata
// && self.entity_type == other.entity_type
// && self.duration == other.duration
// && self.effect_nature == other.effect_nature
// && self.effect_bounds == other.effect_bounds
}
}

View File

@ -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<stats::FactionId>) {
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<stats::CharacterId> {
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<stats::CharacterId> {
self.metadata.governor.take()
}
/// Add a governor to the entity if the id exists
pub fn change_capital(&mut self, capital: stats::TownId) -> Option<stats::TownId> {
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<stats::TownId> {
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<EntityIdentifier>) -> 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,
}
}
}

View File

@ -0,0 +1,286 @@
//! # Entity Methods
//!
//! This module implements the public API of the `Entity` struct.
//! The API covers:
//! 1. **Statistical reporting** – pretty tables and pretty‑printed trees.
//! 2. **Metadata manipulation** – links, links, governor/capital, prestige, etc.
//! 3. **Stat modification** – strict, fuzzy, delta, and randomised changes.
//! 4. **Entity creation** – deterministic or RNG‑based.
//! 5. **Utility helpers** – position handling, identifier matching.
use cli_table::{Style, WithTitle};
use colored::*;
use rand::distr::Distribution;
use crate::{
entity::*,
epoch::EpochInfo,
error::EpochError,
items_table,
stats::{self, Symbols},
utils::RngLevel,
};
use uuid::Uuid;
impl Entity {
// Display the entity's statistics in a pretty table.
///
/// The table contains both the permanent and temporary statistics of the
/// entity. The table is formatted with a custom border and separator
/// using the `cli_table` crate.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn full_stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![&self.stats, t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Adds a link (UUID) to the entity's metadata.
///
/// If `id_to_add` is already present in the `links` vector, this method does
/// nothing - it silently ignores duplicates. The method is idempotent: calling
/// it repeatedly with the same UUID will not change the underlying state.
pub fn add_to_links(&mut self, id_to_add: stats::TypedLink) {
if !self.metadata.links.contains(&id_to_add) {
self.metadata.links.push(id_to_add);
}
}
/// Removes a link (UUID) from the entity's metadata.
///
/// If the supplied `id_to_remove` exists in `self.metadata.links`, it is
/// removed and returned wrapped in `Some`. If the UUID is not present,
/// the method returns `None` and leaves the link list unchanged.
pub fn del_from_links(&mut self, id_to_remove: stats::TypedLink) -> Option<stats::TypedLink> {
self.metadata
.links
.iter()
.position(|id| *id == id_to_remove)
.map(|pos| self.metadata.links.swap_remove(pos))
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
pub fn stats_to_table(&self) -> Result<cli_table::TableDisplay, EpochError> {
let items = if let Some(t) = &self.temp_stats {
vec![t]
} else {
vec![&self.stats]
};
self.stat_to_table(items)
}
/// Reset the temporary stats to a given base value.
///
/// Useful before performing an update: you can set the temporary stats to
/// whatever snapshot you want to start from (or `None` to clear it).
pub fn reset_temporary_stats_to(&mut self, other: Option<OverallStats>) {
self.temp_stats = other;
}
/// Return an immutable reference to the entity’s live statistics.
pub fn get_stats(&self) -> &OverallStats {
&self.stats
}
/// Return an immutable reference to the temporary statistics snapshot,
/// if one is currently stored.
pub fn get_temp_stats(&self) -> &Option<OverallStats> {
&self.temp_stats
}
/// Display the entity's statistics in a pretty table (same format as
/// `full_stats_to_table`).
///
/// This method is provided for backward compatibility and forwards all
/// work to `full_stats_to_table`.
///
/// # Returns
/// A `Result` containing the table display on success, or an `EpochError` if the
/// conversion to a table string fails.
///
pub(crate) fn stat_to_table(
&self,
items: Vec<&OverallStats>,
) -> Result<cli_table::TableDisplay, EpochError> {
items_table!(items, self.name.clone(), self.id)
}
/// Pretty-print the entity as a coloured tree.
///
/// The output is a `String` that visualises the entity's metadata, type,
/// duration, effect bounds, and any links. Colours are applied using
/// `colored::Colorize`.
///
/// # Returns
/// A `String` containing the formatted tree.
pub fn to_pretty_tree(&self, epoch_info: &EpochInfo) -> String {
// Helper that prefixes a line with the correct amount of vertical bars.
pub(crate) fn indent(level: usize, line: &str) -> String {
let bars = "│ ".repeat(level);
format!(" {}{}", bars, line)
}
let mut out = String::new();
out.push_str(&format!(
"[{} {} 󰻾[{}]]\n",
self.entity_type.to_symbol().blue().bold(),
self.name.cyan().bold(),
self.id.to_string().blue().bold()
));
// ── Metadata section
out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green())));
if let Some(capital) = self.metadata.capital {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}\n",
"capital".bright_green(),
implementations::uuid_to_symbol(*capital, epoch_info, &EntityType::Town)
),
));
}
if let Some(faction) = self.metadata.faction {
out.push_str(&indent(
1,
&format!(
"├─ {} : {}{}\n",
"faction".bright_green(),
"".yellow(),
faction.to_string().yellow(),
),
));
}
if let Some(governor) = self.metadata.governor {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}\n",
"governor".bright_green(),
implementations::uuid_to_symbol(*governor, epoch_info, &EntityType::Character)
),
));
}
if *self.metadata.prestige > 0 {
out.push_str(&indent(
1,
&format!(
"├─ {}: {}{}\n",
"prestige".bright_green(),
self.metadata.prestige.to_string().yellow(),
"".yellow()
),
));
}
out.push_str(&indent(
1,
&format!(
"└─ {}: {}\n",
"position".bright_green(),
self.metadata.position.to_symbol()
),
));
// ── Optional links
if !self.metadata.links.is_empty() {
out.push_str(&indent(0, &format!("├─ {}\n", "links".green())));
for (i, link) in self.metadata.links.iter().enumerate() {
let last = i == self.metadata.links.len() - 1;
let symbol = if last { "└─" } else { "├─" };
out.push_str(&indent(
1,
&format!(
"{} {}\n",
symbol,
implementations::uuid_to_symbol(
link.other_id,
epoch_info,
&link.other_type
)
.yellow()
),
));
}
}
// ── Other top-level fields
out.push_str(&indent(
0,
&format!(
"├─ {}: {}\n",
"duration".green(),
self.duration.to_symbol().yellow()
),
));
out.push_str(&indent(
0,
&format!("├─ {}: {:?}\n", "effect_nature".green(), self.effect_nature),
));
out.push_str(&indent(
0,
&format!(
"└─ {}: {}",
"effect_bounds".green(),
self.effect_bounds.to_symbol()
),
));
out
}
/// Create an entity using a specific RNG level.
///
/// The entity is initialised with random statistics, a random position,
/// and a random prestige value derived from the supplied `RngLevel`.
///
/// # Arguments
/// * `e_type` - The type of entity to create.
/// * `rng` - The RNG level to use when generating random values.
///
/// # Returns
/// * `Ok(Self)` - The newly created entity.
/// * `Err(EpochError)` - Propagated from any randomisation failure.
///
pub fn create_rng(e_type: &EntityType, rng: &RngLevel) -> Result<Self, EpochError> {
let mut r = rand::rng();
Ok(Self {
id: Uuid::new_v4(),
stats: OverallStats::create_rng(rng, &mut r)?,
temp_stats: None,
metadata: MetaStats {
prestige: stats::GenericStat(rng.to_rng()?.sample(&mut r) as isize),
position: stats::Position::create_rng(&mut r)?,
..Default::default()
},
entity_type: *e_type,
..Default::default()
})
}
/// 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))
}
}
EntityDuration::Done => (),
}
}
}

View File

@ -0,0 +1,14 @@
---
source: lib_efo/src/entity/test.rs
expression: collect
---
recurring = Ok(Recurring)
when_present_wh = Ok(WhenPresent)
when_present_present = Ok(WhenPresent)
when_present_toap = Ok(WhenPresent)
when_present_appl = Ok(WhenPresent)
permanent_effect_applied_done = Ok(PermanentEffectApplied)
permanent_effect_applied_ok = Ok(PermanentEffectApplied)
permanent_effect_to_apply = Ok(PermanentEffectToApply)
parse_error = Err(ParsingArgument { argument_parsed: "unknown", while_parsing: "EffectApplication" })

View File

@ -0,0 +1,50 @@
---
source: lib_efo/src/entity/test.rs
expression: dump_entity(&e)
---
{
"name": "JBE Zorg",
"description": "Another description",
"id": "00000000-0000-0000-0000-000000000001",
"stats": {
"demographics": 0,
"population": 14,
"growth_rate": 0,
"crime": 0,
"happiness": 0,
"economy": 0,
"food": 0,
"industry": 0,
"science": 0,
"trade": 0,
"military": 0,
"army": 0,
"strength": 0,
"fortification": 0,
"threat": 0,
"infrastructure": 0,
"bureaucracy": 0,
"transportation": 0,
"sprawl": 0,
"health": 0
},
"metadata": {
"position": [
6000,
40000
],
"capital": null,
"governor": null,
"faction": 42,
"links": [],
"prestige": 30,
"reach": "Global"
},
"entity_type": "Event",
"duration": "Done",
"effect_nature": "Recurring",
"effect_bounds": {
"min": 0,
"max": 0
}
}

View File

@ -0,0 +1,50 @@
---
source: lib_efo/src/entity/test.rs
expression: dump_entity(&e)
---
{
"name": "JBE Zorg",
"description": "Another description",
"id": "00000000-0000-0000-0000-000000000001",
"stats": {
"demographics": 0,
"population": 14,
"growth_rate": 0,
"crime": 0,
"happiness": 0,
"economy": 0,
"food": 0,
"industry": 0,
"science": 0,
"trade": 0,
"military": 0,
"army": 0,
"strength": 0,
"fortification": 0,
"threat": 0,
"infrastructure": 0,
"bureaucracy": 0,
"transportation": 0,
"sprawl": 0,
"health": 0
},
"metadata": {
"position": [
6000,
40000
],
"capital": "ffffffff-ffff-ffff-ffff-ffffffffffff",
"governor": "00000000-0000-0000-0000-000000000000",
"faction": 42,
"links": [],
"prestige": 30,
"reach": "Global"
},
"entity_type": "Event",
"duration": "Done",
"effect_nature": "Recurring",
"effect_bounds": {
"min": 0,
"max": 0
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/entity/test.rs
expression: result
---
Ok(
Recurring,
)

View File

@ -81,6 +81,7 @@ Entity {
prestige: GenericStat(
0,
),
reach: None,
},
entity_type: Event,
duration: Done,

View File

@ -145,13 +145,16 @@ Entity {
),
),
links: [
TownId(
00000000-0000-0000-0000-000000000079,
),
TypedLink {
other_id: 79000000-0000-0000-0000-000000000000,
role: Govern,
other_type: Character,
},
],
prestige: GenericStat(
0,
),
reach: None,
},
entity_type: Town,
duration: Permanent,

View File

@ -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,

View File

@ -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,

View File

@ -1,14 +1,18 @@
---
source: lib_efo/src/entity/test.rs
expression: e.to_pretty_tree()
expression: e.to_pretty_tree(&epoch_info)
---
[ Hero 󰻾[0c000000-0000-0000-0000-000000000000]]
├─ metadata
│ ├─ capital: "\u{f0efe}[0000000]"
│ ├─ prestige: 3
│ ├─ capital:  󰻾[7c00000] Bobpital
│ ├─ faction :  2
│ ├─ governor:  󰻾[0b00000] is missing [C]
│ ├─ prestige: 3
│ └─ position: ( 2, 4)⚓
├─ links
│ └─ 󰻾[0000000]
│ ├─  󰻾[bc04000] is missing [T]
│ ├─  󰻾[7900000] Bobtown
│ └─  󰻾[7900000] Bobtown
├─ duration: ⧗10
├─ effect_nature: Recurring
└─ effect_bounds: (1 ⭾ 5)

View File

@ -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]
│ └─ Capital:  󰻾[7c00000] Governor:  󰻾[0b00000]
│

View File

@ -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,
}

View File

@ -15,11 +15,14 @@ MetaStats {
),
),
links: [
TownId(
00000000-0000-0000-0000-000000000002,
),
TypedLink {
other_id: 02000000-0000-0000-0000-000000000000,
role: Govern,
other_type: Character,
},
],
prestige: GenericStat(
0,
),
reach: None,
}

View File

@ -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,
}

View File

@ -81,6 +81,7 @@ Entity {
prestige: GenericStat(
0,
),
reach: None,
},
entity_type: Event,
duration: Duration(

View File

@ -81,6 +81,7 @@ Entity {
prestige: GenericStat(
0,
),
reach: None,
},
entity_type: Event,
duration: Done,

View File

@ -81,6 +81,7 @@ Entity {
prestige: GenericStat(
0,
),
reach: None,
},
entity_type: Event,
duration: Done,

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/entity/test.rs
expression: result
---
Ok(
WhenPresent,
)

View File

@ -1,17 +1,21 @@
// tests/mod.rs - or put this inside your crate's tests module
#![allow(unused_imports)]
use crate::stats::{ListStats, PositionGrid};
use std::arch::x86_64::_mm256_mask_inserti64x2;
use std::str::FromStr;
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier};
use crate::epoch::epoch_traits::Diffable;
use crate::epoch::{EpochInfo, epoch_info};
use crate::error::EpochError;
use crate::stats::{self, EntityType, MetaStats, Position, StatPair, TownId};
use crate::stats::{self, EntityType, MetaStats, Position, StatPair, TownId, TypedLink};
use std::io::Write;
use super::*;
use crate::Displayable;
use insta::assert_snapshot;
use cli_table::Cell;
use insta::{assert_debug_snapshot, assert_snapshot};
use uuid::Uuid;
#[test]
@ -232,12 +236,29 @@ 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(124))),
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![
stats::TypedLink::new(
Uuid::from_u128_le(1212),
stats::Role::Capital,
EntityType::Town,
),
stats::TypedLink::new(
Uuid::from_u128_le(121),
stats::Role::Capital,
EntityType::Town,
),
stats::TypedLink::new(
Uuid::from_u128_le(121),
stats::Role::Capital,
EntityType::Town,
),
],
reach: stats::Reach::Global,
},
duration: EntityDuration::Duration(10),
effect_nature: EffectApplication::Recurring,
@ -263,8 +284,21 @@ fn effect_bound_testing() {
fn snapshot_full_oneline_display() {
init_snapshot_env();
let e = full_entity();
let mut epoch_info = EpochInfo::default();
let e2 = Entity {
id: Uuid::from_u128_le(121),
name: "Bobtown".to_string(),
..Default::default()
};
let e3 = Entity {
id: Uuid::from_u128_le(124),
name: "Bobpital".to_string(),
..Default::default()
};
epoch_info.towns.push(e2);
epoch_info.towns.push(e3);
assert_snapshot!(e.oneline_display());
assert_snapshot!(e.to_pretty_tree());
assert_snapshot!(e.to_pretty_tree(&epoch_info));
}
#[test]
@ -272,7 +306,7 @@ fn snapshot_minimal_oneline_display() {
init_snapshot_env();
let e = Entity::default();
assert_snapshot!(e.oneline_display());
assert_snapshot!(e.to_pretty_tree());
assert_snapshot!(e.to_pretty_tree(&EpochInfo::default()));
}
#[test]
@ -290,7 +324,7 @@ fn snapshot_print_full_output() {
// // Temporarily swap the real stdout for our buffer.
// let original = std::mem::replace(&mut handle, &mut buffer);
// Run the method we want to snapshot.
e.print_full();
e.print_full(&EpochInfo::default());
// Restore the original stdout.
// std::mem::replace(&mut handle, original);
}
@ -334,10 +368,13 @@ fn snapshot_overwrite_stat() {
let mut entity = Entity::default();
let stats = OverallStats::linear(0);
entity.stats = stats;
entity.change_stat(StatPair {
stat: stats::ListStats::Population,
value: stats::GenericStat(33),
});
entity.change_stat_strict(
StatPair {
stat: stats::ListStats::Population,
value: stats::GenericStat(33),
},
stats::Modification::Replace,
);
assert_snapshot!(format!("{:#?}", entity.stats));
}
@ -370,11 +407,16 @@ 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![TypedLink::new(
Uuid::from_u128_le(141),
stats::Role::Govern,
EntityType::Character,
)],
prestige: stats::GenericStat(3),
reach: stats::Reach::Local(12),
},
entity_type: EntityType::Monster,
duration: EntityDuration::Permanent,
@ -390,11 +432,16 @@ 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![TypedLink::new(
Uuid::from_u128_le(121),
stats::Role::Govern,
EntityType::Character,
)],
prestige: stats::GenericStat(5),
reach: stats::Reach::Faction(stats::FactionId(2)),
},
entity_type: EntityType::Town,
duration: EntityDuration::Permanent,
@ -455,28 +502,43 @@ 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![TypedLink::new(
Uuid::from_u128_le(12),
stats::Role::Govern,
EntityType::Character,
)],
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![TypedLink::new(
Uuid::from_u128_le(42),
stats::Role::Govern,
EntityType::Character,
)],
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![TypedLink::new(
Uuid::from_u128_le(2),
stats::Role::Govern,
EntityType::Character,
)],
prestige: stats::GenericStat(1),
reach: stats::Reach::Faction(stats::FactionId(12)),
};
let delta = meta1.delta(&meta2);
@ -493,7 +555,10 @@ fn snapshot_delta_stat_positive() {
init_snapshot_env();
let mut e = Entity::default();
e.delta_stat(StatPair::from_str("health:4").unwrap());
e.change_stat_strict(
StatPair::from_str("health:4").unwrap(),
stats::Modification::Delta,
);
e.id = Uuid::nil();
assert_snapshot!(format!("{:#?}", e));
@ -542,3 +607,131 @@ fn test_rng() {
Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Mixed).unwrap();
Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Flawed).unwrap();
}
/// All the inputs we want to test, in the same order the original
/// `match` evaluates them. The key is the snapshot name, the
/// value is the input string.
const TEST_CASES: &[(&str, &str)] = &[
("recurring", "re"),
("when_present_wh", "wh"),
("when_present_present", "present"),
("when_present_toap", "toap"),
("when_present_appl", "appl"),
("permanent_effect_applied_done", "done"),
("permanent_effect_applied_ok", "ok"),
("permanent_effect_to_apply", "todo"),
("parse_error", "unknown"),
];
#[test]
fn effect_application_from_str_snapshots() {
let mut collect = String::new();
for (snapshot_name, input) in TEST_CASES {
let result: Result<EffectApplication, EpochError> =
<crate::entity::EffectApplication>::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
/// Helper that prints a “nice”, deterministic view of the entity.
/// It uses `serde_json::to_string_pretty` so that every run has the same ordering.
fn dump_entity(e: &Entity) -> String {
// We purposely ignore `temp_stats` because it is marked `#[serde(skip)]`
// and we want deterministic snapshots.
serde_json::to_string_pretty(e).expect("JSON should be serialisable")
}
#[test]
fn test_entity_lifecycle() {
// --------------------------------------------------------------------
// 1️⃣ Create a brand‑new entity (all fields default)
// --------------------------------------------------------------------
let mut e = Entity {
name: "JBE Zorg".into(),
description: "A test entity".into(),
id: Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap(),
duration: EntityDuration::default(),
..Default::default()
};
e.change_description("A brand new description".into());
e.change_duration(EntityDuration::default());
e.modify_description("Another description".into());
let pos = Position::from((30, 200));
e.modify_position(pos.clone());
assert_eq!(pos.distance(e.position()), 0);
e.modify_position_grid(PositionGrid::from((30, 200)));
e.modify_prestige(stats::GenericStat(18), stats::Modification::Replace);
e.modify_prestige(stats::GenericStat(12), stats::Modification::Delta);
e.modify_reach(stats::Reach::Global);
e.modify_faction(Some(stats::FactionId::from(42)));
let link = TypedLink {
other_id: Uuid::from_u128_le(21),
role: stats::Role::Govern,
other_type: EntityType::Character,
};
e.add_to_links(link);
let link_dup = link; // same value, will be ignored
e.add_to_links(link_dup);
let removed = e.del_from_links(link);
assert_eq!(removed, Some(link));
assert!(e.del_from_links(link).is_none());
e.change_stat_strict(
StatPair {
stat: ListStats::Population,
value: stats::GenericStat(10),
},
stats::Modification::Replace,
);
e.change_stat_fuzzy(
StatPair {
stat: ListStats::Population,
value: stats::GenericStat(4),
},
stats::Modification::Delta,
);
e.modify_effect_application(EffectApplication::Recurring);
e.modify_effect_bounds(EffectBounds::default());
let governor = stats::CharacterId(Uuid::nil());
e.change_governor(governor);
let capital = TownId(Uuid::max());
e.change_capital(capital);
assert_snapshot!("entity_lifecycle: start", dump_entity(&e));
assert_eq!(e.remove_capital(), Some(capital));
assert_eq!(e.remove_capital(), None);
assert_eq!(e.remove_governor(), Some(governor));
assert_eq!(e.remove_governor(), None);
assert_snapshot!("entity_lifecycle: end", dump_entity(&e));
assert_debug_snapshot!(
"entity_lifecycle: table",
e.stats_to_table().map(|t| t.to_string())
);
}
#[test]
fn name_prefix_match() {
let e = Entity {
name: "AlphaBetaGamma".into(),
id: Uuid::parse_str("12345678-1234-5678-1234-567812345678").unwrap(),
..Entity::default() // fill the rest with defaults
};
let ident = Some(EntityIdentifier::Name("Alpha".into()));
assert!(e.match_identifier(&ident), "Name prefix should match");
let ident = Some(EntityIdentifier::Name("Beta".into()));
assert!(!e.match_identifier(&ident), "Name prefix should NOT match");
let ident = Some(EntityIdentifier::Id("1234".into()));
assert!(e.match_identifier(&ident), "ID prefix should match");
let ident = Some(EntityIdentifier::Id("9999".into()));
assert!(!e.match_identifier(&ident), "ID prefix should NOT match");
assert!(!e.match_identifier(&None), "None should return false");
}

View File

@ -41,7 +41,7 @@ static SUBFOLDER_NAMING: &str = "epoch";
/// The main name of the epoch
static MAIN_NAME: &str = ".epoch";
/// The subname of the epochinfo
static SUB_NAME: &str = ".epochinfo";
static SUB_NAME: &str = "epochinfo.json";
/// A lightweight wrapper around a list of tags.
///
@ -165,3 +165,82 @@ impl FromStr for EpochIdentifier {
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod test {
use insta::assert_debug_snapshot;
// tests/epoch.rs
use serde_json::to_string_pretty;
use crate::epoch::{EpochId, EpochIdentifier, SaveMode, TagList};
#[test]
fn epoch_id_arithmetic() {
let id = EpochId::new(42);
assert_eq!(*id, 42);
let next = id.next();
assert_eq!(*next, 43);
let added = id.add_to_epoch(5);
assert_eq!(*added, 47);
let negative = id.add_to_epoch(-10);
assert_eq!(*negative, 32);
// saturating behaviour
let zero = EpochId::new(0);
let under = zero.add_to_epoch(-1);
assert_eq!(*under, 0);
}
#[test]
fn epoch_identifier_parsing() {
// numeric string → Id
let parsed: EpochIdentifier = "7".parse().unwrap();
assert!(matches!(parsed, EpochIdentifier::Id(_)));
// non-empty string → Tag
let parsed: EpochIdentifier = "winter-b".parse().unwrap();
assert!(matches!(parsed, EpochIdentifier::Tag(_)));
// empty string → error
assert!("".parse::<EpochIdentifier>().is_err());
}
#[test]
fn epoch_identifier_serialisation() {
// Id variant should serialize to a number
let id = EpochIdentifier::Id(EpochId::new(13));
let json = to_string_pretty(&id).unwrap();
assert_debug_snapshot!("epoch_identifier_id", json);
// Tag variant should serialize to a string
let tag = EpochIdentifier::Tag("alpha".into());
let json = to_string_pretty(&tag).unwrap();
assert_debug_snapshot!("epoch_identifier_tag", json);
}
#[test]
fn tag_list_deref_and_mut() {
let mut list = TagList::new();
list.push("one".into());
list.push("two".into());
// Deref to Vec<String>
assert_eq!(list[0], "one");
assert_eq!(list[1], "two");
// Mutating through DerefMut
list[1] = "TWO".into();
assert_eq!(list[1], "TWO");
}
#[test]
fn save_mode_variants() {
// Just a quick check that the variants exist and can be constructed
let _do_not = SaveMode::DoNotErase;
let _erase = SaveMode::Erase;
}
}

View File

@ -11,11 +11,11 @@
//! directories and are **not** part of this file.
use crate::{
entity::Entity,
epoch::{
EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode,
EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, TagList,
epoch_traits::ConfigWritable,
},
stats,
};
use std::{
collections::HashMap,
@ -25,7 +25,6 @@ use std::{
use log::{info, warn};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::{epoch::epoch_traits::Prettiable, error::EpochError};
@ -106,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::<EpochId>()?;
info!("Initialized {:?}", id);
info!("Preloaded Epoch {:?}", id);
self.list_existing_epochs.insert(id, None);
}
}
@ -143,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);
@ -305,15 +305,71 @@ impl EpochConfig {
/// with the ID immediately following the current one. The actual logic
/// is deferred to the `EpochInfo -> World` subsystem.
pub fn compute_next(&mut self) -> Result<EpochInfo, EpochError> {
// unimplemented!()
// 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
/// * The caller must guarantee that the current epoch is **loaded** and
/// its storage is still valid for the duration of the call.
/// * The function performs raw pointer arithmetic / `unsafe` reads/writes
/// on the internal data structures. No other thread may be mutably
/// borrowing the same data at the same time.
pub unsafe fn update_all_temporary_values(&mut self) {}
/// Reset **all** temporary values to the current live values.
///
/// # Safety
/// * The caller must ensure that the current epoch is loaded and that
/// no other mutable references to the same data exist.
/// * This method writes directly into the entity structs; any concurrent
/// access will lead to undefined behaviour.
pub unsafe fn reset_temporary_stats(&mut self) -> Result<(), EpochError> {
let current_epoch = self.try_load_current_as_mut()?;
current_epoch
.vec_entities_mut(&stats::EntityType::Town)
.iter_mut()
.for_each(|entity| entity.reset_temporary_stats_to(Some(entity.get_stats().clone())));
Ok(())
}
/// Update temporary values for every entity assuming the current epoch
/// is loaded.
///
/// # Safety
/// * Same as `update_all_temporary_values`: the current epoch must be
/// loaded and no other mutable references may exist.
pub unsafe fn update_temps(&mut self) {}
/// Insert a new epoch into the configuration and persist it.
///
/// The function creates the epoch's directory, writes its metadata,
@ -368,43 +424,6 @@ impl EpochConfig {
println!("{}", EpochInfo::as_table(items_to_log)?);
Ok(())
}
/// 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.
///
/// # Safety
/// The caller must guarantee that the epoch identified by `self.epoch_id`
/// has already been loaded into memory (for example by calling
/// `try_load` first). The function performs an unchecked reference
/// conversion via `try_load_id`; invoking it when the epoch is not
/// cached results in **undefined behaviour**.
///
/// # 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.
///
#[allow(dead_code)]
unsafe fn find_entity(&self, id: Uuid) -> Result<&Entity, EpochError> {
let epoch_info = unsafe { self.try_load_id(self.epoch_id) }?;
let predicate = |entity: &&Entity| entity.id == 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))
}
}
impl ConfigWritable for EpochConfig {

View File

@ -10,14 +10,16 @@ use cli_table::Table;
use derive_more::Display;
use serde::{Deserialize, Serialize};
use std::fs::create_dir_all;
use uuid::Uuid;
use crate::{
entity::Entity,
entity::{Entity, EntityIdentifier},
epoch::{
EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList,
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
stats::{EntityType, Position, PositionIdentifier, TypedLink},
};
/// The metadata file stored inside each epoch directory
@ -115,3 +117,264 @@ impl ConfigWritable for EpochInfo {
format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
}
}
impl EpochInfo {
/// 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.
pub fn find_entity_of_type(
&self,
entity_to_find: &Option<EntityIdentifier>,
e_type: &EntityType,
) -> Result<&Entity, EpochError> {
self.vec_entities(e_type)
.iter()
.find(|&entity| entity.match_identifier(entity_to_find))
.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.
pub fn add_to_links(
&mut self,
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(target_t)
.iter_mut()
.find(|entity| entity.id == target_id)
.ok_or(EpochError::EntityNotFoundById(
EntityIdentifier::Id(target_id.to_string()),
Some(*target_t),
))?;
e.add_to_links(link_back);
Ok(())
}
/// Removes a link from an entity inside the epoch.
///
/// The removal is performed on the *target* entity (`id_to_add_to`). If the
/// target entity cannot be found, an `EpochError::EntityNotFoundById` error
/// is returned. The removal itself is delegated to the entity's
/// `del_from_links` method, which silently ignores missing links.
pub fn del_from_links(
&mut self,
target_id: Uuid,
target_t: &EntityType,
link_back: TypedLink,
) -> Result<(), EpochError> {
let e = self
.vec_entities_mut(target_t)
.iter_mut()
.find(|entity| entity.id == target_id)
.ok_or(EpochError::EntityNotFoundById(
EntityIdentifier::Id(target_id.to_string()),
Some(*target_t),
))?;
e.del_from_links(link_back);
Ok(())
}
/// 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.
pub fn find_any_entity(&self, id: EntityIdentifier) -> Result<&Entity, EpochError> {
let predicate = |entity: &&Entity| match &id {
EntityIdentifier::Name(name) => {
entity.name.to_lowercase().starts_with(&name.to_lowercase())
}
EntityIdentifier::Id(id) => entity.id.to_string().starts_with(id),
};
self.events
.iter()
.find(predicate)
.or(self.characters.iter().find(predicate))
.or(self.towns.iter().find(predicate))
.or(self.blockers.iter().find(predicate))
.or(self.calamities.iter().find(predicate))
.ok_or(EpochError::EntityNotFoundById(id, None))
}
/// Find an entity from an Uuid
pub fn find_entity_strict(
&self,
id: Uuid,
strict: Option<EntityType>,
) -> Result<&Entity, EpochError> {
let predicate = |entity: &&Entity| entity.id == id;
if let Some(e_type) = strict {
self.vec_entities(&e_type)
.iter()
.find(|entity| entity.id == id)
.ok_or(EpochError::EntityNotFound(
e_type,
Some(EntityIdentifier::Id(id.to_string())),
))
} else {
self.events
.iter()
.find(predicate)
.or(self.characters.iter().find(predicate))
.or(self.towns.iter().find(predicate))
.or(self.blockers.iter().find(predicate))
.or(self.calamities.iter().find(predicate))
.ok_or(EpochError::EntityNotFound(
EntityType::Player,
Some(EntityIdentifier::Id(id.to_string())),
))
}
}
/// Find an entity from an Uuid
// TODO: Siplify this with the better iterator
pub fn find_entity_strict_as_mut(
&mut self,
id: Uuid,
strict: Option<EntityType>,
) -> Result<&mut Entity, EpochError> {
let predicate = |entity: &&mut Entity| entity.id == id;
if let Some(e_type) = strict {
self.vec_entities_mut(&e_type)
.iter_mut()
.find(|entity| entity.id == id)
.ok_or(EpochError::EntityNotFound(
e_type,
Some(EntityIdentifier::Id(id.to_string())),
))
} else {
self.events
.iter_mut()
.find(predicate)
.or(self.characters.iter_mut().find(predicate))
.or(self.towns.iter_mut().find(predicate))
.or(self.blockers.iter_mut().find(predicate))
.or(self.calamities.iter_mut().find(predicate))
.ok_or(EpochError::EntityNotFound(
EntityType::Player,
Some(EntityIdentifier::Id(id.to_string())),
))
}
}
/// 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.
pub fn vec_entities(&self, e_type: &EntityType) -> &Vec<Entity> {
match e_type {
EntityType::Character => &self.characters,
EntityType::Player => unimplemented!("No players for now"),
EntityType::Town => &self.towns,
EntityType::Monster => &self.calamities,
EntityType::Blocker => &self.blockers,
EntityType::Event => &self.events,
}
}
/// Removes an entity from the epoch's collection and returns it.
///
/// The function looks up the entity that matches the supplied `entity_identifier`
/// in the collection corresponding to `e_type`. If the entity is found, it
/// is removed using `swap_remove` and returned. When the entity cannot be
/// located, an `EpochError::EntityNotFound` is returned.
pub fn remove_entity(
&mut self,
entity_identifier: &Option<EntityIdentifier>,
e_type: &EntityType,
) -> Result<Entity, EpochError> {
let vec_entities: &mut Vec<Entity> = self.vec_entities_mut(e_type);
let index = vec_entities
.iter()
.position(|entity| entity.match_identifier(entity_identifier))
.ok_or(EpochError::EntityNotFound(
*e_type,
entity_identifier.clone(),
))?;
let entity = vec_entities.swap_remove(index);
Ok(entity)
}
/// 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!()`.
pub fn vec_entities_mut(&mut self, e_type: &EntityType) -> &mut Vec<Entity> {
match e_type {
EntityType::Character => &mut self.characters,
EntityType::Player => unimplemented!("No players for now"),
EntityType::Town => &mut self.towns,
EntityType::Monster => &mut self.calamities,
EntityType::Blocker => &mut self.blockers,
EntityType::Event => &mut self.events,
}
}
/// 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<Item = &mut Entity> {
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<Position, EpochError> {
Ok(match position {
PositionIdentifier::Exact(pos) => pos.clone(),
PositionIdentifier::Grid(pos) => pos.to_position(),
PositionIdentifier::Id(ident) => {
self.find_any_entity(ident.clone())?.position().clone()
}
})
}
/// Swap an entity with an updated one
pub fn swap_entity(&mut self, entity: Entity) -> Result<Entity, EpochError> {
// Get a mutable reference to the vector that holds the entities of `e_type`
let entities = self.vec_entities_mut(&entity.entity_type);
// Locate the index of the entity that we want to replace
let idx_opt = entities.iter().position(|e| e.id == entity.id);
match idx_opt {
Some(idx) => {
// Replace the old entity with the new one, returning the old entity
Ok(std::mem::replace(&mut entities[idx], entity))
}
None => Err(EpochError::EntityNotFound(
entity.entity_type,
Some(EntityIdentifier::Id(entity.id.to_string())),
)),
}
}
}

View File

@ -5,10 +5,7 @@
//! common to many of the library's element types.
#![warn(clippy::missing_docs_in_private_items)]
use cli_table::{
Style, Table, WithTitle,
format::{Border, HorizontalLine, Separator, VerticalLine},
};
use cli_table::{Style, Table, WithTitle};
use serde::Serialize;
use std::{fmt::Display, fs::File, io::Write};
use uuid::Uuid;
@ -108,3 +105,127 @@ pub trait ConfigWritable: Serialize {
Ok(())
}
}
#[allow(clippy::unwrap_used)]
#[cfg(test)]
mod tests {
use super::*;
use derive_more::Display;
use insta::assert_snapshot;
use tempfile::tempdir;
/// A tiny helper struct that implements every trait you defined.
#[derive(Debug, Clone, PartialEq, Serialize, Table, Display)]
#[display("{id}:{value}")]
struct DummyItem {
id: Uuid,
value: i32,
#[serde(skip)]
#[table(skip)]
save: String,
}
impl DummyItem {
fn new(value: i32) -> Self {
Self {
id: Uuid::nil(),
value,
save: tempdir()
.expect("Tempdir")
.path()
.join("dummy.json")
.to_string_lossy()
.into(),
}
}
}
impl Diffable for DummyItem {
fn delta(&self, other: &Self) -> Self {
Self {
id: self.id, // keep the same id
value: self.value - other.value,
save: self.save.clone(),
}
}
}
// impl Applyable for DummyItem {}
// impl Nextable for DummyItem {}
impl Prettiable for DummyItem {}
/* ------------------- ConfigWritable ------------------- */
impl ConfigWritable for DummyItem {
fn save_path(&self) -> String {
self.save.clone()
}
fn save_folder(&self) -> String {
String::new()
}
}
#[test]
fn test_prettiable_as_table() {
let item = DummyItem::new(42);
let table = DummyItem::as_table(vec![&item]).expect("Dummytable");
assert_snapshot!(format!("{}", table));
}
#[test]
fn test_prettiable_show_as_log() {
DummyItem::new(7).show_as_log();
}
#[test]
fn test_config_writable_as_json() {
let item = DummyItem::new(123);
let json = item.as_json("test action".into()).unwrap();
assert_snapshot!(json);
}
// fn dummy_with_tempfile(value: i32) -> (DummyItem, std::path::PathBuf) {
// let dummy = DummyItem::new(value);
// (dummy.clone(), dummy.save.clone().into())
// }
// #[test]
// fn test_config_writable_save_with_context_erase() {
// let (item, path) = dummy_with_tempfile(10);
// // Erase: we expect a file to be created (or overwritten)
// item.save_with_context("Erase test", &SaveMode::DoNotErase)
// .unwrap();
// // Verify file contents
// let mut file = File::open(&path).unwrap();
// let mut contents = String::new();
// file.read_to_string(&mut contents).unwrap();
// assert_snapshot!(contents);
// }
// #[test]
// fn test_config_writable_save_with_context_donot_erase() {
// let (item, _path) = dummy_with_tempfile(20);
// // First write - must succeed
// item.save_with_context("DoNotErase test 1", &SaveMode::DoNotErase)
// .unwrap();
// // Second write - should fail with `ConfigCreation` because the file
// // already exists.
// let err = item
// .save_with_context("DoNotErase test 2", &SaveMode::DoNotErase)
// .unwrap_err();
// assert_snapshot!(format!("{}", err));
// }
#[test]
fn test_diffable_delta() {
let a = DummyItem::new(30);
let b = DummyItem::new(15);
let diff = a.delta(&b);
assert_eq!(diff.value, 15);
assert_eq!(diff.id, a.id); // same id
}
}

View File

@ -0,0 +1,8 @@
---
source: lib_efo/src/epoch/epoch_traits.rs
expression: json
---
{
"id": "00000000-0000-0000-0000-000000000000",
"value": 123
}

View File

@ -0,0 +1,10 @@
---
source: lib_efo/src/epoch/epoch_traits.rs
expression: "format!(\"{}\", table)"
---
┌──────────────────────────────────────┬───────┐
│ id  │ value │
├──────────────────────────────────────┼───────┤
│ 00000000-0000-0000-0000-000000000000 │ 42  │
└──────────────────────────────────────┴───────┘


View File

@ -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.
@ -249,12 +253,12 @@ pub enum EpochError {
EpochHashingImpossible(&'static str, u32),
/// The entity with id **`{0}`** could not be found.
#[error("Entity of type with id {0:?} not found")]
#[error("Entity of type {1:?} with id {0:?} not found")]
#[diagnostic(code(epoch::entity_not_found_by_id))]
#[diagnostic(help(
"Verify that the identifier is correct and that the entity exists in the current epoch."
))]
EntityNotFoundById(Uuid),
EntityNotFoundById(EntityIdentifier, Option<EntityType>),
/// The entity could not be found
#[error("Entity of type {0:?} with name {1:?} not found")]
@ -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<String>,
},
}
/// A small enum of explicit user-facing error messages.

View File

@ -9,6 +9,8 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
#![deny(clippy::unwrap_used)]
use crate::epoch::EpochInfo;
#[macro_use]
#[allow(unused_assignments)]
pub mod error;
@ -18,33 +20,33 @@ pub mod naming;
pub mod stats;
pub mod utils;
use std::io::Result as IoResult;
// use std::io::Result as IoResult;
/// Marker trait for anything that can be persisted via the `Store<T>` abstraction.
///
/// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the
/// compiler can infer that the type is both serialisable *and* deserialisable.
pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {}
impl<T> Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {}
// /// Marker trait for anything that can be persisted via the `Store<T>` abstraction.
// ///
// /// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the
// /// compiler can infer that the type is both serialisable *and* deserialisable.
// pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {}
// impl<T> Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {}
/// The generic store. All domain entities that need persistence should use this trait.
/// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`.
pub trait Store<T>
where
T: Persistable,
{
/// Read a value identified by `id`.
fn read(&self, id: &str) -> IoResult<Option<T>>;
// /// The generic store. All domain entities that need persistence should use this trait.
// /// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`.
// pub trait Store<T>
// where
// T: Persistable,
// {
// /// Read a value identified by `id`.
// fn read(&self, id: &str) -> IoResult<Option<T>>;
/// Write (or overwrite) a value identified by `id`.
fn write(&self, id: &str, value: &T) -> IoResult<()>;
// /// Write (or overwrite) a value identified by `id`.
// fn write(&self, id: &str, value: &T) -> IoResult<()>;
/// Delete the value identified by `id`.
fn delete(&self, id: &str) -> IoResult<()>;
// /// Delete the value identified by `id`.
// fn delete(&self, id: &str) -> IoResult<()>;
/// List all ids known to this store.
fn list_ids(&self) -> IoResult<Vec<String>>;
}
// /// List all ids known to this store.
// fn list_ids(&self) -> IoResult<Vec<String>>;
// }
/// A trait for types that can be displayed in a command-line tool.
///
/// Implementors should provide three levels of representation:
@ -60,24 +62,19 @@ where
/// directly on a vector of displayable items.
pub trait Displayable {
/// Return a fully-described string representation.
fn print_full(&self) {
self.print_short()
fn print_full(&self, epoch_info: &EpochInfo) {
println!("{}", self.short_display(epoch_info));
}
/// Return a short, user-friendly string.
fn print_short(&self) {
println!("{}", self.oneline_display())
/// Return a short, user-friendly string. Resolves Ids
fn short_display(&self, _epoch_info: &EpochInfo) -> String {
self.oneline_display()
}
/// Return a one-liner string, suitable for embedding in a collection
/// representation (e.g. a `Vec<T>`). Implementations should avoid
/// new-lines to keep the output usable in a single line context.
fn oneline_display(&self) -> String;
/// Print oneline
fn print_oneline(&self) {
println!("{}", self.oneline_display())
}
}
/// Implement `Displayable` for vectors of displayable items.
@ -87,12 +84,15 @@ pub trait Displayable {
/// already implements `Displayable`. This is a **blanket implementation**,
/// so you do not need to write a manual impl for each concrete type
impl<T: Displayable> Displayable for Vec<T> {
fn print_full(&self) {
self.iter().for_each(|e| e.print_full());
fn print_full(&self, epoch_info: &EpochInfo) {
self.iter().for_each(|e| e.print_full(epoch_info));
}
fn print_short(&self) {
self.iter().for_each(|e| e.print_short());
fn short_display(&self, epoch_info: &EpochInfo) -> String {
self.iter()
.map(|e| e.short_display(epoch_info))
.collect::<Vec<String>>()
.join("\n")
}
fn oneline_display(&self) -> String {
@ -100,6 +100,43 @@ impl<T: Displayable> Displayable for Vec<T> {
self.iter()
.map(|x| x.oneline_display())
.collect::<Vec<_>>()
.join(",")
.join("\n")
}
}
// tests/api.rs --------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use insta::assert_snapshot;
struct Dummy {
name: String,
}
impl Displayable for Dummy {
fn oneline_display(&self) -> String {
self.name.clone()
}
}
#[test]
fn test_displayable_vec() {
let vec = vec![
Dummy {
name: "Alice".to_string(),
},
Dummy {
name: "Bob".to_string(),
},
Dummy {
name: "Eve".to_string(),
},
];
let efo = EpochInfo::default();
vec.print_full(&efo);
vec.short_display(&efo);
assert_snapshot!("dummy_vec_oneline", vec.oneline_display());
assert_snapshot!("dummy_vec_oneline", vec.short_display(&efo));
}
}

View File

@ -1,20 +1,17 @@
//! Autonaming generator
//! Supposed to be loaded with the world if needed
use crate::stats::Symbols;
use once_cell::sync::Lazy;
use rand::prelude::*;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::{
fs, io,
path::{Path, PathBuf},
};
use crate::Displayable;
use crate::entity::EffectApplication;
use crate::entity::EffectBounds;
use crate::entity::EntityDuration;
use crate::entity::{EffectApplication, EffectBounds, EntityDuration};
use crate::error::EpochError;
use crate::stats::EntityType;
use crate::stats::StatPair;
use crate::stats::{EntityType, StatPair, Symbols};
/// The structure that holds everything we need for name generation.
#[derive(Debug, Serialize, Deserialize, Default)]

View File

@ -0,0 +1,5 @@
---
source: lib_efo/src/epoch.rs
expression: json
---
"{\n \"id\": 13\n}"

View File

@ -0,0 +1,5 @@
---
source: lib_efo/src/epoch.rs
expression: json
---
"\"alpha\""

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/lib.rs
expression: vec.short_display(&efo)
---
Alice
Bob
Eve

View File

@ -10,11 +10,11 @@
//! * **Source** - Formula or function that generates the stat value.
#![deny(clippy::missing_docs_in_private_items)]
#![allow(dead_code)]
use crate::{error::EpochError, thin_newtype, utils::RngLevel};
use crate::{entity::EntityIdentifier, error::EpochError, thin_newtype, utils::RngLevel};
use cli_table::{CellStruct, Color, Style, Table};
use colored::Colorize;
use derive_more::{Add, Display, Sub};
use derive_more::{Add, Display, Mul, Sub};
use rand::{Rng, distr::Distribution, rngs::ThreadRng};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@ -391,13 +391,7 @@ pub struct MetaStats {
/// UIDs of all entities the entity is linked to (roads, trade routes,
/// alliances, war declarations, etc.).
///
/// **Purpose** - Connectivity network.
/// **Effect** - Influences economic, military, and diplomatic
/// interactions.
/// **Source** - `links = Vec<Uuid>` collected from the entity's
/// network manager.
pub links: Vec<TownId>,
pub links: Vec<TypedLink>,
/// Prestige / reputation of the entity in the eyes of the empire
/// and foreign powers.
@ -407,6 +401,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
@ -421,35 +420,82 @@ pub struct StatPair {
pub value: GenericStat,
}
/// Structure used to indicate position, possess nice helper methods to use as is in the program
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub)]
/// A two-dimensional point on the world map.
///
/// The struct is a thin wrapper around a pair of `isize` values
/// representing the X and Y coordinates.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
pub struct Position(isize, isize);
/// The grid size, as a static like a degenerate
/// A grid-aligned position used for chunk look-ups.
///
/// A `PositionGrid` stores the coordinates of a chunk in the world
/// grid. Each component is the index of the chunk in the X and Y
/// direction.
#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub, Mul)]
pub struct PositionGrid(isize, isize);
/// The size of the whole world in pixels.
///
/// These constants are internal to the module; they are not part
/// of the public API.
// TODO(9): Change to be at least initialized with the world ?
const GRID_SIZE: (i32, i32) = (1920, 1080);
/// The size the map is divided into
/// The size of one world chunk in pixels.
const CHUNK_SIZE: isize = 200;
impl Position {
/// The euclidian distance between two points
fn distance(&self, other: &Self) -> isize {
((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt()
/// Calculates the Euclidean distance between two points.
///
/// The distance is computed in the 2-D Euclidean space.
pub fn distance(&self, other: &Self) -> isize {
((self.0 - other.0).pow(2) + (self.1 - other.1).pow(2)).isqrt()
}
/// The position in grid coordinates
fn to_grid_distance(&self) -> (isize, isize) {
(self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
/// Converts this point to its corresponding grid position.
///
/// The conversion divides the world coordinates by the
/// `CHUNK_SIZE` to obtain the chunk indices.
pub fn to_grid_distance(&self) -> PositionGrid {
PositionGrid(self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
}
/// Create a random position
/// None that there is no concept to either city or continent making this position rather unrelyable
/// Returns the inner tuple representation of the position.
///
/// This is a convenience method to obtain the raw `(isize, isize)`
/// coordinates without wrapping them in the struct.
pub fn to_inner(&self) -> (isize, isize) {
(self.0, self.1)
}
/// Generates a random position within the world bounds.
///
/// The position is chosen uniformly at random using the supplied
/// random number generator.
pub fn create_rng(r: &mut ThreadRng) -> Result<Self, EpochError> {
let x = r.random_range(0..GRID_SIZE.0);
let y = r.random_range(0..GRID_SIZE.1);
Ok(Self(x as isize, y as isize))
}
}
impl PositionGrid {
/// Calculates the Euclidean distance between two grid positions.
///
/// The distance is computed by converting both grid positions to
/// world coordinates and then using `Position::distance`.
pub fn distance(&self, other: &PositionGrid) -> isize {
self.to_position().distance(&other.to_position())
}
/// Converts the grid coordinates to world coordinates.
///
/// Each component is multiplied by `CHUNK_SIZE` to obtain the
/// corresponding world position.
pub fn to_position(&self) -> Position {
Position(CHUNK_SIZE * self.0, CHUNK_SIZE * self.1)
}
}
/// A summary of the stats, only for display purposes
#[allow(clippy::missing_docs_in_private_items)]
#[derive(Table)]
@ -512,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,
@ -542,9 +588,62 @@ 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]);
#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)]
/// A typed link between two entities.
///
/// A link is a lightweight association that ties an entity's **identifier**
/// (`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("{}{}({}{})",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 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(other_id: Uuid, role: Role, other_type: EntityType) -> Self {
Self {
other_id,
role,
other_type,
}
}
}
#[derive(Copy, Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Display, Default)]
/// Semantic role of a link.
///
/// The role encodes *what the link represents* in the model. The
/// variants are intentionally limited to the most common use-cases,
/// but the enum can be extended if the domain evolves.
pub enum Role {
/// The linked entity has governing authority over the link owner
Govern,
/// The linked entity is the capital of the link owner
Capital,
#[default]
/// No role has been assigned.
Undefined,
}
// --- TRAITS ---------------------------------------------------------------
/// A stat is a *game value* that can be converted to two different
/// normalised ranges - a 100-point range for “gaming” logic and a
@ -593,3 +692,77 @@ pub trait Accessible {
/// `None` if the key does not exist.
fn get_val(&self, key: &str) -> Option<Box<dyn GameStat>>;
}
/// Represents a position that can be identified in three different ways.
///
/// The string format is deliberately simple and is designed to be easy to write
/// by hand while still being unambiguous to a machine.
///
/// | Variant | Syntax in a string |
/// |---------|--------------------|
/// | `Exact` | `X,Y` |
/// | `Grid` | `~X,Y` or `gX,Y` |
/// | `Id` | `@{uuid}` |
#[derive(Debug, Clone)]
pub enum PositionIdentifier {
/// Exact position specified as `X,Y`.
Exact(Position),
/// Grid-aligned position specified as `~X,Y` or `gX,Y`.
Grid(PositionGrid),
/// 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,
}
/// A description of how a value should be updated.
///
/// The enum is intentionally tiny – only the three actions that
/// matter in our state‑diff engine. Each variant is documented
/// with a short, practical example so you know exactly when
/// you’d pick it.
///
/// The enum is `Copy`, so you can freely pass it around without
/// ownership worries. The `From<&str>` implementation below
/// lets you read the operation name from configuration files or
/// CLI flags:
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Modification {
/// The modification will be a *delta*, i.e. an increment.
///
/// For numeric values this is equivalent to adding the new
/// value to the existing one. For collections it usually
/// means “append”.
Delta,
/// The modification will *replace* the existing value.
///
/// This is a hard overwrite: the old value is dropped
/// entirely and the new one is written in its place.
Replace,
/// The modification will *reset* the underlying value.
///
/// For plain types this is typically a default/zero value.
/// For `Option<T>` it sets the field to `None`. It can
/// also be interpreted as “delete the field entirely”.
Delete,
}

View File

@ -1,15 +1,9 @@
//! All traits implementatition for the main structs are deffered here
#![allow(dead_code)]
use crate::stats::{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::{GameStat, GenericStat, ListStats, OverallStats};
mod from_impl;
mod symb_impl;
/// Generates an `impl GameStat for <TYPE>` 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<Self, Self::Err> {
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),
"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<ListStats> 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,192 +176,17 @@ 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<FactionId> {
fn to_symbol(&self) -> String {
if let Some(faction) = self {
format!("{faction}")
} else {
"Ø".to_string()
}
}
}
impl Symbols for TownId {
fn to_symbol(&self) -> String {
format!("󰻾[{}]", self.0.to_string().split_at(7).0)
}
fn to_shortest(&self) -> String {
self.0.to_string().split_at(7).0.to_string()
}
}
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<Self, Self::Err> {
// Trim whitespace just in case and attempt to parse.
let inner = s
.trim()
.parse::<usize>()
.map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "The argument could't be made into a 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`,
/// …). You can optionally provide an extra list of derives – e.g. `Add`,
/// `Sub`, `FromStr`, or any custom derive – by writing:
/// …). You can optionally provide an extra list of derives - e.g. `Add`,
/// `Sub`, `FromStr`, or any custom derive - by writing:
/// ```
/// # use lib_efo::thin_newtype;
/// use derive_more::{Add, Sub};
/// thin_newtype!(MyInt, i32, derives: [Add, Sub]);
/// ```
/// (you’ll need the corresponding crates – e.g. `derive_more` for `Add`, `Sub`).
/// (you'll need the corresponding crates - e.g. `derive_more` for `Add`, `Sub`).
#[macro_export]
macro_rules! thin_newtype {
/* ---- no custom derives ------------------------------------------------- */
@ -542,7 +293,6 @@ macro_rules! thin_newtype {
}
};
}
mod from_impl;
#[cfg(test)]
pub(crate) mod test;

View File

@ -1,8 +1,9 @@
//! All from implementations
use crate::stats::FactionId;
use crate::{
error::EpochError,
stats::{self, ListStats, Position, StatPair},
stats::{self, GenericStat, ListStats, Position, PositionGrid, PositionIdentifier, StatPair},
};
use std::str::FromStr;
@ -68,8 +69,258 @@ impl std::str::FromStr for Position {
}
}
/// Parse a string into a `PositionGrid`.
///
/// The string is expected to contain two signed integers separated by a comma,
/// optionally surrounded by whitespace. Each component is trimmed before
/// parsing, so leading and trailing whitespace is ignored.
///
/// The parsing logic is the same as for `Position`:
/// * Split on the comma; there must be exactly one comma.
/// * Trim each component and parse it as an `isize`.
/// * Convert the resulting `Position` to a grid distance with
/// `Position::to_grid_distance`.
///
/// # Errors
///
/// * `EpochError::InvalidPositionFormat` - the string does not contain
/// exactly one comma or there are not exactly two components.
/// * `EpochError::ParsePositionError` - one of the components cannot be
/// parsed as an `isize`. (These errors come from the underlying `Position`
/// implementation.)
impl std::str::FromStr for PositionGrid {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<Position>().map(|p| PositionGrid(p.0, p.1))
}
}
impl FromStr for PositionIdentifier {
type Err = EpochError;
/// Parses a string into one of the three variants.
///
/// The parsing rules are described in the table above.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let s = s.trim();
if let Some(_rest) = s.find('@') {
let id = s.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::EpochId",
})?;
return Ok(Self::Id(id));
}
if let Some(rest) = s.strip_prefix('~').or_else(|| s.strip_prefix('g')) {
let grid = rest.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::PositionGrid",
})?;
return Ok(Self::Grid(grid));
}
let exact = s.parse().map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_string(),
while_parsing: "PositionIdentifier::Position",
})?;
Ok(Self::Exact(exact))
}
}
/// Convert a tuple of two signed integers into a `Position`.
///
/// This implementation simply wraps the `(isize, isize)` tuple into a
/// `Position` struct. It is equivalent to `Position(x, y)` where `x` is the
/// first element and `y` is the second.
impl From<(isize, isize)> for Position {
fn from(value: (isize, isize)) -> Self {
Self(value.0, value.1)
}
}
/// Convert a tuple of two signed integers into a `PositionGrid`.
///
/// This implementation simply wraps the `(isize, isize)` tuple into a
/// `Position` struct. It is equivalent to `Position(x, y)` where `x` is the
/// first element and `y` is the second.
impl From<(isize, isize)> for PositionGrid {
fn from(value: (isize, isize)) -> Self {
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<Self, Self::Err> {
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",
})
}
}
impl FromStr for GenericStat {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.parse::<isize>()
.map_err(|_| EpochError::ParsingArgument {
argument_parsed: s.to_owned(),
while_parsing: "GenericStat",
})
.map(Self)
}
}
impl std::str::FromStr for stats::Modification {
type Err = EpochError; // placeholder – you can make a custom error
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_ascii_lowercase().as_str() {
w if w.starts_with("delt") => Ok(stats::Modification::Delta),
"add" => Ok(stats::Modification::Delta),
w if w.starts_with("repl") => Ok(stats::Modification::Replace),
"change" => Ok(stats::Modification::Replace),
w if w.starts_with("del") => Ok(stats::Modification::Delete),
_ => Err(EpochError::ParsingArgument {
argument_parsed: s.to_owned(),
while_parsing: "Modification",
}), // trick: convert a bad string into a ParseIntError
}
}
}
impl From<bool> for stats::Modification {
fn from(value: bool) -> Self {
match value {
true => stats::Modification::Delta,
false => stats::Modification::Replace,
}
}
}
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<Self, Self::Err> {
// Trim whitespace just in case and attempt to parse.
let inner = s
.trim()
.parse::<usize>()
.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<Self, Self::Err> {
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<ListStats> 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",
}
}
}

View File

@ -0,0 +1,8 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
valid_positive = Ok(GenericStat(42))
valid_negative = Ok(GenericStat(-7))
invalid_non_numeric = Err(ParsingArgument { argument_parsed: "foo", while_parsing: "GenericStat" })

View File

@ -0,0 +1,39 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: tests
---
[
(
"delta",
Ok(
Delta,
),
),
(
"repl",
Ok(
Replace,
),
),
(
"del",
Ok(
Delete,
),
),
(
"add",
Ok(
Delta,
),
),
(
"unknown",
Err(
ParsingArgument {
argument_parsed: "unknown",
while_parsing: "Modification",
},
),
),
]

View File

@ -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`",
},
)

View File

@ -0,0 +1,11 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Faction(
FactionId(
3,
),
),
)

View File

@ -0,0 +1,11 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Faction(
FactionId(
42,
),
),
)

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Global,
)

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Global,
)

View File

@ -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`",
},
)

View File

@ -0,0 +1,9 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Local(
5,
),
)

View File

@ -0,0 +1,9 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
Local(
12,
),
)

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
None,
)

View File

@ -0,0 +1,7 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Ok(
None,
)

View File

@ -0,0 +1,10 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: parsed
---
Err(
ParsingArgument {
argument_parsed: "unknown",
while_parsing: "Unknown error",
},
)

View File

@ -0,0 +1,9 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
valid_comma_separated = Ok(PositionGrid(3, 4))
valid_larger_numbers = Ok(PositionGrid(10, 20))
invalid_non_numeric = Err(ParsePositionError("a,b"))
invalid_wrong_separator = Err(InvalidPositionFormat("3 4"))

View File

@ -0,0 +1,13 @@
---
source: lib_efo/src/stats/implementations/test.rs
expression: collect
---
id_valid = Ok(Id(Name("42@epoch")))
id_invalid_non_numeric = Ok(Id(Name("foo@bar")))
grid_tilde = Ok(Grid(PositionGrid(3, 4)))
grid_g = Ok(Grid(PositionGrid(5, 6)))
grid_invalid_bad_prefix = Err(ParsingArgument { argument_parsed: "~bad,grid", while_parsing: "PositionIdentifier::PositionGrid" })
exact_valid = Ok(Exact(Position(7, 8)))
exact_invalid_non_numeric = Err(ParsingArgument { argument_parsed: "x,y", while_parsing: "PositionIdentifier::Position" })
invalid_no_delimiter = Err(ParsingArgument { argument_parsed: "3-4", while_parsing: "PositionIdentifier::Position" })

View File

@ -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<FactionId> {
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()
}
}

View File

@ -1,16 +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::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.
@ -18,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();
@ -41,136 +46,186 @@ 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 = stats::StatPair::from_str("justastring").unwrap_err();
assert!(matches!(err, EpochError::IllFormedStatQualifier(_)));
// 2️⃣ Separator but missing the value
let err = stats::StatPair::from_str("cri:").unwrap_err();
assert!(matches!(err, EpochError::IllFormedStatQualifier(_)));
// 3️⃣ Separator but missing the stat name
let err = stats::StatPair::from_str(":10").unwrap_err();
assert!(matches!(err, EpochError::UnknownStatAcronim(_)));
// 4️⃣ Two spaces (splits into > 2 parts)
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 = 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 = 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 = stats::Position::from_str("123 456").unwrap_err();
assert!(matches!(err, EpochError::InvalidPositionFormat(_)));
// 2️⃣ Too many commas
let err = stats::Position::from_str("1,2,3").unwrap_err();
assert!(matches!(err, EpochError::InvalidPositionFormat(_)));
// 3️⃣ Leading/trailing comma
let err = stats::Position::from_str(",5").unwrap_err();
assert!(matches!(err, EpochError::ParsePositionError(_)));
let err = stats::Position::from_str("5,").unwrap_err();
assert!(matches!(err, EpochError::ParsePositionError(_)));
// 4️⃣ Non-integer components
let err = stats::Position::from_str("x,5").unwrap_err();
assert!(matches!(err, EpochError::ParsePositionError(_)));
let err = stats::Position::from_str("5,y").unwrap_err();
assert!(matches!(err, EpochError::ParsePositionError(_)));
}
#[test]
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::<ListStats>().unwrap();
let val = alias.parse::<stats::ListStats>().unwrap();
s.get_field_mut_from_str(val.into());
assert_eq!(
val, expected_variant,
@ -197,7 +252,7 @@ fn test_liststats_unknown_alias() {
let unknown = "unknown_stat_123";
// Verify the error type and payload directly.
let err = unknown.parse::<ListStats>().unwrap_err();
let err = unknown.parse::<stats::ListStats>().unwrap_err();
match err {
EpochError::UnknownStatAcronim(msg) => {
assert_eq!(msg, unknown);
@ -209,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()))
@ -224,19 +279,19 @@ fn test_entity_type_to_shortest() {
}
// ---------------------------------------------------------------------------
// EntityType – already tested by your existing example
// EntityType - already tested by your existing example
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// EffectApplication – one line per variant
// EffectApplication - one line per variant
// ---------------------------------------------------------------------------
#[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()))
@ -246,11 +301,11 @@ fn test_effect_application_to_symbol() {
}
// ---------------------------------------------------------------------------
// Position – two variants, tested for both `to_symbol` and `to_shortest`
// Position - two variants, tested for both `to_symbol` and `to_shortest`
// ---------------------------------------------------------------------------
#[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::<Vec<String>>()
@ -259,7 +314,7 @@ fn test_position_to_symbol() {
}
// ---------------------------------------------------------------------------
// EntityDuration – one line per variant
// EntityDuration - one line per variant
// ---------------------------------------------------------------------------
#[test]
fn test_entity_duration_to_symbol() {
@ -272,3 +327,96 @@ 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::<stats::Reach>();
// `assert_debug_snapshot!` will serialize the `Result`
// (Ok or Err) using its `Debug` impl.
assert_debug_snapshot!(format!("parse_{}", input), parsed);
}
}
#[test]
fn generic_stat_from_str_snapshots() {
let test_cases = [
("valid_positive", "42"),
("valid_negative", "-7"),
("invalid_non_numeric", "foo"),
];
let mut collect = String::new();
for (snapshot_name, input) in test_cases {
let result: Result<stats::GenericStat, EpochError> = stats::GenericStat::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn position_grid_from_str_snapshots() {
let mut collect = String::new();
let test_cases = [
("valid_comma_separated", "3,4"),
("valid_larger_numbers", "10,20"),
("invalid_non_numeric", "a,b"),
("invalid_wrong_separator", "3 4"),
];
for (snapshot_name, input) in test_cases {
let result: Result<stats::PositionGrid, EpochError> = stats::PositionGrid::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn position_identifier_from_str_snapshots() {
let test_cases = [
// ID‑variant
("id_valid", "42@epoch"),
("id_invalid_non_numeric", "foo@bar"),
// Grid‑variant
("grid_tilde", "~3,4"),
("grid_g", "g5,6"),
("grid_invalid_bad_prefix", "~bad,grid"),
// Exact‑variant
("exact_valid", "7,8"),
("exact_invalid_non_numeric", "x,y"),
// General invalid
("invalid_no_delimiter", "3-4"),
];
let mut collect = String::new();
for (snapshot_name, input) in test_cases {
let result: Result<stats::PositionIdentifier, EpochError> =
stats::PositionIdentifier::from_str(input);
collect = format!("{}\n{} = {:?}", collect, snapshot_name, result);
}
assert_snapshot!(collect);
}
#[test]
fn test_modification_from_str() {
let tests = [
("delta", "delta".parse::<stats::Modification>()),
("repl", "repl".parse::<stats::Modification>()),
("del", "del".parse::<stats::Modification>()),
("add", "add".parse::<stats::Modification>()),
("unknown", "unknown".parse::<stats::Modification>()),
];
assert_debug_snapshot!(tests);
}

View File

@ -31,6 +31,10 @@ pub enum RngLevel {
Mixed,
/// All non specified are either high or low
Flawed,
/// All non-specified values are apocalyptic
Apocaliptic,
/// All non-specified values are doomed
Doom,
}
impl RngLevel {
@ -43,7 +47,9 @@ impl RngLevel {
RngLevel::High => 20..50,
RngLevel::Legendary => 40..70,
RngLevel::Mixed => 0..70,
RngLevel::Flawed => 0..100,
RngLevel::Flawed => -20..30,
RngLevel::Apocaliptic => -50..30,
RngLevel::Doom => -70..40,
}
}
@ -57,10 +63,10 @@ impl RngLevel {
/// and return the rendered string.
///
/// # Parameters
/// * `$items` – A table builder that implements the `Table` trait
/// * `$items` - A table builder that implements the `Table` trait
/// (e.g. `Vec<Vec<...>>.into_table()`, `items.into_table()`, …).
/// * `$name` – The name that should be stored in `EpochError::TableStringConversionError`.
/// * `$id` – The id that should be stored in `EpochError::TableStringConversionError`.
/// * `$name` - The name that should be stored in `EpochError::TableStringConversionError`.
/// * `$id` - The id that should be stored in `EpochError::TableStringConversionError`.
#[macro_export]
macro_rules! items_table {
($items:expr, $name:expr, $id:expr) => {{
@ -68,17 +74,19 @@ macro_rules! items_table {
.with_title()
.bold(true)
.border(
Border::builder()
.top(HorizontalLine::new('┌', '┐', '┬', '─'))
.bottom(HorizontalLine::new('└', '┘', '┴', '─'))
.left(VerticalLine::new('│'))
.right(VerticalLine::new('│'))
cli_table::format::Border::builder()
.top(cli_table::format::HorizontalLine::new('┌', '┐', '┬', '─'))
.bottom(cli_table::format::HorizontalLine::new('└', '┘', '┴', '─'))
.left(cli_table::format::VerticalLine::new('│'))
.right(cli_table::format::VerticalLine::new('│'))
.build(),
)
.separator(
Separator::builder()
.column(Some(VerticalLine::new('│')))
.row(Some(HorizontalLine::new('├', '┤', '┼', '─')))
cli_table::format::Separator::builder()
.column(Some(cli_table::format::VerticalLine::new('│')))
.row(Some(cli_table::format::HorizontalLine::new(
'├', '┤', '┼', '─',
)))
.build(),
)
.display()