diff options
author | HampusM <hampus@hampusmat.com> | 2024-05-19 21:12:07 +0200 |
---|---|---|
committer | HampusM <hampus@hampusmat.com> | 2024-05-19 21:14:55 +0200 |
commit | 9863b431950c681225f8774af244a56adbd18937 (patch) | |
tree | c487a12b9a7b4d362687d9fa065748af1f12cca8 /ecs/examples | |
parent | 355a19e630de61397bf70b69b7ab2356318be2b8 (diff) |
feat(ecs): add support for optional query components
Diffstat (limited to 'ecs/examples')
-rw-r--r-- | ecs/examples/optional_component.rs | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/ecs/examples/optional_component.rs b/ecs/examples/optional_component.rs new file mode 100644 index 0000000..e47bf2e --- /dev/null +++ b/ecs/examples/optional_component.rs @@ -0,0 +1,86 @@ +use ecs::event::Event; +use ecs::{Component, Query, World}; + +#[derive(Debug, Component)] +struct PettingCapacity +{ + capacity_left: u32, +} + +#[derive(Debug, Clone, Copy, Component)] +enum Aggressivity +{ + High, + Medium, + Low, +} + +#[derive(Debug, Component)] +pub struct CatName +{ + name: String, +} + +fn pet_cats(query: Query<(CatName, PettingCapacity, Option<Aggressivity>)>) +{ + for (cat_name, mut petting_capacity, aggressivity) in &query { + let Some(aggressivity) = aggressivity else { + println!("Aggressivity of cat {} is unknown. Skipping", cat_name.name); + continue; + }; + + if let Aggressivity::High = *aggressivity { + println!("Cat {} is aggressive. Skipping", cat_name.name); + continue; + } + + if petting_capacity.capacity_left == 0 { + println!( + "Cat {} have had enough of being petted. Skipping", + cat_name.name + ); + continue; + } + + println!("Petting cat {}", cat_name.name); + + petting_capacity.capacity_left -= 1; + } +} + +#[derive(Debug)] +struct PettingTime; + +impl Event for PettingTime {} + +fn main() +{ + let mut world = World::new(); + + world.register_system(PettingTime, pet_cats); + + world.create_entity(( + CatName { name: "Jasper".to_string() }, + Aggressivity::Medium, + PettingCapacity { capacity_left: 5 }, + )); + + world.create_entity(( + CatName { name: "Otto".to_string() }, + PettingCapacity { capacity_left: 9 }, + )); + + world.create_entity(( + CatName { name: "Carrie".to_string() }, + PettingCapacity { capacity_left: 2 }, + Aggressivity::High, + )); + + world.create_entity(( + CatName { name: "Tommy".to_string() }, + PettingCapacity { capacity_left: 1 }, + Aggressivity::Low, + )); + + world.emit(PettingTime); +} |