ravenous-tools/crates/weaponry/src/weaponry_structs/equipement_impl_basics.rs

439 lines
14 KiB
Rust

// Workspace: weaponry
// File: weaponry/src/weaponry_structs/equipement_impl_basics.rs
// TODO: At some point a trait might want to be used to use these into instead of calling it directly
// : Doing so would ensure all prerequists are met
// : Another way of doing so might be to instead use Into<Combinable> instead
// : Another way would be to add a filter field that would allow or not the combinaison and abstract all
// logic that would be into doing multi traits things
//! 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 super::equipement_structs::InnerEquipementStats;
use crate::interfaces::{FilterFunction, Reportable};
use crate::weaponry_structs::equipement_fields::WeaponBaseSize;
use crate::weaponry_structs::{SpecialField, WeaponBaseShape};
use comfy_table::{Table, modifiers::UTF8_ROUND_CORNERS};
use std::{
fmt::{Debug, Display},
rc::Rc,
};
use super::{
Equipement, InitialEquipementList,
equipement_advanced_repr::RefinedEquipementList,
equipement_structs::{
EqFinishing, EqMaterial, EqNature, EqShape, filter_id_unique_and_right_category,
},
};
impl From<EqShape> for Equipement {
fn from(val: EqShape) -> Self {
Self {
stats: val.stats,
..Default::default()
}
}
}
impl From<EqMaterial> for Equipement {
fn from(val: EqMaterial) -> Self {
Self {
stats: val.stats,
filter_function: FilterFunction::new(filter_id_unique_and_right_category()),
}
}
}
impl From<EqNature> for Equipement {
fn from(val: EqNature) -> Self {
Self {
stats: val.stats,
// Checks that the nature is compatible with the previous iteration
filter_function: FilterFunction::new(filter_id_unique_and_right_category()),
}
}
}
impl From<EqFinishing> for Equipement {
fn from(val: EqFinishing) -> Self {
Self {
stats: val.stats,
..Default::default()
}
}
}
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_base
.clone()
.map_or_else(|| "ø".to_string(), |v| v.to_string()),
self.category_size
.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.is_empty(),
vec![
self.special
.iter()
.intersperse(&",".to_string())
.fold(String::new(), |res, new| format!("{}; {}", res, new)),
],
);
write!(f, "{table}")
}
}
// impl Display for InitialEquipementList {
// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// for v in self.ref_inner() {
// write!(f, "{v}")?;
// }
// Ok(())
// }
// }
impl Reportable for InitialEquipementList {
fn get_report(&self, title: Option<&str>) -> String {
let mut table = Table::new();
table.apply_modifier(UTF8_ROUND_CORNERS);
match title {
Some(t) => table.add_row(vec![format!("[IEL] {t}")]),
None => table.add_row(vec![format!("Initial Equipement List")]),
};
table.add_row(vec![format!("Rows: {}", self.inner.len())]);
table.to_string()
}
}
impl Reportable for RefinedEquipementList {
fn get_report(&self, title: Option<&str>) -> String {
let mut table = Table::new();
table.apply_modifier(UTF8_ROUND_CORNERS);
match title {
Some(t) => table.add_row(vec![format!("[REL] {t}")]),
None => table.add_row(vec![format!("Refined Equipement List")]),
};
table.add_row(vec![format!("Rows: {}", self.len())]);
table.to_string()
}
}
impl<T> Debug for FilterFunction<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Filter:{}", std::any::type_name::<Self>())
}
}
impl<T> Default for FilterFunction<T> {
fn default() -> Self {
FilterFunction(Box::new(Rc::new(|_, _| true)))
}
}
impl<T> PartialEq for FilterFunction<T> {
// #[coverage(off)] // INCORRECT: Error with line report
fn eq(&self, _other: &Self) -> bool {
true
}
}
/// Add a new vector to a clone of a inner field
macro_rules! add_to_vec {
($self: expr, $rhs: expr) => {{
let mut new = $self.clone();
new.append(&mut $rhs.clone());
new
}};
}
/// Adds either of the vectors or merge them
macro_rules! add_two_options {
($self: expr, $rhs: expr) => {{
match ($self.as_ref(), $rhs.as_ref()) {
(None, None) => None,
(None, Some(a)) => Some(a.clone()),
(Some(a), None) => Some(a.clone()),
(Some(a), Some(b)) => Some(a.clone() + b.clone()),
}
}};
}
/// Clones the first option that has some data
macro_rules! first_correct_option {
($self:expr, $rhs:expr) => {
match ($self.as_ref(), $rhs.as_ref()) {
(Some(a), _) => Some(a.clone()),
(_, Some(b)) => Some(b.clone()),
_ => None,
}
};
}
/// Fixing the french grammar in the worst way possible
fn stupid_adjective_fix(name_base: &str, adj: String) -> String {
let plur = || format!("{adj}s");
let masc = || match adj.as_str() {
"moyenne" => "moyen".to_owned(),
"légère" => "léger".to_owned(),
_ => adj[..adj.len() - 1].to_string(),
};
match name_base {
"Griffes" => plur(),
"Hast" => masc(),
"Marteau" => masc(),
"Arc" => masc(),
"Bouclier" => masc(),
_ => adj,
}
}
impl std::ops::Add for &InnerEquipementStats {
type Output = InnerEquipementStats;
fn add(self, rhs: Self) -> Self::Output {
InnerEquipementStats {
id: add_to_vec!(self.id, rhs.id),
name: add_to_vec!(
self.name,
if let Some(ad) = &rhs.adjective {
vec![stupid_adjective_fix(&self.name[0], ad.clone())]
} else {
rhs.name.clone()
}
),
adjective: rhs.adjective.clone(),
rarity: self.rarity + rhs.rarity,
cost: self.cost + rhs.cost,
difficulty: self.difficulty + rhs.difficulty,
tier: self.tier + rhs.tier,
damage: self.damage + rhs.damage,
p_damage: self.p_damage + rhs.p_damage,
precision: self.precision + rhs.precision,
rmax: self.rmax + rhs.rmax,
armor_break: self.armor_break + rhs.armor_break,
armor_pierce: {
if self.armor_pierce > 0
|| matches!(self.category_base, Some(WeaponBaseShape::Ranged))
{
self.armor_pierce + rhs.armor_pierce
} else {
0
}
},
antimaterial: self.antimaterial + rhs.antimaterial,
damage_type: add_two_options!(self.damage_type, rhs.damage_type),
protection: self.protection + rhs.protection,
integrity: self.integrity + rhs.integrity,
torque_two_handed: add_two_options!(self.torque_two_handed, rhs.torque_two_handed),
torque_one_handed: add_two_options!(self.torque_one_handed, rhs.torque_one_handed),
dodge: self.dodge + rhs.dodge,
parry: self.parry + rhs.parry,
speed: self.speed + rhs.speed,
stealth: self.stealth + rhs.stealth,
special: self.special.clone() + rhs.special.clone(), // Can be further optimized
action_cost: self.action_cost + rhs.action_cost,
reload_cost: self.reload_cost.or(rhs.reload_cost),
range: self.range + rhs.range,
agility_bonus: self.agility_bonus + rhs.agility_bonus,
category_base: first_correct_option!(self.category_base, rhs.category_base),
category_size: first_correct_option!(self.category_size, rhs.category_size),
target_category: first_correct_option!(self.target_category, rhs.target_category),
}
}
}
impl std::ops::Add for SpecialField {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
let mut c = self.clone();
c.append(&mut rhs.clone());
c
}
}
impl InnerEquipementStats {
/// Get the maniement as a printable string
pub fn get_maniement(&self) -> String {
match &self.category_size {
Some(WeaponBaseSize::SuperHeavy) => match self.name[0].as_str() {
"Griffes" => "Frienzä",
"Marteau" => "Rhödarak",
"Épée" => "Haroth",
"Hache" => "Kahml",
"Hast" => "Paysagiste",
"Arc" => "Distance",
"Arbalète" => "Distance",
_ => "-",
}
.to_string(),
_ => match &self.category_base {
Some(WeaponBaseShape::Staves) => "Hast".to_string(),
Some(WeaponBaseShape::Blunt) => "Contondante".to_string(),
Some(WeaponBaseShape::Slash) => "Tranchante".to_string(),
Some(WeaponBaseShape::Ranged) => "Distance".to_string(),
_ => "-".to_string(),
},
}
}
/// Get the modes as a printable string
pub fn get_modes(&self) -> String {
match &self.damage_type {
Some(t) => t
.get_best_modes()
.iter()
.map(|v| v.export())
.collect::<Vec<String>>()
.join(","),
None => "-".to_string(),
}
}
}
#[cfg(test)]
mod test {
use crate::{
interfaces::{FilterFunction, RecipeCollection, Reportable},
weaponry_structs::{
Equipement, InitialEquipementList,
equipement_advanced_repr::RefinedEquipementList,
equipement_structs::{DatabaseEquipementStats, InnerEquipementStats},
},
};
#[test]
fn test_filter_weapons() {
let _ = format!("{:?}", FilterFunction::<Equipement>::default());
let r = FilterFunction::<Equipement>::new(&|_, _| false) == FilterFunction::default();
assert!(r);
}
#[allow(dead_code)]
/// A manually implemented hashmap of all values
#[doc(hidden)]
macro_rules! r {
() => {
fastrand::i8(1..20)
};
}
impl InnerEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: vec![r!() as u8],
range: (r!() - 10) as i16,
damage: r!() - 10,
p_damage: r!() - 10,
protection: r!() - 10,
..Default::default()
}
}
}
impl DatabaseEquipementStats {
/// Testing function to fuzz data
pub fn random_new() -> Self {
Self {
id: r!() as u8,
range: r!() - 19,
damage: r!() - 10,
p_damage: r!() - 10,
protection: r!() - 10,
..Default::default()
}
}
}
#[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(None));
println!("{}", eqlist.get_report(None));
}
#[test]
fn test_macros() {
assert_eq!(first_correct_option!(None::<i8>, None::<i8>), None);
assert_eq!(first_correct_option!(Some(3), None::<i8>), Some(3));
assert_eq!(first_correct_option!(None::<i8>, Some(4)), Some(4));
assert_eq!(first_correct_option!(Some(1), Some(3)), Some(1));
assert_eq!(add_two_options!(Some(1), Some(3)), Some(4));
assert_eq!(add_two_options!(Some(3), None::<i8>), Some(3));
assert_eq!(add_two_options!(None::<i8>, Some(4)), Some(4));
let a = vec![1, 2];
let b = vec![3];
assert_eq!(add_to_vec!(a, b), vec![1, 2, 3]);
}
}