From f57560a1440065c10e10609954d1e34067b9b6f4 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 30 Dec 2020 10:37:26 -0500 Subject: [PATCH] Restart on game over --- src/main.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/main.rs b/src/main.rs index c2487f0..8c24470 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,6 +36,7 @@ struct Materials { struct SnakeMoveTimer(Timer); +struct GameOverEvent; struct GrowthEvent; #[derive(Default)] @@ -130,6 +131,7 @@ fn spawn_segment( fn snake_movement( keyboard_input: Res>, snake_timer: ResMut, + mut game_over_events: ResMut>, mut last_tail_position: ResMut, segments: ResMut, mut heads: Query<(Entity, &mut SnakeHead)>, @@ -173,6 +175,21 @@ fn snake_movement( head_pos.y -= 1; } }; + + // Check if we've hit a wall + if head_pos.x < 0 + || head_pos.y < 0 + || head_pos.x as u32 >= ARENA_WIDTH + || head_pos.y as u32 >= ARENA_HEIGHT + { + game_over_events.send(GameOverEvent); + } + + // Check if we've hit our tail + if segment_positions.contains(&head_pos) { + game_over_events.send(GameOverEvent); + } + segment_positions .iter() .zip(segments.0.iter().skip(1)) @@ -183,6 +200,23 @@ fn snake_movement( } } +fn game_over( + commands: &mut Commands, + mut reader: Local>, + game_over_events: Res>, + materials: Res, + segments_res: ResMut, + food: Query>, + segments: Query>, +) { + if reader.iter(&game_over_events).next().is_some() { + for ent in food.iter().chain(segments.iter()) { + commands.despawn(ent); + } + spawn_snake(commands, materials, segments_res); + } +} + fn snake_eating( commands: &mut Commands, snake_timer: ResMut, @@ -284,6 +318,7 @@ fn main() { .add_resource(SnakeSegments::default()) .add_resource(LastTailPosition::default()) .add_event::() + .add_event::() .add_startup_system(setup.system()) .add_startup_stage("game_setup", SystemStage::single(spawn_snake.system())) .add_system(snake_movement.system()) @@ -293,6 +328,7 @@ fn main() { .add_system(snake_timer.system()) .add_system(snake_eating.system()) .add_system(snake_growth.system()) + .add_system(game_over.system()) .add_plugins(DefaultPlugins) .run(); }