index : snake-rs
An implementation of the classic Snake game in Rust using SDL2
about summary refs log tree commit diff

Diffstat (limited to 'src/game_context.rs')

-rw-r--r-- src/game_context.rs 33
 1 file changed, 17 insertions(+), 16 deletions(-)

diff --git a/src/game_context.rs b/src/game_context.rs
index ab2dec6..7109b05 100644
--- a/src/game_context.rs
+++ b/src/game_context.rs
@@ -7,9 +7,18 @@
pub enum GameState {
    Playing,
    Paused,
    Over,
    GameOver,
}

#[derive(PartialEq, Clone, Copy)]
pub enum GameEvent {
    Resume,
    Restart,
    Quit,
    FoodEaten,
    Died,
}

#[derive(Copy, Clone, PartialEq)]
pub enum PlayerDirection {
    Up,
@@ -46,17 +55,16 @@
        })
    }

    pub fn next_tick(&mut self) {
    pub fn next_tick(&mut self) -> Option<GameEvent> {
        if self.state != GameState::Playing {
            return;
            return None;
        }

        let back_position = *self.player_position.last().unwrap();
        let next_head_position = self.next_head_position(self.player_direction);

        if self.player_position.contains(&next_head_position) {
            self.state = GameState::Over;
            return;
            return Some(GameEvent::Died);
        }
        self.player_position.insert(0, next_head_position);

@@ -66,9 +74,11 @@
            self.food.retain(|p| *p != next_head_position);

            self.generate_food();
            return Some(GameEvent::FoodEaten);
        } else {
            self.player_position.pop();
        }
        None
    }

    // Food
@@ -139,19 +149,10 @@
                head
            }
            _ => next_head_position,
        }
    }

    // Game State
    pub fn toggle_pause(&mut self) {
        self.state = match self.state {
            GameState::Playing => GameState::Paused,
            GameState::Paused => GameState::Playing,
            _ => return,
        }
    }

    pub fn restart(&self) {
        todo!()
    pub fn restart(&mut self) {
        *self = Self::new().unwrap();
    }
}