diff --git a/weaponry/Cargo.toml b/weaponry/Cargo.toml index c15964e..9889c9a 100644 --- a/weaponry/Cargo.toml +++ b/weaponry/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +comfy-table = "7.1.4" fastrand = "2.3.0" iter-enum = "1.2.0" pretty_assertions = "1.4.1" diff --git a/weaponry/src/interfaces.rs b/weaponry/src/interfaces.rs index ee0b004..301f250 100644 --- a/weaponry/src/interfaces.rs +++ b/weaponry/src/interfaces.rs @@ -164,26 +164,10 @@ pub trait FixedRecipe: DbSerializable { fn get_elements() -> Vec<(Self::Database, Self::KeyList)>; } -// /// A blanket implementation giving all combinaisons of recipes with another RecipeCollection -// /// -// /// This method doesn't make use of parallel iterators as the workload is way faster than would be the memory dispatch -// fn combine_all_par(&mut self, other: &G) -// where -// G: RecipeCollection + std::marker::Sync, -// { -// self.assign_inner( -// self.owned_inner() -// .par_iter() -// .flat_map(|inner_recipes| { -// other -// .ref_inner() -// .iter() -// .filter(|&external_recipes| external_recipes.backward_filter(inner_recipes)) -// .map(|external_recipes: &Self::Recipes| { -// inner_recipes.add_ref_to_self(external_recipes) -// }) -// .collect::>() -// }) -// .collect::>(), -// ); -// } +/// Trait ensuring a status report can be inferred from the structure +pub trait Reportable { + /// Get a detailled inner status report with as many useful informations as possible + /// + /// This report should give detailled information about the inner data, without showing the actual inner data + fn get_report(&self) -> String; +} diff --git a/weaponry/src/lib.rs b/weaponry/src/lib.rs index bf88e5e..7e4c707 100644 --- a/weaponry/src/lib.rs +++ b/weaponry/src/lib.rs @@ -3,6 +3,7 @@ //! Weaponry module, handling all weaponry creation and analysis #![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![feature(iter_intersperse)] mod database; mod export; diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 3213d7e..21e5727 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -13,6 +13,7 @@ use core::f64; use std::fmt::Display; use crate::interfaces::RefinedList; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; use probability::prelude::{Binomial, Discrete}; use strum::{Display, EnumIter, IntoEnumIterator}; @@ -41,7 +42,7 @@ impl From for RefinedEquipement { /// The complete equipement list, refined with all advanced stats pub struct RefinedEquipementList { /// Inner list of Refined Equipements - inner: Vec, + pub(super) inner: Vec, } // Just a checkmark @@ -75,7 +76,8 @@ pub struct AdvancedStats { } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { - let damage_per_attack = (value.damage + value.p_damage * (value.rmax - 1)) as f64; + let damage_per_attack = + (value.damage + value.p_damage * (value.rmax.saturating_sub(1))) as f64; let armor_break_per_attack = (value.armor_break as f64).min(damage_per_attack); Self { damage_per_attack, @@ -111,33 +113,27 @@ impl DamageMatrix { impl Display for DamageMatrix { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - // "[{:.3}:{:.3}] {:5.2}", dices, precision, - write!( - f, - "{}", - DiceNumber::iter() - .map(|dices| { - Precision::iter() - .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))) - .fold(format!("[{:.3}]", dices.to_string()), |res, new| { - res + " " + &new - }) - }) - .fold( - Precision::iter().fold(String::from(" D\\P "), |res, new| format!( - "{} [{:.3}]", - res, new - )), - |res, new| res + "\n" + &new - ) - ) + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + let mut headers = vec![String::from("D\\P")]; + headers.append( + &mut Precision::iter() + .map(|e| format!("{:.3}", e)) + .collect::>(), + ); + table.set_header(headers); + table.add_rows(DiceNumber::iter().map(|dices| { + vec![format!("{:.3}", dices)].into_iter().chain( + Precision::iter() + .map(move |precision| format!("{:5.2}", self.get_damage(precision, dices))), + ) + })); + write!(f, "{}", table) } } impl From<&InnerEquipementStats> for DamageMatrix { fn from(value: &InnerEquipementStats) -> Self { - // let binomial_distribution = Binomial::new(dices, value.precision); - // binomial_distribution.mass(i) // -> The chance to have this number of success DamageMatrix { damage_matrix: (DiceNumber::iter() .flat_map(|dices| { @@ -163,7 +159,7 @@ fn binomial_dice_distribution(value: &InnerEquipementStats, precision: usize, di if target_dices >= 1 { (value.damage as f64 + value.p_damage as f64 - * (target_dices.clamp(0, value.rmax as usize) - 1) as f64) + * (target_dices.clamp(0, value.rmax as usize).saturating_sub(1)) as f64) * probability_success } else { 0. @@ -216,25 +212,37 @@ impl DiceNumber { #[cfg(test)] mod test { use crate::weaponry_structs::{ - equipement_advanced_repr::DamageMatrix, equipement_structs::InnerEquipementStats, + equipement_advanced_repr::{DamageMatrix, DiceNumber, Precision}, + equipement_structs::InnerEquipementStats, }; #[test] fn test_binomial() { - let damage = InnerEquipementStats { + let damage = new_inner_eq(); + let mat: DamageMatrix = DamageMatrix::from(&damage); + println!("{:#?}", damage); + println!("{:#?}", mat); + } + + fn new_inner_eq() -> InnerEquipementStats { + InnerEquipementStats { damage: 10, p_damage: 2, precision: 0, rmax: 3, armor_break: 2, ..Default::default() - }; - let mat: DamageMatrix = DamageMatrix::from(&damage); - println!("{:#?}", damage); - println!("{:#?}", mat); - println!("{}", mat); + } } #[test] - fn test_creation() {} + fn test_creation() { + let mat = DamageMatrix::from(&new_inner_eq()); + println!("{}", mat); + println!( + "(High,Many): {}, (Low,Few): {}", + mat.get_damage(Precision::High, DiceNumber::Many), + mat.get_damage(Precision::Low, DiceNumber::Few) + ); + } } diff --git a/weaponry/src/weaponry_structs/equipement_fields.rs b/weaponry/src/weaponry_structs/equipement_fields.rs index 0940494..a352e7e 100644 --- a/weaponry/src/weaponry_structs/equipement_fields.rs +++ b/weaponry/src/weaponry_structs/equipement_fields.rs @@ -2,6 +2,10 @@ // File: weaponry/src/weaponry_structs/equipement_fields.rs //! The inner fields used by the super structs +use std::fmt::Display; + +use strum::Display; + #[derive(Clone, Default, Debug)] #[cfg_attr(test, derive(PartialEq))] /// The special category, a vec of string, for display purposes only @@ -39,7 +43,7 @@ impl From<&str> for PhysicalDamageType { /// /// Signifying wether the damage is pure or [secondary] or [[tertiary]] #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug)] +#[derive(Clone, Debug, Display)] #[cfg_attr(test, derive(PartialEq))] pub enum DamageMod { Primary(PhysicalDamageType), @@ -70,9 +74,21 @@ impl From<&str> for DamageType { } } +impl Display for DamageType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.0 + .iter() + .fold(String::new(), |res, new| format!("{res}, {new}")) + ) + } +} + /// List all weapon categories #[allow(clippy::missing_docs_in_private_items, missing_docs)] -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, Display)] // #[cfg_attr(test, derive(PartialEq))] pub enum WeaponCategory { Exotic, diff --git a/weaponry/src/weaponry_structs/equipement_impl_basics.rs b/weaponry/src/weaponry_structs/equipement_impl_basics.rs index 252833a..9b7cb66 100644 --- a/weaponry/src/weaponry_structs/equipement_impl_basics.rs +++ b/weaponry/src/weaponry_structs/equipement_impl_basics.rs @@ -8,11 +8,15 @@ //! Implementations to transform all Specialized equipement into a generic Equipement //! A specific implementation could be preferable, but this simplicity might allow for easier developpement -use crate::interfaces::FilterFunction; +use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS}; +use std::fmt::Display; + +use crate::interfaces::{FilterFunction, Reportable}; use super::{ - Equipement, - equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape}, + Equipement, InitialEquipementList, + equipement_advanced_repr::RefinedEquipementList, + equipement_structs::{EqFinishing, EqMaterial, EqNature, EqShape, InnerEquipementStats}, }; impl From for Equipement { @@ -55,3 +59,132 @@ impl From for Equipement { } } } + +impl Display for Equipement { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.stats) + } +} + +impl Display for InnerEquipementStats { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!( + "Ids: {}, Names:{}", + self.id + .iter() + .fold(String::new(), |res, new| format!("{res} {new}")), + self.name.join(" & ") + )]); + table.add_row(vec![format!( + "Rarity: {}, Cost {}, Difficulty: {}, Tier: {} [{}]", + self.rarity, + self.cost, + self.difficulty, + self.tier, + self.category + .clone() + .map_or_else(|| "ø".to_string(), |v| v.to_string()) + )]); + table.add_row_if( + |_, _| self.damage > 0, + vec![format!( + "Damage: {}/+{} P:{}, AB:{} AM:{} A:{} [{}]", + self.damage, + self.p_damage, + self.precision, + self.armor_break, + self.antimaterial, + self.action_cost, + self.clone() + .damage_type + .map_or_else(|| "ø".to_string(), |damage| damage.to_string()) + )], + ); + table.add_row_if( + |_, _| self.protection > 0, + vec![format!("Prot:{} Int:{}", self.protection, self.integrity)], + ); + table.add_row(vec![format!( + "T1/T2 {}/{} Dodge:{} Parry:{} Speed:{} Stealth:{} Agility: {}", + self.torque_one_handed, + self.torque_two_handed, + self.dodge, + self.parry, + self.speed, + self.stealth, + self.agility_bonus, + )]); + table.add_row_if( + |_, _| (self.range > 0) | (self.armor_pierce > 0), + vec![format!( + "Rg:{}, AP:{}, Rel:{}", + self.range, + self.armor_pierce, + self.reload_cost + .map_or_else(|| "ø".to_string(), |v| format!("{v}")) + )], + ); + table.add_row_if( + |_, _| !self.special.0.is_empty(), + vec![ + self.special + .0 + .iter() + .intersperse(&",".to_string()) + .fold(String::new(), |res, new| format!("{}; {}", res, new)), + ], + ); + write!(f, "{table}") + } +} + +impl Reportable for InitialEquipementList { + fn get_report(&self) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!("Refined Equipement List")]); + table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.to_string() + } +} + +impl Reportable for RefinedEquipementList { + fn get_report(&self) -> String { + let mut table = Table::new(); + table.apply_modifier(UTF8_ROUND_CORNERS); + table.add_row(vec![format!("Refined Equipement List")]); + table.add_row(vec![format!("Rows: {}", self.inner.len())]); + table.to_string() + } +} + +#[cfg(test)] +mod test { + use crate::{ + interfaces::{RecipeCollection, Reportable}, + weaponry_structs::{ + Equipement, InitialEquipementList, equipement_advanced_repr::RefinedEquipementList, + equipement_structs::InnerEquipementStats, + }, + }; + + #[test] + fn test_format() { + let equi = Equipement { + stats: InnerEquipementStats::random_new(), + ..Default::default() + }; + print!("{}", equi); + } + + #[test] + fn test_report() { + let eqlist = InitialEquipementList::from_vectored(vec![Equipement::default(); 10]); + let feqlist: RefinedEquipementList = eqlist.clone().into(); + + println!("{}", feqlist.get_report()); + println!("{}", eqlist.get_report()); + } +} diff --git a/weaponry/src/weaponry_structs/equipement_structs.rs b/weaponry/src/weaponry_structs/equipement_structs.rs index d4e6f5e..1a6b4de 100644 --- a/weaponry/src/weaponry_structs/equipement_structs.rs +++ b/weaponry/src/weaponry_structs/equipement_structs.rs @@ -89,12 +89,22 @@ pub struct InnerEquipementStats { pub(super) agility_bonus: u8, } +#[doc(hidden)] +macro_rules! r { + () => { + fastrand::u8(1..10) + }; +} // TODO: Make this a test requirement or hide it behind a profile impl InnerEquipementStats { /// Testing function to fuzz data pub fn random_new() -> Self { Self { - id: vec![fastrand::u8(..10)], + id: vec![r!()], + range: r!(), + damage: r!(), + p_damage: r!(), + protection: r!(), ..Default::default() } }