database_monsters #139
|
|
@ -6,7 +6,7 @@ resolver = "3"
|
|||
# edition = "2024"
|
||||
# license = "MIT OR Apache-2.0"
|
||||
[workspace.package]
|
||||
version = "0.3.14"
|
||||
version = "0.3.15"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
|
|
@ -61,3 +61,5 @@ indexmap = {version= "2.14.0", features= ["serde"]}
|
|||
rusqlite = { version = "0.40.1" } # , features = ["bundled"]
|
||||
serde_rusqlite = "0.43.0"
|
||||
handlebars = "6.4.3"
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
probability = "0.20.3"
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ rusqlite = {workspace = true}
|
|||
serde_rusqlite = {workspace = true}
|
||||
serde_json = {workspace = true}
|
||||
handlebars = {workspace = true}
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
strum = {workspace = true}
|
||||
probability = {workspace = true}
|
||||
comfy-table = "7.2.2"
|
||||
colored = "3.1.1"
|
||||
|
||||
|
|
|
|||
|
|
@ -3,12 +3,16 @@
|
|||
|
||||
use crate::{
|
||||
Config, Connection, MonsterConfig,
|
||||
monster_analysis::monster_analysis_structs::{ArmorBreakCategory, DamageCategory},
|
||||
monster_database::{fetch_all_creature_data, fetch_all_player_data},
|
||||
monster_render::ToRow,
|
||||
monster_structs::{MonsterFullAttack, PlayerBalancing},
|
||||
monster_render::ToTable,
|
||||
monster_structs::PlayerBalancing,
|
||||
};
|
||||
use comfy_table::{presets, *};
|
||||
use more_fields::FieldsAsSlice;
|
||||
use probability::distribution::Discrete;
|
||||
use probability::prelude::Binomial;
|
||||
use std::cmp::{max, min};
|
||||
pub mod monster_analysis_structs;
|
||||
|
||||
/// Shows balancing information for monsters and players.
|
||||
pub fn show_balancing_data(
|
||||
|
|
@ -17,75 +21,180 @@ pub fn show_balancing_data(
|
|||
connection: Connection,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
let _ = args;
|
||||
let _data = fetch_all_creature_data(&connection, config)?;
|
||||
let data = fetch_all_creature_data(&connection, config)?;
|
||||
let player_data = fetch_all_player_data(&connection, config)?;
|
||||
|
||||
let mut table = Table::new();
|
||||
table
|
||||
.load_preset(presets::UTF8_FULL_CONDENSED)
|
||||
.apply_modifier(modifiers::UTF8_ROUND_CORNERS)
|
||||
.set_content_arrangement(ContentArrangement::Dynamic)
|
||||
.set_width(120)
|
||||
.set_header(
|
||||
PlayerBalancing::attributes_slice()
|
||||
.iter()
|
||||
.map(|(a, _b)| Cell::new(a)),
|
||||
);
|
||||
// table.add_row(player_data.as_slice());
|
||||
// let table = player_data.to_table();
|
||||
|
||||
for entry in player_data {
|
||||
table.add_row(entry.to_row());
|
||||
for creature in data {
|
||||
println!("{}", creature.name);
|
||||
let player_level = &creature.balancing.profile_hse;
|
||||
let available_profiles = player_data
|
||||
.clone()
|
||||
.into_iter()
|
||||
.filter(|v| &v.profile_hse == player_level)
|
||||
.collect::<Vec<PlayerBalancing>>();
|
||||
|
||||
// TODO: This doen't dynamically select profiles !
|
||||
let profile_a = &available_profiles[0];
|
||||
let attacks: Vec<monster_analysis_structs::MonsterBalancingAttack> = creature.into();
|
||||
// let table = attacks.to_table();
|
||||
// println!("{table}");
|
||||
|
||||
let mut res = Vec::new();
|
||||
for attack in attacks {
|
||||
let report = attack_player(&attack, profile_a, DefenseMode::Best).unwrap();
|
||||
res.push(report);
|
||||
}
|
||||
let res = res
|
||||
.into_iter()
|
||||
.filter(|v| {
|
||||
v.damage_category != v.damage_expected || v.armor_expected != v.armor_category
|
||||
})
|
||||
.collect::<Vec<DamageReport>>();
|
||||
println!("{}", res.to_table());
|
||||
}
|
||||
// for creature in data {
|
||||
// println!("{} {:#?}", creature.name, creature.balancing);
|
||||
// }
|
||||
println!("{table}");
|
||||
// println!("{table}");
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum DefenseMode {
|
||||
Best,
|
||||
Worst,
|
||||
}
|
||||
|
||||
impl PlayerBalancing {
|
||||
// /// Estimate what an attack does to a player
|
||||
// pub fn estimate_attack(&self, atk: MonsterAttack) {}
|
||||
pub fn attack_player(
|
||||
attack: &monster_analysis_structs::MonsterBalancingAttack,
|
||||
victim: &PlayerBalancing,
|
||||
mode: DefenseMode,
|
||||
) -> Option<DamageReport> {
|
||||
// How much successes left
|
||||
let threshold = match mode {
|
||||
DefenseMode::Best => max(attack.threshold_parry, attack.threshold_dodge),
|
||||
DefenseMode::Worst => max(attack.threshold_parry, attack.threshold_dodge),
|
||||
} + victim.specialty_def;
|
||||
|
||||
/// Apply an attack to a player, returns the damage done but "healing" afterwards
|
||||
pub fn apply_attack(&mut self, atk: &MonsterAttack) -> DamageDone {
|
||||
let _ = atk;
|
||||
self.health -= 1;
|
||||
DamageDone {
|
||||
armor: 0,
|
||||
health: 0,
|
||||
category: DamageCategory::Low,
|
||||
let bin = binomial_dice_distribution(threshold, victim.successes_def);
|
||||
// let successes_left = attack.successes - thld(victim.successes_def, threshold);
|
||||
let avg_successes_left: f64 = bin
|
||||
.iter()
|
||||
.map(|(dice, p)| (attack.successes - dice) as f64 * p)
|
||||
.sum::<f64>()
|
||||
/ bin.len() as f64;
|
||||
let avg_damage_incomming: f64 = bin
|
||||
.iter()
|
||||
.map(|(dices, p)| {
|
||||
how_much_with_succeses(&attack.damage, attack.successes - dices) as f64 * p
|
||||
})
|
||||
.sum::<f64>();
|
||||
// / bin.len() as f64;
|
||||
|
||||
// println!(
|
||||
// "{} DMG:{:?} {:.2?} Left[{avg_successes_left:.2}/{} with {}] = {avg_damage_incomming}",
|
||||
// attack.name, attack.damage, bin, attack.successes, victim.successes_def
|
||||
// );
|
||||
// let mut damage_incoming = how_much_with_succeses(&attack.damage, successes_left);
|
||||
let damage_incoming = avg_damage_incomming;
|
||||
let damage_tanked = (damage_incoming - (victim.protection + victim.strength) as f64).max(0.0);
|
||||
let armor_loss =
|
||||
(damage_incoming - victim.protection as f64).clamp(0.0, attack.armor_break as f64);
|
||||
// if avg_successes_left < 0.0 {
|
||||
// damage_incoming = 0.0;
|
||||
// damage_tanked = 0.0;
|
||||
// armor_loss = 0.0;
|
||||
// }
|
||||
let report = DamageReport {
|
||||
damage_incoming,
|
||||
damage_tanked,
|
||||
armor_loss,
|
||||
successes_left: avg_successes_left,
|
||||
damage_category: DamageCategory::from_percent(damage_tanked as f64 / victim.health as f64),
|
||||
armor_expected: attack.target_ab,
|
||||
name: attack.name.clone(),
|
||||
damage_expected: attack.target_damage,
|
||||
armor_category: ArmorBreakCategory::from_percent(
|
||||
armor_loss as f64 / victim.integrity as f64,
|
||||
),
|
||||
player_health: victim.health,
|
||||
player_integrity: victim.integrity,
|
||||
threshold,
|
||||
attack_successes: attack.successes,
|
||||
mode,
|
||||
};
|
||||
Some(report)
|
||||
}
|
||||
|
||||
// Binomial damage distribution
|
||||
// As a (0s, p), (1s, p) etc
|
||||
// can be used to calc avg damage
|
||||
// with avg(dmg_with_successes(i)*j)
|
||||
/// Calculate the binomial distribution and average the damage from there
|
||||
pub(super) fn binomial_dice_distribution(threshold: i64, dices: i64) -> Vec<(i64, f64)> {
|
||||
let p = ((threshold as f64) / 10.).clamp(0. + 1E-10, 1. - 1E-10);
|
||||
let binomial = Binomial::new(dices as usize, p);
|
||||
|
||||
(0..(dices + 1) as usize)
|
||||
.map(|target_dices| {
|
||||
let probability_success = binomial.mass(target_dices);
|
||||
(target_dices as i64, probability_success)
|
||||
})
|
||||
.collect::<Vec<(i64, f64)>>()
|
||||
}
|
||||
|
||||
#[derive(Debug, FieldsAsSlice)]
|
||||
pub struct DamageReport {
|
||||
pub name: String,
|
||||
#[INTEGER(name = "dmg_inc")]
|
||||
pub damage_incoming: f64,
|
||||
#[INTEGER(name = "r_left")]
|
||||
pub successes_left: f64,
|
||||
#[INTEGER(name = "dmg_tak")]
|
||||
pub damage_tanked: f64,
|
||||
#[TEXT(name = "dmg_cat")]
|
||||
pub damage_category: DamageCategory,
|
||||
#[TEXT(name = "dmg_expt")]
|
||||
pub damage_expected: DamageCategory,
|
||||
#[INTEGER(name = "arm_loss")]
|
||||
pub armor_loss: f64,
|
||||
#[TEXT(name = "arm_cat")]
|
||||
pub armor_category: ArmorBreakCategory,
|
||||
#[TEXT(name = "arm_expt")]
|
||||
pub armor_expected: ArmorBreakCategory,
|
||||
#[SKIP]
|
||||
pub player_health: i64,
|
||||
#[SKIP]
|
||||
pub player_integrity: i64,
|
||||
#[SKIP]
|
||||
pub threshold: i64,
|
||||
#[SKIP]
|
||||
pub mode: DefenseMode,
|
||||
#[SKIP]
|
||||
pub attack_successes: i64,
|
||||
}
|
||||
|
||||
impl DamageCategory {
|
||||
fn from_percent(percent: f64) -> Self {
|
||||
match percent {
|
||||
..0.01 => Self::None,
|
||||
0.01..0.15 => Self::Chip,
|
||||
0.15..0.5 => Self::Moderate,
|
||||
0.5..0.8 => Self::High,
|
||||
0.8..1.0 => Self::NearDeath,
|
||||
1.0..1.5 => Self::Kill,
|
||||
1.5.. => Self::Overkill,
|
||||
_ => Self::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MonsterAttack<'a> {
|
||||
base_attack: &'a MonsterFullAttack,
|
||||
damage: Vec<usize>,
|
||||
successes: usize,
|
||||
armor_break: usize,
|
||||
action_cost: usize,
|
||||
fn thld(r_succeses: i64, threshold_parry: i64) -> i64 {
|
||||
(r_succeses * min(threshold_parry, 10)) / 10
|
||||
}
|
||||
|
||||
pub struct DamageDone {
|
||||
armor: i64,
|
||||
health: i64,
|
||||
category: DamageCategory,
|
||||
}
|
||||
|
||||
pub enum DamageCategory {
|
||||
/// No lasting damage
|
||||
None,
|
||||
/// Chip damage
|
||||
Low,
|
||||
/// Average, under half
|
||||
Moderate,
|
||||
/// High, above half
|
||||
High,
|
||||
/// Near death 90%
|
||||
NearDeath,
|
||||
/// Kill, above > 100%
|
||||
Kill,
|
||||
/// Complete overkill > 200%
|
||||
Overkill,
|
||||
fn how_much_with_succeses(damage: &[i64], succeses: i64) -> i64 {
|
||||
if succeses <= 0 {
|
||||
0
|
||||
} else {
|
||||
damage[(succeses - 1).clamp(0_i64, damage.len() as i64 - 1) as usize]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,198 @@
|
|||
use crate::monster_structs::{FullMonster, PlayerBalancing, ProfileStance};
|
||||
use more_fields::FieldsAsSlice;
|
||||
use std::str::FromStr;
|
||||
use strum::EnumString;
|
||||
|
||||
impl From<FullMonster> for Vec<MonsterBalancingAttack> {
|
||||
fn from(creature: FullMonster) -> Self {
|
||||
creature
|
||||
.all_attacks
|
||||
.phases
|
||||
.into_iter()
|
||||
.flat_map(|(_, phases)| {
|
||||
phases.into_iter().flat_map(|monster_full_attack| {
|
||||
// let mut cumul = 0;
|
||||
monster_full_attack
|
||||
.attacklist
|
||||
.into_iter()
|
||||
.map(move |sub_attack| {
|
||||
// cumul += from_successes(sub_attack.success.as_ref());
|
||||
MonsterBalancingAttack {
|
||||
damage: damage_from_string(sub_attack.damage_regular.as_ref()),
|
||||
successes: from_successes(sub_attack.success.as_ref()),
|
||||
armor_break: from_opt_i64(sub_attack.armor_break.as_ref()),
|
||||
action_cost: from_actions(sub_attack.cost_action.as_ref()),
|
||||
name: sub_attack.name,
|
||||
threshold_parry: from_opt_i64(sub_attack.threshold_parry.as_ref()),
|
||||
threshold_dodge: from_opt_i64(sub_attack.threshold_dodge.as_ref()),
|
||||
target_damage: sub_attack.target_damage_category.into(),
|
||||
target_ab: sub_attack.target_ab_category.into(),
|
||||
target_stance: sub_attack.target_stance.into(),
|
||||
}
|
||||
})
|
||||
.filter(|sub| !sub.damage.is_empty())
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayerBalancing {
|
||||
// /// Estimate what an attack does to a player
|
||||
// pub fn estimate_attack(&self, atk: MonsterAttack) {}
|
||||
|
||||
/// Apply an attack to a player, returns the damage done but "healing" afterwards
|
||||
pub fn apply_attack(&mut self, atk: &MonsterBalancingAttack) -> DamageDone {
|
||||
let _ = atk;
|
||||
self.health -= 1;
|
||||
DamageDone {
|
||||
armor: 0,
|
||||
health: 0,
|
||||
category: DamageCategory::Chip,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, FieldsAsSlice)]
|
||||
pub struct MonsterBalancingAttack {
|
||||
pub name: String,
|
||||
pub damage: Vec<i64>,
|
||||
#[INTEGER(name = "s")]
|
||||
pub successes: i64,
|
||||
#[INTEGER(name = "ab")]
|
||||
pub armor_break: i64,
|
||||
#[INTEGER(name = "A")]
|
||||
pub action_cost: i64,
|
||||
#[SKIP(name = "parry_t")]
|
||||
pub threshold_parry: i64,
|
||||
#[SKIP(name = "dodge_t")]
|
||||
pub threshold_dodge: i64,
|
||||
#[TEXT(name = "damage_t")]
|
||||
pub target_damage: DamageCategory,
|
||||
#[TEXT(name = "arbreak_t")]
|
||||
pub target_ab: ArmorBreakCategory,
|
||||
#[TEXT(name = "stance_t")]
|
||||
pub target_stance: ProfileStance,
|
||||
}
|
||||
|
||||
pub struct DamageDone {
|
||||
pub(crate) armor: i64,
|
||||
pub(crate) health: i64,
|
||||
pub(crate) category: DamageCategory,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumString, Default, strum::Display, PartialEq)]
|
||||
pub enum DamageCategory {
|
||||
/// Malformed data
|
||||
#[default]
|
||||
Malformed,
|
||||
/// No lasting damage
|
||||
None,
|
||||
/// Chip damage
|
||||
Chip,
|
||||
/// Average, under half
|
||||
Moderate,
|
||||
/// High, above half
|
||||
High,
|
||||
/// Near death 90%
|
||||
NearDeath,
|
||||
/// Kill, above > 100%
|
||||
Kill,
|
||||
/// Complete overkill > 200%
|
||||
Overkill,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, EnumString, Default, strum::Display, PartialEq, Eq)]
|
||||
pub enum ArmorBreakCategory {
|
||||
/// Malformed data
|
||||
#[default]
|
||||
Malformed,
|
||||
/// No lasting damage
|
||||
None,
|
||||
/// Chip damage
|
||||
Chip,
|
||||
/// High, above half
|
||||
High,
|
||||
/// Full destruction
|
||||
FullBreak,
|
||||
/// Complete overkill > 200%
|
||||
Overkill,
|
||||
}
|
||||
|
||||
impl ArmorBreakCategory {
|
||||
pub fn from_percent(value: f64) -> Self {
|
||||
match value {
|
||||
..0.01 => ArmorBreakCategory::None,
|
||||
0.01..0.3 => ArmorBreakCategory::Chip,
|
||||
0.3..0.7 => ArmorBreakCategory::High,
|
||||
0.7..1.2 => ArmorBreakCategory::FullBreak,
|
||||
1.2.. => ArmorBreakCategory::Overkill,
|
||||
_ => ArmorBreakCategory::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<Option<String>> for DamageCategory {
|
||||
fn from(value: Option<String>) -> Self {
|
||||
if let Some(value) = value {
|
||||
Self::from_str(&value).unwrap_or_default()
|
||||
} else {
|
||||
Self::Malformed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Option<String>> for ArmorBreakCategory {
|
||||
fn from(value: Option<String>) -> Self {
|
||||
if let Some(value) = value {
|
||||
Self::from_str(&value).unwrap_or_default()
|
||||
} else {
|
||||
Self::Malformed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Option<String>> for ProfileStance {
|
||||
fn from(value: Option<String>) -> Self {
|
||||
if let Some(value) = value {
|
||||
Self::from_str(&value).unwrap_or_default()
|
||||
} else {
|
||||
Self::Neutral
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn damage_from_string(str: Option<&String>) -> Vec<i64> {
|
||||
match str {
|
||||
Some(str) => str.split("/").map(|v| v.parse().ok()).collect(),
|
||||
None => None,
|
||||
}
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(crate) fn from_successes(str: Option<&String>) -> i64 {
|
||||
match str {
|
||||
Some(str) => str.replace("r", "").parse().unwrap_or_default(),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_actions(str: Option<&String>) -> i64 {
|
||||
match str {
|
||||
Some(str) => str.replace("A", "").parse().unwrap_or_default(),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_opt_str(str: Option<&String>) -> i64 {
|
||||
match str {
|
||||
Some(str) => str.parse().unwrap_or_default(),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn from_opt_i64(val: Option<&i64>) -> i64 {
|
||||
match val {
|
||||
Some(val) => *val,
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,12 @@
|
|||
use comfy_table::Color;
|
||||
use comfy_table::{Cell, Row};
|
||||
use comfy_table::{Color, Table, *};
|
||||
|
||||
use crate::monster_structs::{PlayerBalancing, ProfileHSE, ProfileStance};
|
||||
use crate::{
|
||||
monster_analysis::{
|
||||
DamageReport,
|
||||
monster_analysis_structs::{ArmorBreakCategory, DamageCategory, MonsterBalancingAttack},
|
||||
},
|
||||
monster_structs::{PlayerBalancing, ProfileHSE, ProfileStance},
|
||||
};
|
||||
|
||||
/// Handy trait: “give me the table row that represents this record”
|
||||
pub trait ToCell {
|
||||
|
|
@ -11,7 +16,45 @@ pub trait ToCell {
|
|||
pub trait ToRow {
|
||||
fn to_row(&self) -> Row;
|
||||
}
|
||||
pub trait ToTable {
|
||||
fn to_table(&self) -> Table;
|
||||
}
|
||||
|
||||
impl<T> ToTable for Vec<T>
|
||||
where
|
||||
T: more_fields::FieldsAsSlice + ToRow,
|
||||
{
|
||||
fn to_table(&self) -> Table {
|
||||
let mut table = Table::new();
|
||||
table
|
||||
.load_preset(presets::UTF8_FULL_CONDENSED)
|
||||
.apply_modifier(modifiers::UTF8_ROUND_CORNERS)
|
||||
.set_content_arrangement(ContentArrangement::Dynamic)
|
||||
.set_width(120)
|
||||
.set_header(T::attributes_slice().iter().map(|(a, _b)| Cell::new(a)));
|
||||
// table.add_row(player_data.as_slice());
|
||||
|
||||
for entry in self {
|
||||
table.add_row(entry.to_row());
|
||||
}
|
||||
table
|
||||
}
|
||||
}
|
||||
impl ToRow for MonsterBalancingAttack {
|
||||
fn to_row(&self) -> Row {
|
||||
vec![
|
||||
self.name.to_cell(),
|
||||
self.damage.to_cell(),
|
||||
self.successes.to_cell(),
|
||||
self.armor_break.to_cell(),
|
||||
self.action_cost.to_cell(),
|
||||
self.target_damage.to_cell(),
|
||||
self.target_ab.to_cell(),
|
||||
self.target_stance.to_cell(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
impl ToRow for PlayerBalancing {
|
||||
fn to_row(&self) -> Row {
|
||||
vec![
|
||||
|
|
@ -27,7 +70,103 @@ impl ToRow for PlayerBalancing {
|
|||
.into()
|
||||
}
|
||||
}
|
||||
impl ToRow for DamageReport {
|
||||
fn to_row(&self) -> Row {
|
||||
vec![
|
||||
self.name.to_cell().fg(Color::Green),
|
||||
format!(
|
||||
"{:.1} [{:.1}r]",
|
||||
self.damage_incoming, self.attack_successes,
|
||||
)
|
||||
.to_cell(),
|
||||
format!("{:.1} [>{:.1}]", self.successes_left, self.threshold)
|
||||
.to_cell()
|
||||
.fg(if self.successes_left > 0.0 {
|
||||
Color::Blue
|
||||
} else {
|
||||
Color::Red
|
||||
}),
|
||||
format!("{:.1}/{:.1}", self.damage_tanked, self.player_health)
|
||||
.to_cell()
|
||||
.fg(self.damage_category.get_color()),
|
||||
self.damage_category.to_cell().add_attribute(
|
||||
if self.damage_expected != self.damage_category {
|
||||
Attribute::Reverse
|
||||
} else {
|
||||
Attribute::Dim
|
||||
},
|
||||
),
|
||||
self.damage_expected.to_cell(),
|
||||
format!("{:.1}/{:.1}", self.armor_loss, self.player_integrity)
|
||||
.to_cell()
|
||||
.fg(self.armor_category.get_color()),
|
||||
self.armor_category.to_cell().add_attribute(
|
||||
if self.armor_expected != self.armor_category {
|
||||
Attribute::Reverse
|
||||
} else {
|
||||
Attribute::Dim
|
||||
},
|
||||
),
|
||||
self.armor_expected.to_cell(),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
}
|
||||
impl ToCell for DamageCategory {
|
||||
fn to_cell(&self) -> Cell {
|
||||
Into::<Cell>::into(format!("{self:?}")).fg(self.get_color())
|
||||
}
|
||||
}
|
||||
pub trait ToColor {
|
||||
fn get_color(&self) -> Color;
|
||||
}
|
||||
impl ToColor for DamageCategory {
|
||||
fn get_color(&self) -> Color {
|
||||
match self {
|
||||
DamageCategory::None => Color::DarkGrey,
|
||||
DamageCategory::Chip => Color::DarkBlue,
|
||||
DamageCategory::Moderate => Color::Blue,
|
||||
DamageCategory::High => Color::Green,
|
||||
DamageCategory::NearDeath => Color::Yellow,
|
||||
DamageCategory::Kill => Color::Red,
|
||||
DamageCategory::Overkill => Color::DarkRed,
|
||||
DamageCategory::Malformed => Color::Black,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ToCell for ArmorBreakCategory {
|
||||
fn to_cell(&self) -> Cell {
|
||||
Into::<Cell>::into(format!("{self:?}")).fg(self.get_color())
|
||||
}
|
||||
}
|
||||
|
||||
impl ToColor for ArmorBreakCategory {
|
||||
fn get_color(&self) -> Color {
|
||||
match self {
|
||||
ArmorBreakCategory::None => Color::DarkGrey,
|
||||
ArmorBreakCategory::Chip => Color::Blue,
|
||||
ArmorBreakCategory::High => Color::Yellow,
|
||||
ArmorBreakCategory::FullBreak => Color::Red,
|
||||
ArmorBreakCategory::Overkill => Color::DarkRed,
|
||||
ArmorBreakCategory::Malformed => Color::Black,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ToCell for i64 {
|
||||
fn to_cell(&self) -> Cell {
|
||||
format!("{}", self).into()
|
||||
}
|
||||
}
|
||||
impl ToCell for Vec<i64> {
|
||||
fn to_cell(&self) -> Cell {
|
||||
format!("{self:?}").into()
|
||||
}
|
||||
}
|
||||
impl ToCell for String {
|
||||
fn to_cell(&self) -> Cell {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
impl ToCell for ProfileHSE {
|
||||
fn to_cell(&self) -> Cell {
|
||||
match self {
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@
|
|||
use indexmap::IndexMap;
|
||||
use more_fields::FieldsAsSlice;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use strum::EnumString;
|
||||
|
||||
/// Full data, including monster_data & balancing data
|
||||
pub struct FullData {}
|
||||
|
|
@ -230,6 +231,12 @@ pub struct MonsterSingleAttack {
|
|||
/// Minimum dodge rating required to avoid the ability’s effect.
|
||||
#[INTEGER]
|
||||
pub threshold_dodge: Option<i64>,
|
||||
/// Target level of damage
|
||||
pub target_damage_category: Option<String>,
|
||||
/// Target level of damage
|
||||
pub target_ab_category: Option<String>,
|
||||
/// Target stance of players
|
||||
pub target_stance: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, FieldsAsSlice)]
|
||||
|
|
@ -408,25 +415,25 @@ pub struct CreatureStats {
|
|||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, FieldsAsSlice)]
|
||||
pub struct CreatureBalancing {
|
||||
#[INTEGER]
|
||||
creature_id: i64,
|
||||
pub creature_id: i64,
|
||||
#[TEXT]
|
||||
/// (Fixed) HSE profile of the monster (see `ProfileHSE`).
|
||||
profile_hse: ProfileHSE,
|
||||
pub profile_hse: ProfileHSE,
|
||||
#[INTEGER]
|
||||
/// (Goal) Turns needed to reach phase 2.
|
||||
time_to_p2: i64,
|
||||
pub time_to_p2: i64,
|
||||
#[INTEGER]
|
||||
/// (Goal) Turns until the monster’s armor breaks.
|
||||
time_to_armorbreak: i64,
|
||||
pub time_to_armorbreak: i64,
|
||||
#[INTEGER]
|
||||
/// (GOAL) Avg. turns to kill a single target.
|
||||
time_to_first_kill: i64,
|
||||
pub time_to_first_kill: i64,
|
||||
#[INTEGER]
|
||||
/// (FIXED) Size of a single monster group (usually one).
|
||||
monster_groupsize: i64,
|
||||
pub monster_groupsize: i64,
|
||||
#[INTEGER]
|
||||
/// (FIXED) The number of players this fight was designed for
|
||||
player_groupsize: i64,
|
||||
pub player_groupsize: i64,
|
||||
}
|
||||
|
||||
/// Balancing info on all the player depending on their level
|
||||
|
|
@ -461,13 +468,20 @@ pub struct PlayerBalancing {
|
|||
#[INTEGER]
|
||||
/// Current health points.
|
||||
pub health: i64,
|
||||
#[INTEGER]
|
||||
/// Current precision.
|
||||
pub precision: i64,
|
||||
#[INTEGER]
|
||||
/// Current deffensive specialty.
|
||||
pub specialty_def: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, EnumString)]
|
||||
/// Player stance preference used for balance tables.
|
||||
pub enum ProfileStance {
|
||||
Defensive,
|
||||
Offensive,
|
||||
#[default]
|
||||
Neutral,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
|
|||
|
|
@ -5,28 +5,24 @@
|
|||
//! however this limitation is completely artificial
|
||||
|
||||
pub use more_fields_macro::FieldsAsSlice;
|
||||
pub use more_fields_macro::InstanceAsArray;
|
||||
|
||||
pub trait FieldsAsSlice {
|
||||
fn attributes_slice() -> &'static [(&'static str, &'static str)];
|
||||
}
|
||||
|
||||
// fn iter(&self) -> std::vec::IntoIter<(&'static str, &'static str)>;
|
||||
/// Converts an instance into a homogeneous array.
|
||||
///
|
||||
/// The array length is determined by the derive macro.
|
||||
pub trait InstanceAsArray {
|
||||
/// Element type of the generated array.
|
||||
type Item;
|
||||
|
||||
// #[cfg(feature = "expand_macro")]
|
||||
// #[derive(FieldsAsSlice, Default)]
|
||||
// struct Bob {
|
||||
// #[TEXT]
|
||||
// field_ouane: u16,
|
||||
// #[INTEGER]
|
||||
// field_2: u16,
|
||||
// #[BLOB]
|
||||
// field_3: u16,
|
||||
// #[NULL]
|
||||
// field_4: u16,
|
||||
// #[REAL]
|
||||
// field_5: u16,
|
||||
// field_6: u16,
|
||||
// }
|
||||
// /// Concrete array type, e.g. `[Value; 5]`.
|
||||
// type Array: AsRef<Vec<Self::Item>>;
|
||||
|
||||
fn instance_as_array(&self) -> Vec<Self::Item>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
|
@ -63,4 +59,67 @@ mod test {
|
|||
|
||||
assert_eq!(Bob::attributes_slice(), b_hash);
|
||||
}
|
||||
use crate::InstanceAsArray;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Value {
|
||||
Integer(i64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl From<i32> for Value {
|
||||
fn from(v: i32) -> Self {
|
||||
Value::Integer(v as i64)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for Value {
|
||||
fn from(v: String) -> Self {
|
||||
Value::Text(v)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FieldsAsSlice, InstanceAsArray)]
|
||||
#[InstanceAsArray(Type = String)]
|
||||
struct Person {
|
||||
#[INTEGER]
|
||||
id: String,
|
||||
|
||||
#[TEXT]
|
||||
name: String,
|
||||
|
||||
#[SKIP]
|
||||
cached: String,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn instance_as_array_works() {
|
||||
let person = Person {
|
||||
id: "Alice".into(),
|
||||
name: "Alice".into(),
|
||||
cached: "Alice".into(),
|
||||
};
|
||||
assert!(person.cached == "Alice",);
|
||||
let array = person.instance_as_array();
|
||||
let slice = array.as_ref();
|
||||
|
||||
assert_eq!(slice, &["Alice".to_string(), "Alice".to_string(),]);
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn attributes_slice_matches_instance_array() {
|
||||
// let attrs = Person::attributes_slice();
|
||||
|
||||
// assert_eq!(attrs, &[("id", "INTEGER"), ("name", "TEXT"),]);
|
||||
|
||||
// let values = Person {
|
||||
// id: 1,
|
||||
// name: "Bob".into(),
|
||||
// cached: false,
|
||||
// }
|
||||
// .instance_as_array();
|
||||
|
||||
// assert_eq!(attrs.len(), values.as_ref().len());
|
||||
// }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,4 +8,4 @@ proc-macro = true
|
|||
|
||||
[dependencies]
|
||||
quote = "1.0.46"
|
||||
syn = "2.0.118"
|
||||
syn = {version= "2.0.118", features=["full"]}
|
||||
|
|
|
|||
|
|
@ -12,64 +12,109 @@
|
|||
// use proc_macro::TokenStream;
|
||||
// use quote::quote;
|
||||
// use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
#![feature(coverage_attribute)]
|
||||
extern crate proc_macro;
|
||||
|
||||
use proc_macro::{Span, TokenStream};
|
||||
use proc_macro::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::DeriveInput;
|
||||
use syn::Ident;
|
||||
use syn::parse_macro_input;
|
||||
use syn::{Data, Fields};
|
||||
use syn::{Data, DeriveInput, Fields, parse_macro_input};
|
||||
|
||||
#[coverage(off)]
|
||||
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB))]
|
||||
/// The macro can now be used on structs that have a mix of the
|
||||
/// following field‑level attributes:
|
||||
/// * INTEGER, NULL, REAL, TEXT, BLOB → SQLite column type
|
||||
/// * SKIP → omit this field from the slice
|
||||
///
|
||||
/// Example usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// #[derive(FieldsAsSlice)]
|
||||
/// struct Person {
|
||||
/// #[INTEGER] id: i32,
|
||||
/// #[TEXT] name: String,
|
||||
/// #[SKIP] secret_code: String, // will not appear in `attributes_slice()`
|
||||
/// }
|
||||
/// ```
|
||||
#[proc_macro_derive(FieldsAsSlice, attributes(INTEGER, NULL, REAL, TEXT, BLOB, SKIP))]
|
||||
pub fn derive_iterable(input: TokenStream) -> TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
let struct_name = input.ident;
|
||||
|
||||
// collect named fields only
|
||||
let fields = match input.data {
|
||||
Data::Struct(data_struct) => {
|
||||
// let list_attrs = input.attrs.iter().map(|v| v.path());
|
||||
match data_struct.fields {
|
||||
Fields::Named(fields_named) => fields_named.named,
|
||||
_ => panic!("Only structs with named fields are supported"),
|
||||
}
|
||||
}
|
||||
Data::Struct(data_struct) => match data_struct.fields {
|
||||
Fields::Named(f_named) => f_named.named,
|
||||
_ => panic!("Only structs with named fields are supported"),
|
||||
},
|
||||
_ => panic!("Only structs are supported"),
|
||||
};
|
||||
|
||||
let fields_iter = fields.iter().map(|field| {
|
||||
let field_ident = &field.ident;
|
||||
let val = field
|
||||
.attrs
|
||||
.iter()
|
||||
.map(|v| v.path().get_ident())
|
||||
.next()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| syn::Ident::new("TEXT", Span::call_site().into()))
|
||||
.to_string();
|
||||
let field_name = field_ident.as_ref().unwrap().to_string();
|
||||
quote! {
|
||||
(#field_name, #val)
|
||||
// For each field: * skip if `#[SKIP]` is present
|
||||
// * otherwise find the first of the type attributes, or default to TEXT
|
||||
let fields_iter = fields.iter().filter_map(|field| {
|
||||
// Skip fields marked with #[SKIP]
|
||||
if field.attrs.iter().any(|a| a.path().is_ident("SKIP")) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut sqlite_type = "TEXT".to_string();
|
||||
let mut exported_name = field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("Expected named field")
|
||||
.to_string();
|
||||
|
||||
for attr in &field.attrs {
|
||||
let ident = match attr.path().get_ident() {
|
||||
Some(i) => i.to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if !matches!(
|
||||
ident.as_str(),
|
||||
"INTEGER" | "NULL" | "REAL" | "TEXT" | "BLOB"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sqlite_type = ident;
|
||||
|
||||
// Parse optional: #[TEXT(name = "...")]
|
||||
let _ = attr.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("name") {
|
||||
let value = meta.value()?;
|
||||
let lit: syn::LitStr = value.parse()?;
|
||||
exported_name = lit.value();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(meta.error("expected `name = \"...\"`"))
|
||||
}
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
Some(quote! {
|
||||
(#exported_name, #sqlite_type)
|
||||
})
|
||||
});
|
||||
// Build a unique static name for the slice.
|
||||
let const_name_str = format!(
|
||||
"{}_ATTR_SLICE",
|
||||
struct_name.to_string().to_ascii_uppercase()
|
||||
);
|
||||
let const_name = syn::Ident::new(&const_name_str, proc_macro::Span::call_site().into());
|
||||
|
||||
let name_of_static_str = struct_name.to_string().to_ascii_uppercase() + "_ATTR_SLICE";
|
||||
let name_of_static = Ident::new(&name_of_static_str, Span::call_site().into());
|
||||
|
||||
// Finally emit the implementation
|
||||
let expanded = quote! {
|
||||
/// Derived implementation of a (attribute, type) slice
|
||||
/// allowing a constant time serialisation & deserialisation into rusqlite
|
||||
const #name_of_static: &[(&str, &str)] = &[
|
||||
/// Generated slice containing `(field_name, sqlite_type)` pairs.
|
||||
///
|
||||
/// The slice is `static` so it can be used in zero‑alloc scenarios.
|
||||
const #const_name: &[(&str, &str)] = &[
|
||||
#(#fields_iter),*
|
||||
];
|
||||
|
||||
impl FieldsAsSlice for #struct_name {
|
||||
/// Gives a precompiled slice of the &[(fields: &str, sqlite_type: &str)]
|
||||
fn attributes_slice<'a>() -> &'static [(&'static str, &'static str)] {
|
||||
#name_of_static
|
||||
&#const_name
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -77,7 +122,63 @@ pub fn derive_iterable(input: TokenStream) -> TokenStream {
|
|||
TokenStream::from(expanded)
|
||||
}
|
||||
|
||||
// As an hashmap (incorrect as of no ordering)
|
||||
// let mut h = std::collections::HashMap::new();
|
||||
// #(h.insert(#fields_iter);)*
|
||||
// h
|
||||
#[proc_macro_derive(InstanceAsArray, attributes(InstanceAsArray, SKIP))]
|
||||
pub fn derive_instance_as_array(input: TokenStream) -> TokenStream {
|
||||
use syn::{Data, DeriveInput, Fields, Type, parse_macro_input};
|
||||
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
let struct_name = &input.ident;
|
||||
|
||||
// Read #[InstanceAsSlice(Type = "...")]
|
||||
let mut output_ty: Option<Type> = None;
|
||||
|
||||
for attr in &input.attrs {
|
||||
if !attr.path().is_ident("InstanceAsArray") {
|
||||
continue;
|
||||
}
|
||||
|
||||
attr.parse_nested_meta(|meta| {
|
||||
if meta.path.is_ident("Type") {
|
||||
let value = meta.value()?;
|
||||
let ty: Type = value.parse()?;
|
||||
output_ty = Some(ty);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(meta.error("expected `Type = ...`"))
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let output_ty = output_ty.expect("Missing #[InstanceAsArray(Type = YourType)] attribute.");
|
||||
|
||||
let fields = match &input.data {
|
||||
Data::Struct(data) => match &data.fields {
|
||||
Fields::Named(fields) => &fields.named,
|
||||
_ => panic!("Only named structs are supported."),
|
||||
},
|
||||
_ => panic!("Only structs are supported."),
|
||||
};
|
||||
|
||||
let field_idents: Vec<_> = fields
|
||||
.iter()
|
||||
.filter(|field| !field.attrs.iter().any(|a| a.path().is_ident("SKIP")))
|
||||
.map(|field| field.ident.as_ref().unwrap())
|
||||
.collect();
|
||||
|
||||
let field_count = field_idents.len();
|
||||
|
||||
let expanded = quote! {
|
||||
impl #struct_name {
|
||||
pub fn instance_as_array(&self) -> [#output_ty; #field_count] {
|
||||
[
|
||||
#(
|
||||
::core::convert::Into::<#output_ty>::into(&self.#field_idents)
|
||||
),*
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
TokenStream::from(expanded)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,12 +11,12 @@ regex = {workspace = true}
|
|||
csv = {workspace = true}
|
||||
serde = {workspace = true}
|
||||
comfy-table = "7.2.2"
|
||||
probability = "0.20.3"
|
||||
probability = {workspace = true}
|
||||
rusqlite = {workspace = true}
|
||||
serde_rusqlite = {workspace = true}
|
||||
serde_json = {workspace = true}
|
||||
handlebars = {workspace = true}
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
strum = {workspace = true}
|
||||
thiserror = "2.0.18"
|
||||
charming = { version = "0.4.0", features = [] }
|
||||
|
||||
|
|
|
|||
|
|
@ -355,12 +355,9 @@ mod test {
|
|||
let eq = new_inner_eq();
|
||||
assert_close!(
|
||||
average_damage(&eq, &[Precision(9)], &[Dices(9)]),
|
||||
13.999999999
|
||||
);
|
||||
assert_close!(
|
||||
average_damage(&eq, &[Precision(4)], &[Dices(4)]),
|
||||
10.1119999
|
||||
11.999999826
|
||||
);
|
||||
assert_close!(average_damage(&eq, &[Precision(4)], &[Dices(4)]), 9.753599);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -401,7 +398,7 @@ mod test {
|
|||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
14.,
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -461,7 +458,7 @@ mod test {
|
|||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
14.,
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -481,7 +478,7 @@ mod test {
|
|||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
28.,
|
||||
24.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -501,7 +498,7 @@ mod test {
|
|||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
14.,
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -511,7 +508,7 @@ mod test {
|
|||
Dices(3),
|
||||
Precision(10),
|
||||
),
|
||||
14.,
|
||||
12.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -531,7 +528,7 @@ mod test {
|
|||
Dices(6),
|
||||
Precision(10),
|
||||
),
|
||||
28.,
|
||||
24.,
|
||||
),
|
||||
(
|
||||
BestDamageScenarios::from_action_constraints_it(
|
||||
|
|
@ -581,15 +578,15 @@ mod test {
|
|||
};
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq1, Actions(2), Attacks(1)),
|
||||
8.3998
|
||||
7.1999
|
||||
);
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq2, Actions(2), Attacks(1)),
|
||||
9.6936
|
||||
8.3624
|
||||
);
|
||||
assert_close!(
|
||||
get_damage_with_simulation(&eq3, Actions(2), Attacks(1)),
|
||||
9.6936
|
||||
8.36249
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
Subproject commit 01dbdc14a30d63a555aa5848619f941585934fd3
|
||||
Subproject commit abacba00c4b888241d47bfb2621322d5586f77d4
|
||||
Loading…
Reference in New Issue