Don't spawn fruits in other elements on the grid

This commit is contained in:
2022-08-21 13:08:35 +02:00
parent 84ed6d1ec1
commit b97e279d71
4 changed files with 32 additions and 17 deletions

View File

@@ -29,14 +29,29 @@ fn eaten_event_sent(mut eaten_event_reader: EventReader<EatenEvent>) -> bool {
eaten_event_reader.iter().count() != 0
}
fn spawn_fruit_system(mut commands: Commands) {
// TODO: not spawn in snake
let mut rng = rand::thread_rng();
let coordinate_range = 0..grid::SIZE;
let fruit_coordinate = grid::Coordinate(
rng.gen_range(coordinate_range.clone()),
rng.gen_range(coordinate_range),
);
fn spawn_fruit_system(
mut commands: Commands,
coordinate_query: Query<&grid::Coordinate>,
) {
fn random_coordinate() -> grid::Coordinate {
let mut rng = rand::thread_rng();
let coordinate_range = 0..grid::SIZE;
grid::Coordinate(
rng.gen_range(coordinate_range.clone()),
rng.gen_range(coordinate_range),
)
}
let coordinate_in_other_element = |coordinate: grid::Coordinate| -> bool {
coordinate_query
.iter()
.any(|&snake_coordinate| snake_coordinate == coordinate)
};
let fruit_coordinate = std::iter::repeat(random_coordinate())
.find(|&coordinate| !coordinate_in_other_element(coordinate))
.expect("Should always be found.");
commands
.spawn_bundle(SpriteBundle {