epoch_forge/lib_efo/src/entity/implementations.rs

397 lines
14 KiB
Rust

//! 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 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};
// ---------- Implementation ----------
impl Displayable for Entity {
// Detailed multi-line view (used e.g. in logs)
fn print_full(&self) {
println!("{}", self.to_pretty_tree(),);
if let Ok(c) = self.stats_to_table() {
println!("{c}");
}
}
/// One-liner used for auto-generation of `Vec<T>` displays
fn oneline_display(&self) -> String {
let capital = self
.metadata
.capital
.as_ref()
.map(|c| format!(" 󰻾[{:>2}] ", c).green())
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!(" 󰻾[{:>2}]", g).red())
.unwrap_or_default();
let prestige = if *self.metadata.prestige > 0 {
format!(" {:2}{}", self.metadata.prestige, "".yellow())
} else {
String::new()
};
// ---- build the two lines ----
let line1 = format!(
"├──┬─ {} {:23} {} ──────> {} {}",
self.id.to_string().split_at(7).0.blue(),
self.name.green(),
self.entity_type.to_symbol(),
self.metadata.position.to_symbol(),
self.duration.to_symbol().yellow(),
);
let (junction, line3) = if !capital.is_empty() | !governor.is_empty() {
("├", format!("│ └─ {}{}\n", capital, governor,))
} else {
("└", "".to_string())
};
let line2 = format!(
"│ {}─ Faction: {} │ Effect: {} {}, Stats: {}{}",
junction,
self.metadata.faction.to_symbol(),
self.effect_nature.to_symbol(),
self.effect_bounds.to_symbol(),
self.stats.to_symbol(),
prestige,
);
format!("{}\n{}\n{}│", line1, line2, line3)
}
}
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
),
));
}
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_string().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);
}
/// 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
}
}
/// Replace a statistic in `stats` with the value from `pair`.
///
/// 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));
}
/// Compare a field on `self` with the same field on `other`.
/// If they are equal → `None`, otherwise → the value from `other`.
macro_rules! diff_fields {
// Two arguments: the two objects you want to compare
($self:ident, $other:ident, $( $field:ident ),* $(,)?) => {
$(
let $field = if $self.$field == $other.$field {
None
} else {
$other.$field.clone()
};
)*
};
}
impl Diffable for Entity {
fn delta(&self, other: &Self) -> Self {
let name = if self.name == other.name {
self.name.clone()
} else {
format!("{}->{}", self.name, other.name)
};
Self {
name,
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(),
duration: other.duration.clone(),
effect_nature: other.effect_nature.clone(),
effect_bounds: other.effect_bounds.clone(),
id: Uuid::new_v4(),
}
}
}
impl Diffable for Option<OverallStats> {
fn delta(&self, other: &Self) -> Self {
match (self, other) {
(None, None) => None,
(None, Some(a)) => Some(a.clone()),
(Some(a), None) => Some(a.clone()),
(Some(a), Some(b)) => Some(a.clone() - b.clone()),
}
}
}
impl Diffable for MetaStats {
fn delta(&self, other: &Self) -> Self {
diff_fields!(self, other, capital, governor);
Self {
position: self.position.clone() - other.position.clone(),
capital,
governor,
faction: {
match (self.faction.as_ref(), other.faction.as_ref()) {
(None, None) => None,
(None, Some(b)) => Some(*b),
(Some(a), None) => Some(*a),
(Some(_), Some(b)) => Some(*b),
}
},
links: self
.links
.clone()
.into_iter()
.filter(|t1| other.links.iter().any(|t2| t1 == t2))
.collect(),
prestige: self.prestige - other.prestige,
}
}
}