From 8a713ba6858769510539b9ce39370eeeebb852b4 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 30 Dec 2020 10:26:25 -0500 Subject: [PATCH] Growing the snake --- src/main.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 93dbf09..c2487f0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -36,6 +36,11 @@ struct Materials { struct SnakeMoveTimer(Timer); +struct GrowthEvent; + +#[derive(Default)] +struct LastTailPosition(Option); + struct SnakeSegment; #[derive(Default)] @@ -125,6 +130,7 @@ fn spawn_segment( fn snake_movement( keyboard_input: Res>, snake_timer: ResMut, + mut last_tail_position: ResMut, segments: ResMut, mut heads: Query<(Entity, &mut SnakeHead)>, mut positions: Query<&mut Position>, @@ -172,7 +178,45 @@ fn snake_movement( .zip(segments.0.iter().skip(1)) .for_each(|(pos, segment)| { *positions.get_mut(*segment).unwrap() = *pos; - }) + }); + last_tail_position.0 = Some(*segment_positions.last().unwrap()); + } +} + +fn snake_eating( + commands: &mut Commands, + snake_timer: ResMut, + mut growth_events: ResMut>, + food_positions: Query<(Entity, &Position), With>, + head_positions: Query<&Position, With>, +) { + if !snake_timer.0.finished() { + return; + } + for head_pos in head_positions.iter() { + for (ent, food_pos) in food_positions.iter() { + if food_pos == head_pos { + commands.despawn(ent); + growth_events.send(GrowthEvent); + } + } + } +} + +fn snake_growth( + commands: &mut Commands, + last_tail_position: Res, + growth_events: Res>, + mut segments: ResMut, + mut growth_reader: Local>, + materials: Res, +) { + if growth_reader.iter(&growth_events).next().is_some() { + segments.0.push(spawn_segment( + commands, + &materials.segment_material, + last_tail_position.0.unwrap(), + )); } } @@ -238,6 +282,8 @@ fn main() { }) .add_resource(SnakeMoveTimer(Timer::new(Duration::from_millis(150), true))) .add_resource(SnakeSegments::default()) + .add_resource(LastTailPosition::default()) + .add_event::() .add_startup_system(setup.system()) .add_startup_stage("game_setup", SystemStage::single(spawn_snake.system())) .add_system(snake_movement.system()) @@ -245,6 +291,8 @@ fn main() { .add_system(size_scaling.system()) .add_system(food_spawner.system()) .add_system(snake_timer.system()) + .add_system(snake_eating.system()) + .add_system(snake_growth.system()) .add_plugins(DefaultPlugins) .run(); }