Restart on game over

This commit is contained in:
Timothy Warren 2020-12-30 10:37:26 -05:00
parent 8a713ba685
commit f57560a144

View File

@ -36,6 +36,7 @@ struct Materials {
struct SnakeMoveTimer(Timer); struct SnakeMoveTimer(Timer);
struct GameOverEvent;
struct GrowthEvent; struct GrowthEvent;
#[derive(Default)] #[derive(Default)]
@ -130,6 +131,7 @@ fn spawn_segment(
fn snake_movement( fn snake_movement(
keyboard_input: Res<Input<KeyCode>>, keyboard_input: Res<Input<KeyCode>>,
snake_timer: ResMut<SnakeMoveTimer>, snake_timer: ResMut<SnakeMoveTimer>,
mut game_over_events: ResMut<Events<GameOverEvent>>,
mut last_tail_position: ResMut<LastTailPosition>, mut last_tail_position: ResMut<LastTailPosition>,
segments: ResMut<SnakeSegments>, segments: ResMut<SnakeSegments>,
mut heads: Query<(Entity, &mut SnakeHead)>, mut heads: Query<(Entity, &mut SnakeHead)>,
@ -173,6 +175,21 @@ fn snake_movement(
head_pos.y -= 1; 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 segment_positions
.iter() .iter()
.zip(segments.0.iter().skip(1)) .zip(segments.0.iter().skip(1))
@ -183,6 +200,23 @@ fn snake_movement(
} }
} }
fn game_over(
commands: &mut Commands,
mut reader: Local<EventReader<GameOverEvent>>,
game_over_events: Res<Events<GameOverEvent>>,
materials: Res<Materials>,
segments_res: ResMut<SnakeSegments>,
food: Query<Entity, With<Food>>,
segments: Query<Entity, With<SnakeSegment>>,
) {
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( fn snake_eating(
commands: &mut Commands, commands: &mut Commands,
snake_timer: ResMut<SnakeMoveTimer>, snake_timer: ResMut<SnakeMoveTimer>,
@ -284,6 +318,7 @@ fn main() {
.add_resource(SnakeSegments::default()) .add_resource(SnakeSegments::default())
.add_resource(LastTailPosition::default()) .add_resource(LastTailPosition::default())
.add_event::<GrowthEvent>() .add_event::<GrowthEvent>()
.add_event::<GameOverEvent>()
.add_startup_system(setup.system()) .add_startup_system(setup.system())
.add_startup_stage("game_setup", SystemStage::single(spawn_snake.system())) .add_startup_stage("game_setup", SystemStage::single(spawn_snake.system()))
.add_system(snake_movement.system()) .add_system(snake_movement.system())
@ -293,6 +328,7 @@ fn main() {
.add_system(snake_timer.system()) .add_system(snake_timer.system())
.add_system(snake_eating.system()) .add_system(snake_eating.system())
.add_system(snake_growth.system()) .add_system(snake_growth.system())
.add_system(game_over.system())
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins)
.run(); .run();
} }