Adds a hashing function and refactors code
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-12-15 16:38:52 +01:00
parent 7b321e4568
commit 5541e657b8
4 changed files with 563 additions and 511 deletions

View File

@ -1,26 +1,16 @@
//! Implementation of all needed traits for the Entity struct
use std::ops::Add;
mod from_impl;
use std::cmp::{max, min};
use std::hash::Hash;
use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine};
use cli_table::{Style, WithTitle};
use colored::*;
use log::debug;
use rand::distr::Distribution;
use rand::seq::{IndexedRandom, IteratorRandom};
use uuid::Uuid; // [3] - colored-rs examples
use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier};
use crate::epoch::EpochInfo;
use crate::epoch::epoch_traits::Diffable;
use crate::error::EpochError;
use crate::stats::{
self, EntityType, FactionId, GenericStat, ListStats, MetaStats, OverallStats, Position,
PositionGrid, StatPair, Symbols, TypedLink,
use crate::{
Displayable,
entity::Entity,
epoch::{EpochInfo, epoch_traits::Diffable},
stats::{self, Symbols},
};
use crate::utils::RngLevel;
use crate::{Displayable, items_table};
use colored::*;
use uuid::Uuid; // [3] - colored-rs examples
mod methods;
// ---------- Implementation ----------
impl Displayable for Entity {
@ -84,480 +74,8 @@ 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)
}
/// 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<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)
}
/// 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.
// TODO: Deref ids
pub fn to_pretty_tree(&self, epoch_info: &EpochInfo) -> 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();
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(),
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(),
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,
uuid_to_symbol(link.id, epoch_info, &EntityType::Town).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_strict(&mut self, pair: StatPair) {
overwrite_stat(&mut self.stats, pair);
}
/// 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: StatPair, delta: bool) {
let stats_demo = [
ListStats::Population,
ListStats::Growthrate,
ListStats::Crime,
ListStats::Happiness,
];
let stats_eco = [
ListStats::Food,
ListStats::Industry,
ListStats::Science,
ListStats::Trade,
];
let stats_soc = [
ListStats::Culture,
ListStats::Education,
ListStats::Tourism,
ListStats::Influence,
];
let stats_mil = [
ListStats::Army,
ListStats::Strength,
ListStats::Fortification,
ListStats::Threat,
];
let stats_inf = [
ListStats::Bureaucracy,
ListStats::Transportation,
ListStats::Sprawl,
ListStats::Health,
];
match pair.stat {
ListStats::Demographics => self.change_random_stats_by(&stats_demo, pair.value, delta),
ListStats::Economy => self.change_random_stats_by(&stats_eco, pair.value, delta),
ListStats::Social => self.change_random_stats_by(&stats_soc, pair.value, delta),
ListStats::Military => self.change_random_stats_by(&stats_mil, pair.value, delta),
ListStats::Infrastructure => self.change_random_stats_by(&stats_inf, pair.value, delta),
_ => self.change_stat_strict(pair),
}
}
/// 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.
fn change_random_stats_by(
&mut self,
stats_demo: &[ListStats],
amount: GenericStat,
delta: bool,
) {
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) = (min(a, b), max(a, b));
let mut value = || GenericStat((a..b).choose(&mut r).unwrap_or(1));
stats.for_each(|stat| {
if delta {
self.delta_stat(StatPair {
stat: *stat,
value: value(),
});
} else {
self.change_stat_strict(StatPair {
stat: *stat,
value: value(),
})
}
});
}
/// 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
}
/// 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: 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<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: 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: GenericStat) {
self.metadata.prestige = prestige;
}
/// Adjusts the entity's prestige stat by adding a delta.
pub fn modify_prestige_by_delta(&mut self, prestige: GenericStat) {
self.metadata.prestige = self.metadata.prestige.add(prestige);
}
/// Add a governor to the entity if the id exists
pub fn change_governor(&mut self, governor: stats::CharacterId) {
debug!("Swapping the governor with {}", governor.to_symbol());
self.metadata.governor = Some(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) {
debug!("Swapping the capital with {}", capital.to_symbol());
self.metadata.capital = Some(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) -> &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.starts_with(name),
Some(EntityIdentifier::Id(id)) => self.id.hyphenated().to_string().starts_with(id),
None => false,
}
}
}
/// Short utility to make a symbol for an entity from it's Uuid
fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &EntityType) -> String {
fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &stats::EntityType) -> String {
epoch_info
.find_entity_strict(id, Some(e_type.clone()))
.map(|e| e.to_symbol())
@ -578,7 +96,7 @@ fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &EntityType) -> Stri
///
/// 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) {
fn overwrite_stat(stats: &mut stats::OverallStats, pair: stats::StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
*affected_stat = pair.value;
}
@ -588,10 +106,10 @@ fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) {
/// 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) {
fn add_to_stat(stats: &mut stats::OverallStats, pair: stats::StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = *affected_stat;
*affected_stat = GenericStat(current_value.saturating_add(*pair.value));
*affected_stat = stats::GenericStat(current_value.saturating_add(*pair.value));
}
/// Compare a field on `self` with the same field on `other`.
@ -630,7 +148,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,
@ -641,7 +159,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 {
@ -668,7 +186,7 @@ impl Diffable for MetaStats {
}
}
impl Symbols for Entity {
impl stats::Symbols for Entity {
fn to_symbol(&self) -> String {
format!(
"{} {} {}",
@ -679,7 +197,7 @@ impl Symbols for Entity {
}
}
impl Symbols for Uuid {
impl stats::Symbols for Uuid {
fn to_symbol(&self) -> String {
format!("󰻾[{}]", self.to_string().split_at(7).0)
}
@ -688,3 +206,36 @@ impl Symbols for Uuid {
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,502 @@
//! # 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 std::ops::Add;
use cli_table::{Style, WithTitle};
use colored::*;
use rand::{
distr::Distribution,
prelude::{IndexedRandom, IteratorRandom},
};
use crate::stats::Symbols;
use crate::{entity::*, epoch::EpochInfo, error::EpochError, items_table, stats, utils::RngLevel};
use log::debug;
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)
}
/// 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.
// TODO: Deref ids
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.id, epoch_info, &EntityType::Town)
.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.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_strict(&mut self, pair: stats::StatPair) {
implementations::overwrite_stat(&mut self.stats, pair);
}
/// 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: bool) {
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),
}
}
/// 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: bool,
) {
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| {
if delta {
self.delta_stat(stats::StatPair {
stat: *stat,
value: value(),
});
} else {
self.change_stat_strict(stats::StatPair {
stat: *stat,
value: value(),
})
}
});
}
/// 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: stats::StatPair) {
implementations::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
}
/// 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) {
self.metadata.prestige = prestige;
}
/// Adjusts the entity's prestige stat by adding a delta.
pub fn modify_prestige_by_delta(&mut self, prestige: stats::GenericStat) {
self.metadata.prestige = self.metadata.prestige.add(prestige);
}
/// Add a governor to the entity if the id exists
pub fn change_governor(&mut self, governor: stats::CharacterId) {
debug!("Swapping the governor with {}", governor.to_symbol());
self.metadata.governor = Some(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) {
debug!("Swapping the capital with {}", capital.to_symbol());
self.metadata.capital = Some(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.starts_with(name),
Some(EntityIdentifier::Id(id)) => self.id.hyphenated().to_string().starts_with(id),
None => false,
}
}
}

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;

View File

@ -74,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()