From f02ba89a93c9ebd1bca49ce554e2049059d597f4 Mon Sep 17 00:00:00 2001 From: Christian Nieves Date: Sun, 8 Dec 2024 02:57:20 -0600 Subject: [PATCH] input system --- src/snake/main.rs | 77 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/src/snake/main.rs b/src/snake/main.rs index 7749638..66efd3b 100644 --- a/src/snake/main.rs +++ b/src/snake/main.rs @@ -6,8 +6,29 @@ const ARENA_WIDTH: u32 = 20; const ARENA_HEIGHT: u32 = 15; const WINDOW_WIDTH: f32 = 1280.0; +#[derive(Eq, PartialEq, Copy, Clone)] +enum Direction { + Up, + Down, + Left, + Right, +} + +impl Direction { + fn opposite(self) -> Self { + match self { + Self::Left => Self::Right, + Self::Right => Self::Left, + Self::Up => Self::Down, + Self::Down => Self::Up, + } + } +} + #[derive(Component)] -struct SnakeHead; +struct SnakeHead { + direction: Direction, +} #[derive(Component)] struct Position { @@ -33,20 +54,43 @@ impl Size { #[derive(Resource)] struct MovementTimer(Timer); -fn snake_movement_system( - input: Res>, - - mut head_transforms: Query<(&SnakeHead, &mut Position)>, -) { - for (_, mut pos) in head_transforms.iter_mut() { - if input.pressed(KeyCode::ArrowUp) { - pos.y += 1; +fn snake_movement_input(input: Res>, mut heads: Query<(&mut SnakeHead)>) { + if let Some(mut head) = heads.iter_mut().next() { + let dir: Direction = if input.pressed(KeyCode::ArrowUp) { + Direction::Up } else if input.pressed(KeyCode::ArrowDown) { - pos.y -= 1; + Direction::Down } else if input.pressed(KeyCode::ArrowLeft) { - pos.x -= 1; + Direction::Left } else if input.pressed(KeyCode::ArrowRight) { - pos.x += 1; + Direction::Right + } else { + head.direction + }; + // allow all inputs except turning around + if dir != head.direction.opposite() { + head.direction = dir; + } + } +} + +fn snake_movement( + input: Res>, + time: Res