use std::fmt::{Display, Formatter};
use std::ops::{AddAssign, DivAssign, MulAssign, SubAssign};
#[derive(PartialEq, Debug, Copy, Clone)]
#[cfg_attr(
feature = "bevy",
derive(bevy_reflect::Reflect),
reflect(PartialEq, Debug, Clone)
)]
pub struct Modifier {
pub bonus: i32,
pub multiplier: f32,
}
impl Modifier {
pub fn new(bonus: i32, multiplier: f32) -> Self {
Self { bonus, multiplier }
}
pub fn from_bonus(bonus: i32) -> Self {
Self {
bonus,
..Self::default()
}
}
pub fn from_multiplier(multiplier: f32) -> Self {
Self {
multiplier,
..Self::default()
}
}
pub fn scaled(&self, fraction: f32) -> Self {
Self {
bonus: (self.bonus as f32 * fraction) as i32,
multiplier: (1.0 - fraction) * 1.0 + fraction * self.multiplier,
}
}
}
impl Default for Modifier {
fn default() -> Self {
Self {
bonus: 0,
multiplier: 1.0,
}
}
}
impl AddAssign<i32> for Modifier {
fn add_assign(&mut self, rhs: i32) {
self.bonus += rhs;
}
}
impl SubAssign<i32> for Modifier {
fn sub_assign(&mut self, rhs: i32) {
self.bonus -= rhs;
}
}
impl MulAssign<f32> for Modifier {
fn mul_assign(&mut self, rhs: f32) {
self.multiplier *= rhs;
}
}
impl DivAssign<f32> for Modifier {
fn div_assign(&mut self, rhs: f32) {
self.multiplier /= rhs;
}
}
impl Display for Modifier {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(precision) = f.precision() {
write!(f, "(+{}) x {:.*}", self.bonus, precision, self.multiplier)
} else {
write!(f, "(+{}) x {}", self.bonus, self.multiplier)
}
}
}