From 18c864efe539932ea72aacbf16caa3fda7c72aa9 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Tue, 25 Feb 2025 01:38:21 +0100 Subject: [PATCH] Refactoring and adds Attacks & Actions as thin types --- weaponry/examples/graph.rs | 43 ++- weaponry/examples/usage_scenario.rs | 1 - weaponry/src/export.rs | 2 +- .../equipement_advanced_repr.rs | 148 +++++--- .../equipement_advanced_tools.rs | 344 ++++++++++++------ .../weaponry_structs/equipement_thin_types.rs | 97 +++++ weaponry/src/weaponry_structs/mod.rs | 1 + 7 files changed, 468 insertions(+), 168 deletions(-) create mode 100644 weaponry/src/weaponry_structs/equipement_thin_types.rs diff --git a/weaponry/examples/graph.rs b/weaponry/examples/graph.rs index c4a20fb..053cb0a 100644 --- a/weaponry/examples/graph.rs +++ b/weaponry/examples/graph.rs @@ -49,7 +49,10 @@ // } use charming::{ Chart, - component::{Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, ToolboxDataZoom, VisualMap, VisualMapType}, + component::{ + Axis, DataZoom, DataZoomType, Feature, Grid, Restore, SaveAsImage, Title, Toolbox, + ToolboxDataZoom, VisualMap, VisualMapType, + }, element::{AxisType, Tooltip, Trigger}, series::Line, }; @@ -118,21 +121,49 @@ pub fn chart() -> Chart { }); Chart::new() - .title(Title::new().text("Gradient along the y axis").left("center")) + .title( + Title::new() + .text("Gradient along the y axis") + .left("center"), + ) // .title(Title::new().text("Gradient along the x axis").left("center").top("55%")) .tooltip(Tooltip::new().trigger(Trigger::Axis)) - .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(0).min(0).max(400)) + .visual_map( + VisualMap::new() + .show(false) + .type_(VisualMapType::Continuous) + .series_index(0) + .min(0) + .max(400), + ) // .visual_map(VisualMap::new().show(false).type_(VisualMapType::Continuous).series_index(1).dimension(0).min(0).max(10).max((data_list.len() - 1) as f64)) - .x_axis(Axis::new().data(data_list.to_vec()).type_(AxisType::Category).boundary_gap(false)) + .x_axis( + Axis::new() + .data(data_list.to_vec()) + .type_(AxisType::Category) + .boundary_gap(false), + ) // .x_axis(Axis::new().data(data_list.to_vec()).grid_index(1)) .y_axis(Axis::new()) // .y_axis(Axis::new().grid_index(1)) .grid(Grid::new()) // .grid(Grid::new().top("60%")) .series(Line::new().show_symbol(false).data(value_list.clone())) - .data_zoom(DataZoom::new().type_(DataZoomType::Inside).start(0).end(100)) + .data_zoom( + DataZoom::new() + .type_(DataZoomType::Inside) + .start(0) + .end(100), + ) .data_zoom(DataZoom::new().start(0).end(100)) - .toolbox(Toolbox::new().feature(Feature::new().data_zoom(ToolboxDataZoom::new().y_axis_index("none")).restore(Restore::new()).save_as_image(SaveAsImage::new()))) + .toolbox( + Toolbox::new().feature( + Feature::new() + .data_zoom(ToolboxDataZoom::new().y_axis_index("none")) + .restore(Restore::new()) + .save_as_image(SaveAsImage::new()), + ), + ) .tooltip(Tooltip::new().trigger(Trigger::Axis)) // .series(Line::new().show_symbol(false).x_axis_index(1).y_axis_index(1).data(value_list)) } diff --git a/weaponry/examples/usage_scenario.rs b/weaponry/examples/usage_scenario.rs index 18fc536..a3fc0f9 100644 --- a/weaponry/examples/usage_scenario.rs +++ b/weaponry/examples/usage_scenario.rs @@ -44,7 +44,6 @@ fn main() { // TODO[!]: Have an enum match args.sort.as_str() { - "max_per_turn" => refined_list.inner_sort(sort_by!(max_damage_per_turn)), "avg_huge" => refined_list.inner_sort(sort_by!(avg_damage_single_huge_hit)), "avg_safe" => refined_list.inner_sort(sort_by!(avg_damage_2a_safe)), "max_armor" => refined_list.inner_sort(sort_by!(armor_break_per_attack)), diff --git a/weaponry/src/export.rs b/weaponry/src/export.rs index ba05733..db193bb 100644 --- a/weaponry/src/export.rs +++ b/weaponry/src/export.rs @@ -27,7 +27,7 @@ /// |ref_equipement| { /// ( /// &ref_equipement.advanced.display_name, -/// ref_equipement.advanced.max_damage_per_turn, +/// ref_equipement.advanced.max_damage_per_attack, /// ) /// } /// ); diff --git a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs index 45355da..90e37c6 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_repr.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_repr.rs @@ -8,6 +8,8 @@ //! nothing prevents us to implement the trait for other objects and avoid massive computation //! of all the fields even when the user will not be interested in them #![allow(dead_code)] +use crate::weaponry_structs::equipement_thin_types::Dices; +use crate::weaponry_structs::equipement_thin_types::Precision; use crate::{ add_field_to_chart, error::FatalEquipementError, @@ -24,8 +26,10 @@ use charming::Chart; use serde::Serialize; use super::equipement_advanced_tools::{ - Dices, Precision, get_damage_with_simulation, get_sustained_damage, + BestDamageScenarios, get_damage_with_simulation, get_sustained_damage, }; +use super::equipement_thin_types::Actions; +use super::equipement_thin_types::Attacks; /// The final representation of the equipement inplementing all the fields needed for processing // TODO: Add a public getter for the inner data @@ -116,6 +120,7 @@ impl ToAnalysis for RefinedEquipementList { } // TODO[3]: Consider wether the naming should be a parameter, + // : Consider wether the closure should be a parameter // or a config should be given or if the scenario should be fed again the Refined and ... fn write_html(&self, save_path: &str) -> Result<(), FatalEquipementError> { let mut renderer = charming::HtmlRenderer::new("Ravenous Balancing", 4000, 2000) @@ -128,7 +133,7 @@ impl ToAnalysis for RefinedEquipementList { macro_rules! round { ($a:expr) => { - ($a * 10.).round() / 10. + ($a * 100.).round() / 100. }; } add_field_to_chart!( @@ -136,31 +141,32 @@ impl ToAnalysis for RefinedEquipementList { initial_chart, ( index # &String, - // max_damage_per_turn # f64, - // max_damage_per_attack # f64, - // speed # f64, - // armor_break_per_attack # f64, - // expected_armor_break_per # f64, - avg_damage_safe # f64, + max_damage_per_attack # f64, + armor_break_per_attack # f64, + expected_armor_break_per_attack # f64, + avg_damage_2a_safe # f64, avg_damage_single_huge_hit # f64, - // scenario_damage # f64, - // defensive # f64, - mini_scenario_damage # f64 + speed # f64, + scenario_damage # f64, + defensive # f64, + earlygame_sustained_damage_per_turn # f64, + midgame_sustained_damage_per_turn # f64, + endgame_sustained_damage_per_turn # f64, ), |ref_equipement| { ( &ref_equipement.advanced.display_name, - // ref_equipement.advanced.max_damage_per_turn, - // ref_equipement.advanced.max_damage_per_attack, - // ref_equipement.advanced.speed, - // ref_equipement.advanced.armor_break_per_attack, - // ref_equipement.advanced.expected_armor_break_per_2a, - round!(ref_equipement.advanced.avg_damage_2a_safe), - round!(ref_equipement.advanced.avg_damage_single_huge_hit), - // ref_equipement.advanced.scenario_damage, - // ref_equipement.advanced.defensive, - round!(ref_equipement.advanced.mini_scenario_damage), - + round!(ref_equipement.advanced.max_damage_per_attack ), + round!(ref_equipement.advanced.armor_break_per_attack ), + round!(ref_equipement.advanced.expected_armor_break_per_attack ), + round!(ref_equipement.advanced.avg_damage_2a_safe ), + round!(ref_equipement.advanced.avg_damage_single_huge_hit ), + round!(ref_equipement.advanced.speed ), + round!(ref_equipement.advanced.scenario_damage ), + round!(ref_equipement.advanced.defensive ), + round!(ref_equipement.advanced.earlygame_sustained_damage_per_turn ), + round!(ref_equipement.advanced.midgame_sustained_damage_per_turn ), + round!(ref_equipement.advanced.endgame_sustained_damage_per_turn ), ) } ); @@ -192,54 +198,100 @@ impl Default for RefinedEquipementList { /// The list of advanced stats infered from an Equipement // TODO: The two philosophies to drop the old inner or convert the useful fields are considered right now // TODO: This whole public might be overkill ? A good inner view or scenario could implement what is needed -#[allow(missing_docs, clippy::missing_docs_in_private_items)] #[derive(Serialize)] pub struct AdvancedStats { + /// A simple name created by merging all components pub display_name: String, + /// The absolute maximum damage done with each attack pub max_damage_per_attack: f64, - pub max_damage_per_turn: f64, + // /// The absolute maximum damage done every turn (with two attacks) + // pub max_damage_per_turn: f64, + /// The armor break per attack pub armor_break_per_attack: f64, + // This category of every result, using this would be better than id shenenigans // pub category: Option, - /// Armor break factoring in the damage output: While a weapon might have high AB, not having any damage will seriously hinder that AB - pub expected_armor_break_per_2a: f64, - /// Dps with two actions and 5 dices + /// Armor break factoring in the damage output: + /// While a weapon might have high AB, not having any damage will seriously hinder that AB + pub expected_armor_break_per_attack: f64, + /// Dps with two actions and 5 dices over a variety of scenarios pub avg_damage_2a_safe: f64, - // /// Dps with four actions and 11 dices + /// Dps with four actions and 11 dices over a variety of scenarios pub avg_damage_single_huge_hit: f64, + /// The speed given by the weapon pub speed: f64, + /// The damage obtained after a 10 turn pseudo scenario pub scenario_damage: f64, + /// A defensive metric giving the best defense bonus for the weapon pub defensive: f64, - pub mini_scenario_damage: f64, + /// The sustained damage of an earlygame character, normalized over 10 turns + pub earlygame_sustained_damage_per_turn: f64, + /// The sustained damage of an earlygame character, normalized over 10 turns + pub midgame_sustained_damage_per_turn: f64, + /// The sustained damage of an endgame character, normalized over 10 turns + pub endgame_sustained_damage_per_turn: f64, + // QOL Metrics } impl From<&InnerEquipementStats> for AdvancedStats { fn from(value: &InnerEquipementStats) -> Self { let max_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(max_damage_per_attack); + let armor_break_per_attack = + (value.armor_break as f64 + value.antimaterial as f64).min(max_damage_per_attack); Self { - // UNUSED METRICS - // avg_dps_unsafe: damage_matrix.get_unsafe_dmg(value.action_cost), - max_damage_per_turn: max_damage_per_attack * 2., // TODO: Not Sure - // Defensive metrics - // SOL Metrics ? - - // IMPORTANT METRICS display_name: value.name.join(" "), + max_damage_per_attack, speed: value.speed.into(), armor_break_per_attack, - expected_armor_break_per_2a: (max_damage_per_attack + 6. - 8.) + // Adds the base strength, substracts the expected protection + expected_armor_break_per_attack: (max_damage_per_attack + 6. - 8.) .min(armor_break_per_attack) * 2. - / value.action_cost as f64, // Adds the base strength, substracts the expected protection - max_damage_per_attack, - avg_damage_single_huge_hit: value.average_damage(&[Precision(9)], &[Dices(7)]), // A huge hit but definitely not a "FULL THROTTLE" hit - avg_damage_2a_safe: value.average_damage(&[Precision(7)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), - // .average_damage(&[Precision(9), Precision(7), Precision(5)], &[Dices(5)]), // damage_matrix.get_safe_dmg(value.action_cost), - scenario_damage: get_damage_with_simulation(value), - mini_scenario_damage: (value.damage + value.p_damage > 0) - .then(|| get_sustained_damage(value)) - .unwrap_or_default(), - defensive: (value.parry as f64).max(value.dodge.into()), // TODO[b]: Integrity and prot should be taken into account + / value.action_cost as f64, + scenario_damage: get_damage_with_simulation(value, Actions(4), Attacks(2)), + defensive: (value.parry as f64).max(value.dodge.into()), + avg_damage_2a_safe: BestDamageScenarios::from_action_constraints( + value, + Actions(2), + Attacks(2), + Dices(4), + Precision(8), + ) + .map(|f| *f) + .unwrap_or_default(), + avg_damage_single_huge_hit: BestDamageScenarios::from_action_constraints( + value, + Actions(2), + Attacks(2), + Dices(8), + Precision(9), + ) + .map(|f| *f) + .unwrap_or_default(), + earlygame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(4), + Attacks(2), + Dices(9), + Precision(8), + ), + midgame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(5), + Attacks(3), + Dices(11), + Precision(9), + ), + + endgame_sustained_damage_per_turn: get_sustained_damage( + value, + Actions(6), + Attacks(3), + Dices(13), + Precision(10), + ), } } } +// mini_scenario_damage: (value.damage + value.p_damage > 0) +// .then(|| get_sustained_damage(value)) +// .unwrap_or_default(), diff --git a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs index ec10713..756beef 100644 --- a/weaponry/src/weaponry_structs/equipement_advanced_tools.rs +++ b/weaponry/src/weaponry_structs/equipement_advanced_tools.rs @@ -4,12 +4,16 @@ use crate::weaponry_structs::equipement_structs::InnerEquipementStats; use probability::distribution::Discrete; use probability::prelude::Binomial; -use std::fmt::Display; use std::ops::Add; use std::ops::Deref; use strum::Display; use strum::EnumIter; +use super::equipement_thin_types::Actions; +use super::equipement_thin_types::Attacks; +use super::equipement_thin_types::Dices; +use super::equipement_thin_types::Precision; + /// Create the damage profile with the following simulation: /// 10turns total /// - 1 turn no damage @@ -18,9 +22,24 @@ use strum::EnumIter; /// - 1 turn highspeed/range hit (7 dice, 80% precision) /// - 4 turns normal damage (7 dice, 90% precision) // TODO[!] Implementation -pub(super) fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { - let _ = value; - // unfinished!(); +pub(super) fn get_damage_with_simulation( + value: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, +) -> f64 { + let turns = &[ + (actions, attacks, Dices(0), Precision(0)), + (actions, attacks, Dices(12), Precision(13)), + (actions, attacks, Dices(12), Precision(13)), + (actions, attacks, Dices(5), Precision(5)), + (actions, attacks, Dices(7), Precision(8)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + (actions, attacks, Dices(7), Precision(9)), + ]; + 0. } @@ -28,16 +47,51 @@ pub(super) fn get_damage_with_simulation(value: &InnerEquipementStats) -> f64 { /// /// Average damage factoring reload, calculated with 9 dice and 90% precision // TODO[!] Replace avg_damage with this -pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { - // unfinished!(); +pub(super) fn get_sustained_damage( + value: &InnerEquipementStats, + actions: Actions, + attacks: Attacks, + dices: Dices, + precision: Precision, +) -> f64 { // Actions total and damage total are arbitrarely choosen + let l = &[TurnInfo { + actions, + attacks, + dices, + precision, + }; 10]; + let total_damage = damage_over_turns(value, l); + total_damage / 10. + // Iterate 10 turns, every turn we need to substract the leftover reloading + // value.damage.into() +} + +/// Exists internally to pass variables +#[derive(Clone, Copy)] +#[allow(clippy::missing_docs_in_private_items)] +struct TurnInfo { + actions: Actions, + attacks: Attacks, + dices: Dices, + precision: Precision, +} + +/// Calculate the damage over a series of consecutive turns using the given slice of turn info +fn damage_over_turns(value: &InnerEquipementStats, turn_info: &[TurnInfo]) -> f64 { // With reload, damage calculation is rather complicated, since you can half reload but cant half attack // so a reload is valid even if you don't reload fully, but you have to start your turn with less actions // instead of building a complex scenario, the attack pattern is always: Ac:Attack + Re:Reload(and maybe reminder) every turn - let mut reloading_left = 0; + let mut reloading_left = Actions(0); let mut total_damage = 0.; - for _ in 0..10 { + for TurnInfo { + actions, + attacks, + dices, + precision, + } in turn_info + { if let Some(BestDamageScenarios { actions_used: _, attacks_used: _, @@ -46,18 +100,16 @@ pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { depth: _, }) = BestDamageScenarios::from_action_constraints( value, - 4 - reloading_left, - 2, - Dices(9), - Precision(8), + *actions - reloading_left, + *attacks, + *dices, + *precision, ) { reloading_left = reload_remaining; total_damage += damage_done; } } - total_damage / 10. - // Iterate 10 turns, every turn we need to substract the leftover reloading - // value.damage.into() + total_damage } /// The best resulting attack pattern of a virtual scenrio where some conditions are given @@ -65,13 +117,13 @@ pub(super) fn get_sustained_damage(value: &InnerEquipementStats) -> f64 { #[cfg_attr(test, derive(Default, Clone))] pub struct BestDamageScenarios { /// How many actions were used by the best attack - actions_used: i8, + actions_used: Actions, /// Attacks actions used by the scenario - attacks_used: i8, + attacks_used: Attacks, /// Resulting damage damage_done: f64, /// Remaining actions that need to be used to finish reload - reload_remaining: i8, + reload_remaining: Actions, /// A debug value, should be taken down in final builds // TODO[6]: Remove debug once the tests are done depth: u8, @@ -103,15 +155,15 @@ impl BestDamageScenarios { /// Calculate the best alternative with a set of contraints /// /// Returns None if the scenario cant exist with the current conditions (too few actions for an attack to be launched) - fn from_action_constraints( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, + pub fn from_action_constraints( + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, dices_allowed: Dices, precision: Precision, ) -> Option { Self::from_action_constraints_recursive( - value, + equipement_stats, actions_allowed, attacks_allowed, dices_allowed, @@ -124,17 +176,17 @@ impl BestDamageScenarios { /// /// This algorithm takes a recursive approact to avoid too much forward complexity fn from_action_constraints_recursive( - value: &InnerEquipementStats, - actions_allowed: i8, - attacks_allowed: i8, + equipement_stats: &InnerEquipementStats, + actions_allowed: Actions, + attacks_allowed: Attacks, dices_allowed: Dices, precision: Precision, reload_remaining: i8, depth: u8, ) -> Option { // If we can't attack return early - if value.action_cost > actions_allowed - || attacks_allowed == 0 + if equipement_stats.action_cost > *actions_allowed + || *attacks_allowed == 0 || reload_remaining > 0 || *dices_allowed < 1 { @@ -150,18 +202,20 @@ impl BestDamageScenarios { // "Starting recursion: {actions_allowed}A {attacks_allowed}atk {dices_allowed}*" // ); // } - let atkreload_cost = value.reload_cost.unwrap_or_default() + value.action_cost; + let atkreload_cost = + equipement_stats.reload_cost.unwrap_or_default() + equipement_stats.action_cost; // We create our first contender, One attack only let one_attack = Self { // No matter what we try to reload, even if we overcap the attack was still valid - actions_used: (atkreload_cost).clamp(0, actions_allowed), - attacks_used: 1, - damage_done: binomial_dice_distribution(value, precision, dices_allowed), + actions_used: Actions((atkreload_cost).clamp(0, *actions_allowed)), + attacks_used: Attacks(1), + damage_done: binomial_dice_distribution(equipement_stats, precision, dices_allowed), // If the reload+attack exceed the actions, we must bookkeep it // as a reminder that we have leftover actions to spend next turn - reload_remaining: (atkreload_cost - actions_allowed + reload_remaining) - .clamp(0, actions_allowed), + reload_remaining: Actions( + ((atkreload_cost) - *actions_allowed + reload_remaining).clamp(0, *actions_allowed), + ), depth, }; // println!( @@ -172,27 +226,28 @@ impl BestDamageScenarios { // We can only try two attacks if two attack would be valid aka: // - We can spend: 2 attacks and (at least) 1 reload (as actions) // - : 2 attacks (as attacks) - if atkreload_cost + value.action_cost <= actions_allowed && attacks_allowed > 1 { + if atkreload_cost + equipement_stats.action_cost <= *actions_allowed && *attacks_allowed > 1 + { // Cumbersome because of rounding errors if let (Some(a), Some(b)) = ( (Self::from_action_constraints_recursive( - value, + equipement_stats, // TODO[9]: THIS APPROACH IS DEEPLY INCORRECT // : It does however work for the values we will be using it - actions_allowed - atkreload_cost, - attacks_allowed.div_floor(2), + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_floor(2)), Dices(dices_allowed.div_floor(2)), precision, reload_remaining, depth + 1, )), (Self::from_action_constraints_recursive( - value, - actions_allowed - atkreload_cost, - attacks_allowed.div_ceil(2), + equipement_stats, + actions_allowed - Actions(atkreload_cost), + Attacks(attacks_allowed.div_ceil(2)), Dices(dices_allowed.div_ceil(2)), precision, - reload_remaining - value.reload_cost.unwrap_or_default(), + reload_remaining - equipement_stats.reload_cost.unwrap_or_default(), depth + 1, )), ) { @@ -214,23 +269,6 @@ impl BestDamageScenarios { } } -// TODO: Consider implementing something else instead ? -impl InnerEquipementStats { - /// Calculate the average damage expected for a set of precisions and dices - pub(super) fn average_damage(&self, precisions: &[Precision], list_dices: &[Dices]) -> f64 { - precisions - .iter() - .map(|precision| { - list_dices - .iter() - .map(|dices| binomial_dice_distribution(self, *precision, *dices)) - .sum::() - }) - .sum::() - / (precisions.len() as f64 * list_dices.len() as f64) - } -} - /// Calculate the binomial distribution and average the damage from there pub(super) fn binomial_dice_distribution( equipement: &InnerEquipementStats, @@ -268,40 +306,6 @@ pub enum FixedPrecision { Low, } -/// Thin representation of Precision to avoid mistakes -#[derive(Clone, Copy)] -pub struct Precision(pub i8); - -/// Thin representation of Dices to avoid mistakes -#[derive(Clone, Copy)] -pub struct Dices(pub usize); - -impl std::ops::Deref for Precision { - type Target = i8; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Precision { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -impl std::ops::Deref for Dices { - type Target = usize; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl Display for Dices { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - /// The number of dices rolled for a damage simulation #[derive(EnumIter, Clone, Copy, Display)] #[allow(clippy::missing_docs_in_private_items)] @@ -313,9 +317,12 @@ pub enum FixedDiceNumber { #[cfg(test)] mod test { - use crate::weaponry_structs::equipement_structs::InnerEquipementStats; + use crate::weaponry_structs::{ + equipement_structs::InnerEquipementStats, + equipement_thin_types::{Actions, Attacks}, + }; - use super::{BestDamageScenarios, Dices, Precision}; + use super::{BestDamageScenarios, Dices, Precision, binomial_dice_distribution}; fn new_inner_eq() -> InnerEquipementStats { InnerEquipementStats { @@ -334,11 +341,34 @@ mod test { }; } + pub(super) fn average_damage( + equipement: &InnerEquipementStats, + precisions: &[Precision], + list_dices: &[Dices], + ) -> f64 { + precisions + .iter() + .map(|precision| { + list_dices + .iter() + .map(|dices| binomial_dice_distribution(equipement, *precision, *dices)) + .sum::() + }) + .sum::() + / (precisions.len() as f64 * list_dices.len() as f64) + } + #[test] fn basic_binomial() { let eq = new_inner_eq(); - assert_close!(eq.average_damage(&[Precision(9)], &[Dices(9)]), 13.99995162); - assert_close!(eq.average_damage(&[Precision(4)], &[Dices(4)]), 10.1119999); + assert_close!( + average_damage(&eq, &[Precision(9)], &[Dices(9)]), + 13.99995162 + ); + assert_close!( + average_damage(&eq, &[Precision(4)], &[Dices(4)]), + 10.1119999 + ); } #[test] @@ -370,63 +400,153 @@ mod test { }; let known_data = &[ ( - BestDamageScenarios::from_action_constraints(&eq, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq, 2, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(2), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(3), + Precision(10), + ), 30., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq, 3, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq, + Actions(3), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 1, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(1), + Attacks(1), + Dices(3), + Precision(10), + ), 0., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 4, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 5, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(5), + Attacks(3), + Dices(6), + Precision(10), + ), 28., ), ( - BestDamageScenarios::from_action_constraints(&eq2, 6, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq2, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 2, 1, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(2), + Attacks(1), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 4, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(4), + Attacks(2), + Dices(3), + Precision(10), + ), 14., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 6, 2, Dices(3), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(2), + Dices(3), + Precision(10), + ), 22., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 6, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(6), + Attacks(3), + Dices(6), + Precision(10), + ), 28., ), ( - BestDamageScenarios::from_action_constraints(&eq3, 10, 3, Dices(6), Precision(10)), + BestDamageScenarios::from_action_constraints( + &eq3, + Actions(10), + Attacks(3), + Dices(6), + Precision(10), + ), 36., ), ]; diff --git a/weaponry/src/weaponry_structs/equipement_thin_types.rs b/weaponry/src/weaponry_structs/equipement_thin_types.rs new file mode 100644 index 0000000..19175f9 --- /dev/null +++ b/weaponry/src/weaponry_structs/equipement_thin_types.rs @@ -0,0 +1,97 @@ +// Workspace: weaponry +// File: weaponry/src/weaponry_structs/equipement_thin_types.rs +//! Important thin representation to avoid using direct and risky usage of usize,isize etc... + +use std::{ + fmt::Display, + ops::{Add, Sub}, +}; + +/// Thin representation of Precision to avoid mistakes +#[derive(Clone, Copy)] +pub struct Precision(pub i8); + +/// Thin representation of Dices to avoid mistakes +#[derive(Clone, Copy)] +pub struct Dices(pub usize); + +/// Thin representation of Attack to avoid mistakes +#[derive(Clone, Copy, Debug, Default)] +pub struct Attacks(pub i8); + +impl Add for Attacks { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} + +impl std::ops::Deref for Attacks { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} +impl Display for Attacks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} +/// Thin representation of Actions to avoid mistakes +#[derive(Clone, Copy, Default, Debug)] +pub struct Actions(pub i8); + +impl std::ops::Deref for Actions { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Add for Actions { + type Output = Self; + + fn add(self, rhs: Self) -> Self::Output { + Self(self.0 + rhs.0) + } +} +impl Sub for Actions { + type Output = Self; + + fn sub(self, rhs: Self) -> Self::Output { + Self(self.0 - rhs.0) + } +} + +impl Display for Actions { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Precision { + type Target = i8; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Precision { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl std::ops::Deref for Dices { + type Target = usize; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Display for Dices { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} diff --git a/weaponry/src/weaponry_structs/mod.rs b/weaponry/src/weaponry_structs/mod.rs index 9197b22..66d8417 100644 --- a/weaponry/src/weaponry_structs/mod.rs +++ b/weaponry/src/weaponry_structs/mod.rs @@ -26,6 +26,7 @@ mod equipement_impl_logic; mod equipement_impl_math; pub mod equipement_scenario; pub mod equipement_structs; +pub mod equipement_thin_types; mod equipement_views; // Republishes the most used symbols