rsnaker/game_logic/state.rs
1//! # Game State Management
2//!
3//! This module defines a `GameState` struct that manages game-related flags
4//! such as life, score, and game status.
5//! It provides methods for initializing and resetting the game state.
6//!
7//! # Example
8//! ```rust
9//! use rsnaker::game_logic::state::{GameState, GameStatus};
10//!
11//! let mut state = GameState::new(3); // Initialize game_logic with 3 lives
12//! assert_eq!(state.life, 3);
13//! assert_eq!(state.score, 0);
14//! assert_eq!(state.status, GameStatus::Playing);
15//!
16//! state.reset(); // Reset game_logic state
17//! assert_eq!(state.life, 3);
18//! assert_eq!(state.score, 0);
19//! ```
20//!
21
22/// Represents the possible options in the Game Over menu.
23#[derive(Debug, Clone, PartialEq, Copy, Default)]
24pub enum GameOverMenu {
25 #[default]
26 // Because restart is the selected option by default after GameOver but will not restart
27 // automatically unless pressing an entrance key or R
28 Restart,
29 Menu,
30 Quit,
31}
32
33impl GameOverMenu {
34 #[must_use]
35 pub fn next(self) -> Self {
36 match self {
37 Self::Restart => Self::Menu,
38 Self::Menu => Self::Quit,
39 Self::Quit => Self::Restart,
40 }
41 }
42
43 #[must_use]
44 pub fn previous(self) -> Self {
45 match self {
46 Self::Restart => Self::Quit,
47 Self::Menu => Self::Restart,
48 Self::Quit => Self::Menu,
49 }
50 }
51}
52
53/// Represents the possible states of the game.
54#[derive(Debug, Clone, PartialEq)]
55pub enum GameStatus {
56 Paused, // The game is currently paused
57 GameOver(GameOverMenu), // The game has ended, default selected option in attribute
58 ByeBye, // The game has exited
59 Playing, // The game is in progress
60 Restarting, // The game is restarting
61 Menu, // The game is going or displaying the Main Menu
62}
63
64/// Manages the game state, including life count, score, and current status.
65#[derive(Clone, Debug, PartialEq)]
66pub struct GameState {
67 pub life: u16, // Current player life count
68 pub score: u32, // Current player score
69 pub status: GameStatus, // Current game status
70 pub rank: Option<usize>, // Rank in high scores if game over
71 life_ini: u16, // Initial life count (used for reset)
72}
73
74impl GameState {
75 /// Creates a new `GameState` with the specified initial life count.
76 ///
77 /// # Arguments
78 /// * `life` - The initial number of lives the player starts with.
79 ///
80 /// # Returns
81 /// A new instance of `GameState` with default values.
82 #[must_use]
83 pub fn new(life: u16) -> Self {
84 Self {
85 life,
86 score: 0,
87 status: GameStatus::Playing,
88 rank: None,
89 life_ini: life,
90 }
91 }
92
93 /// Resets the game state to its initial values.
94 pub fn reset(&mut self) {
95 self.score = 0;
96 self.status = GameStatus::Playing;
97 self.rank = None;
98 self.life = self.life_ini;
99 }
100}