//! Implementation of all needed traits for the Entity struct 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::Displayable; use crate::entity::Entity; use crate::epoch::epoch_traits::Diffable; use crate::error::EpochError; use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols}; use crate::utils::RngLevel; // ---------- 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 displays fn oneline_display(&self) -> String { let capital = self .metadata .capital .as_ref() .map(|c| format!(" | πŸ’° {:>2}", c)) .unwrap_or_default(); let governor = self .metadata .governor .as_ref() .map(|g| format!(" | πŸ‘‘ {:>2}", g)) .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 { 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 { 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 { items .with_title() .bold(true) .border( Border::builder() .top(HorizontalLine::new('β”Œ', '┐', '┬', '─')) .bottom(HorizontalLine::new('β””', 'β”˜', 'β”΄', '─')) .left(VerticalLine::new('β”‚')) .right(VerticalLine::new('β”‚')) .build(), ) .separator( Separator::builder() .column(Some(VerticalLine::new('β”‚'))) .row(Some(HorizontalLine::new('β”œ', '─', 'β”Ό', '─'))) .build(), ) .display() .map_err(|_e| EpochError::TableStringConversionError { name: self.name.clone(), id: 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: out.push_str(&format!( "[{} {}]\n", self.entity_type.to_symbol().blue().bold(), // entity type self.name.cyan().bold() // name )); // ── Metadata section out.push_str(&indent(0, &format!("β”œβ”€ {}\n", "metadata".green()))); out.push_str(&indent( 1, &format!( "β”œβ”€ {}: {}\n", "position".bright_green(), self.metadata.position.to_symbol() ), )); out.push_str(&indent( 1, &format!( "β”œβ”€ {}: {:?}\n", "capital".bright_green(), self.metadata.capital ), )); out.push_str(&indent( 1, &format!( "└─ {}: {}\n", "prestige".bright_green(), self.metadata.prestige ), )); // ── 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!("{} {}", symbol.cyan(), 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 { 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); } } // TODO: Redoc /// Overwrite a stat in a table fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) { let affected_stat = stats.get_field_mut(&pair.stat); *affected_stat = pair.value; } /// Add to a stat in a table 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: self.entity_type.clone(), duration: self.duration.clone(), effect_nature: self.effect_nature.clone(), effect_bounds: self.effect_bounds.clone() - other.effect_bounds.clone(), id: Uuid::new_v4(), } } } impl Diffable for Option { 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(a)) => Some(*a), (Some(a), None) => Some(*a), (Some(a), Some(b)) => Some(*a - *b), } }, links: self .links .clone() .into_iter() .filter(|t1| other.links.iter().any(|t2| t1 == t2)) .collect(), prestige: self.prestige - other.prestige, } } }