//! 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, }; /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. /// /// # Parameters /// * `$type`: the concrete type that implements `GameStat` /// * `$vis`: the enum variant of `VisibilityLevel` to return macro_rules! impl_game_stat { ($type:ident) => { impl GameStat for $type { fn get_value(&self) -> isize { self.0 } fn change_value(&mut self, value: isize) { self.0 = value; } fn from_value(value: isize) -> Self where Self: Sized, { Self(value) } } }; } /// A field accessor to be able to modify fields on the fly macro_rules! field_accessor { ($name:ident { $($field:ident),* }) => { impl $name { fn get_field_from_str(&self, key: &str) -> Option<&dyn GameStat> { match key { $( stringify!($field) => Some(&self.$field), )* _ => None, } } fn get_field_mut_from_str(&mut self, key: &str) -> Option<&mut dyn GameStat> { match key { $( stringify!($field) => Some(&mut self.$field), )* _ => None, } } } }; } impl_game_stat!(GenericStat); field_accessor!(OverallStats { demographics, population, growth_rate, crime, happiness, economy, food, industry, science, trade, // social, // culture, // education, // tourism, // influence, military, army, strength, fortification, threat, infrastructure, bureaucracy, transportation, sprawl, 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 { 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 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. /// /// # Arguments /// /// * `field` - The `ListStats` variant that selects which statistic to return. /// /// # Returns /// /// A reference to the selected `GenericStat`. /// /// # Panics /// /// Panics if `field` is one of the variants that are not yet implemented /// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`). pub fn get_field(&self, field: &ListStats) -> &GenericStat { match field { ListStats::Demographics => &self.demographics, ListStats::Population => &self.population, ListStats::Growthrate => &self.growth_rate, ListStats::Crime => &self.crime, ListStats::Happiness => &self.happiness, ListStats::Economy => &self.economy, ListStats::Food => &self.food, ListStats::Industry => &self.industry, ListStats::Science => &self.science, ListStats::Trade => &self.trade, ListStats::Social => unimplemented!("This version doens't implement this stat"), //&self.social, ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&self.culture, ListStats::Education => unimplemented!("This version doens't implement this stat"), //&self.education, ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&self.tourism, ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&self.influence, ListStats::Military => &self.military, ListStats::Army => &self.army, ListStats::Strength => &self.strength, ListStats::Fortification => &self.fortification, ListStats::Threat => &self.threat, ListStats::Infrastructure => &self.infrastructure, ListStats::Bureaucracy => &self.bureaucracy, ListStats::Transportation => &self.transportation, ListStats::Sprawl => &self.sprawl, ListStats::Health => &self.health, } } /// Retrieve a mutable reference to a statistic field by its `ListStats` key. /// /// # Arguments /// /// * `field` - The `ListStats` variant that selects which statistic to modify. /// /// # Returns /// /// A mutable reference to the selected `GenericStat`. /// /// # Panics /// /// Panics if `field` is one of the variants that are not yet implemented /// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`). pub fn get_field_mut(&mut self, field: &ListStats) -> &mut GenericStat { match field { ListStats::Demographics => &mut self.demographics, ListStats::Population => &mut self.population, ListStats::Growthrate => &mut self.growth_rate, ListStats::Crime => &mut self.crime, ListStats::Happiness => &mut self.happiness, ListStats::Economy => &mut self.economy, ListStats::Food => &mut self.food, ListStats::Industry => &mut self.industry, ListStats::Science => &mut self.science, ListStats::Trade => &mut self.trade, ListStats::Social => unimplemented!("This version doens't implement this stat"), //&mut self.social, ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&mut self.culture, ListStats::Education => unimplemented!("This version doens't implement this stat"), //&mut self.education, ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&mut self.tourism, ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&mut self.influence, ListStats::Military => &mut self.military, ListStats::Army => &mut self.army, ListStats::Strength => &mut self.strength, ListStats::Fortification => &mut self.fortification, ListStats::Threat => &mut self.threat, ListStats::Infrastructure => &mut self.infrastructure, ListStats::Bureaucracy => &mut self.bureaucracy, ListStats::Transportation => &mut self.transportation, ListStats::Sprawl => &mut self.sprawl, ListStats::Health => &mut self.health, } } } 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 { 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 { // Trim whitespace just in case and attempt to parse. let inner = s .trim() .parse::() .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: /// ``` /// # 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`). #[macro_export] macro_rules! thin_newtype { /* ---- no custom derives ------------------------------------------------- */ ($name:ident, $inner:ty) => { /// Thin wrapper that derefs to the inner type. /// Ideal for zero-overhead new-type patterns. #[repr(transparent)] #[derive( Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Display, )] pub struct $name(pub $inner); impl std::ops::Deref for $name { type Target = $inner; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for $name { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<$inner> for $name { #[inline] fn from(v: $inner) -> Self { $name(v) } } impl From<$name> for $inner { #[inline] fn from(v: $name) -> Self { v.0 } } }; /* ---- with a custom derive list ---------------------------------------- */ ($name:ident, $inner:ty, derives: [ $( $derive:ident ),* $(,)? ]) => { /// Thin wrapper that derefs to the inner type. /// Ideal for zero-overhead new-type patterns. #[repr(transparent)] #[derive( Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, derive_more::Display, $( $derive ),* )] pub struct $name(pub $inner); impl std::ops::Deref for $name { type Target = $inner; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for $name { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<$inner> for $name { #[inline] fn from(v: $inner) -> Self { $name(v) } } impl From<$name> for $inner { #[inline] fn from(v: $name) -> Self { v.0 } } }; } mod from_impl; #[cfg(test)] pub(crate) mod test;