Created
November 9, 2020 15:45
-
-
Save RichoDemus/02541547c7c4844eeb04d72089817177 to your computer and use it in GitHub Desktop.
Writing some legion code to potentially submit an example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::thread::sleep; | |
use std::time::Duration; | |
use legion::*; | |
#[derive(Clone, Copy, Debug, PartialEq)] | |
struct Countdown { | |
value: i32, | |
} | |
#[derive(Clone, Copy, Debug, PartialEq)] | |
struct BelowFifty; | |
/// Simple legion program that continuously creates entites that counts down from 200 to 0 | |
/// when an entity's count reaches 0 it's deleted | |
/// Also adds the component BelowFifty to entnties which count is less than 50 | |
fn main() { | |
let mut world = World::default(); | |
loop { | |
//insert a new entity | |
world.push((Countdown { value: 200 },)); | |
// decrement all entities | |
<&mut Countdown>::query().for_each_mut(&mut world, |countdown| { | |
countdown.value -= 1; | |
}); | |
//Add BelowFifty component if countdown < 50 | |
{ | |
let entities_with_less_than_fifty = <&Countdown>::query() | |
.iter_chunks(&world) | |
.flat_map(|chunk| chunk.into_iter_entities()) | |
.filter(|(_, countdown)| countdown.value < 50) | |
.map(|(entity, _)| entity) | |
.collect::<Vec<_>>(); | |
for entity in entities_with_less_than_fifty { | |
if let Some(mut entry) = world.entry(entity) { | |
entry.add_component(BelowFifty); | |
} | |
} | |
} | |
// find and remove entities that have reached zero | |
{ | |
let entities_to_remove = <&Countdown>::query() | |
.iter_chunks(&world) | |
.flat_map(|chunk| chunk.into_iter_entities()) | |
.filter(|(_, countdown)| countdown.value < 1) | |
.map(|(entity, _)| entity) | |
.collect::<Vec<_>>(); | |
for entity in entities_to_remove { | |
world.remove(entity); | |
} | |
} | |
// print entities | |
<&Countdown>::query() | |
.filter(!component::<BelowFifty>()) | |
.for_each_chunk(&world, |chunck| { | |
for entity in chunck { | |
println!("Entity above fifty: {:?}", entity); | |
} | |
}); | |
<&Countdown>::query() | |
.filter(component::<BelowFifty>()) | |
.for_each_chunk(&world, |chunck| { | |
for entity in chunck { | |
println!("Entity below fifty: {:?}", entity); | |
} | |
}); | |
// ZZZZZZ | |
sleep(Duration::from_millis(10)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment