use bevy::{
ecs::component::{ComponentHooks, StorageType},
prelude::*,
};
use crate::{ecs::CommandsExt, event::OnScore, scoring::Score};
#[derive(Reflect)]
#[derive(Clone, Copy, PartialEq, Debug, Default)]
#[reflect(Component)]
pub struct Winning {
threshold: Score,
}
impl Winning {
pub fn new(threshold: impl Into<Score>) -> Self {
Self {
threshold: threshold.into(),
}
}
pub fn threshold(&self) -> Score {
self.threshold
}
pub fn set_threshold(&mut self, threshold: Score) {
self.threshold = threshold.into();
}
fn observer(trigger: Trigger<OnScore>, actor: Query<(&Children, &Winning)>, mut scores: Query<&mut Score>) {
let Ok((children, settings)) = actor.get(trigger.entity()) else {
return;
};
let mut max: f32 = 0.;
for child_score in scores.iter_many(children) {
if child_score.get() > max {
max = child_score.get();
}
}
if max < settings.threshold().get() {
max = 0.;
}
let Ok(mut actor_score) = scores.get_mut(trigger.entity()) else {
return;
};
actor_score.set(max);
}
}
impl Component for Winning {
const STORAGE_TYPE: StorageType = StorageType::Table;
fn register_component_hooks(hooks: &mut ComponentHooks) {
hooks.on_add(|mut world, _entity, _component| {
#[derive(Resource, Default)]
struct WinningObserverSpawned;
world
.commands()
.once::<WinningObserverSpawned>()
.observe(Self::observer);
});
}
}