diff --git a/src/main.rs b/src/main.rs index 0430d6a..c53a652 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,12 +25,16 @@ impl Size { } } -struct SnakeHead; +struct SnakeHead { + direction: Direction, +} struct Materials { head_material: Handle, food_material: Handle, } +struct SnakeMoveTimer(Timer); + struct Food; struct FoodSpawnTimer(Timer); @@ -40,6 +44,24 @@ impl Default for FoodSpawnTimer { } } +#[derive(PartialEq, Copy, Clone)] +enum Direction { + Left, + Up, + Right, + Down, +} +impl Direction { + fn opposite(self) -> Self { + match self { + Self::Left => Self::Right, + Self::Right => Self::Left, + Self::Up => Self::Down, + Self::Down => Self::Up, + } + } +} + fn setup(commands: &mut Commands, mut materials: ResMut>) { commands.spawn(Camera2dBundle::default()); commands.insert_resource(Materials { @@ -55,28 +77,52 @@ fn spawn_snake(commands: &mut Commands, materials: Res) { sprite: Sprite::new(Vec2::new(10.0, 10.0)), ..Default::default() }) - .with(SnakeHead) + .with(SnakeHead { + direction: Direction::Up, + }) .with(Position { x: 3, y: 3 }) .with(Size::square(0.8)); } fn snake_movement( keyboard_input: Res>, - mut head_positions: Query<&mut Position, With>, + snake_timer: ResMut, + mut heads: Query<(Entity, &mut SnakeHead)>, + mut positions: Query<&mut Position>, ) { - for mut pos in head_positions.iter_mut() { - if keyboard_input.pressed(KeyCode::Left) { - pos.x -= 1; + if let Some((head_entity, mut head)) = heads.iter_mut().next() { + let mut head_pos = positions.get_mut(head_entity).unwrap(); + let dir: Direction = if keyboard_input.pressed(KeyCode::Left) { + Direction::Left + } else if keyboard_input.pressed(KeyCode::Down) { + Direction::Down + } else if keyboard_input.pressed(KeyCode::Up) { + Direction::Up + } else if keyboard_input.pressed(KeyCode::Right) { + Direction::Right + } else { + head.direction + }; + if dir != head.direction.opposite() { + head.direction = dir; } - if keyboard_input.pressed(KeyCode::Right) { - pos.x += 1; - } - if keyboard_input.pressed(KeyCode::Down) { - pos.y -= 1; - } - if keyboard_input.pressed(KeyCode::Up) { - pos.y += 1; + if !snake_timer.0.finished() { + return; } + match &head.direction { + Direction::Left => { + head_pos.x -= 1; + } + Direction::Right => { + head_pos.x += 1; + } + Direction::Up => { + head_pos.y += 1; + } + Direction::Down => { + head_pos.y -= 1; + } + }; } } @@ -127,6 +173,10 @@ fn food_spawner( } } +fn snake_timer(time: Res