use bevy::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LimitType {
Points(f32),
Percentage(f32),
}
#[derive(Component, Debug, Clone)]
pub struct PowerLimit {
pub id: u32,
pub limit_type: LimitType,
pub color: Color,
pub duration: Option<Timer>,
pub resets_cooldown: bool,
pub power_value: f32,
}
impl PowerLimit {
pub fn new(
id: u32,
limit_type: LimitType,
color: Color,
duration: Option<f32>,
resets_cooldown: bool,
) -> Self {
Self {
id,
limit_type,
color,
duration: duration.map(|d| Timer::from_seconds(d, TimerMode::Once)),
resets_cooldown,
power_value: 0.0,
}
}
pub fn calculate_value(&mut self, base_max: f32) {
self.power_value = match self.limit_type {
LimitType::Points(points) => points,
LimitType::Percentage(percent) => base_max * (percent / 100.0),
};
}
pub fn update(&mut self, delta: f32) -> bool {
if let Some(ref mut timer) = self.duration {
timer.tick(std::time::Duration::from_secs_f32(delta));
timer.is_finished()
} else {
false
}
}
pub fn is_permanent(&self) -> bool {
self.duration.is_none()
}
}
#[derive(Component, Default, Debug)]
pub struct PowerLimits {
pub limits: Vec<PowerLimit>,
}
impl PowerLimits {
pub fn add_limit(&mut self, mut limit: PowerLimit, base_max: f32) {
limit.calculate_value(base_max);
self.limits.push(limit);
}
pub fn remove_limit(&mut self, id: u32) -> bool {
if let Some(index) = self.limits.iter().position(|l| l.id == id) {
self.limits.remove(index);
true
} else {
false
}
}
pub fn total_reduction(&self) -> f32 {
self.limits.iter().map(|l| l.power_value).sum()
}
pub fn update_timers(&mut self, delta: f32) -> Vec<u32> {
let mut removed_ids = Vec::new();
self.limits.retain_mut(|limit| {
if limit.update(delta) {
removed_ids.push(limit.id);
false
} else {
true
}
});
removed_ids
}
pub fn any_resets_cooldown(&self) -> bool {
self.limits.iter().any(|l| l.resets_cooldown)
}
pub fn get_limit_segments(&self, total_max: f32) -> Vec<(Color, f32)> {
self.limits
.iter()
.map(|l| {
let percentage = if total_max > 0.0 {
l.power_value / total_max
} else {
0.0
};
(l.color, percentage)
})
.collect()
}
}