rsnaker/controls/
playing_input.rs1use crate::controls::direction::Direction;
2use crate::controls::main_menu::{ENTER_KEYS, NEXT_KEYS, PREVIOUS_KEYS};
3use crate::game_logic::state::{GameOverMenu, GameState, GameStatus};
4use crossterm::event;
5use crossterm::event::{KeyCode, KeyEventKind};
6use std::sync::{Arc, RwLock};
7use tracing::{error, info, warn};
8
9pub const QUIT_KEYS: [KeyCode; 2] = [KeyCode::Char('q'), KeyCode::Char('Q')];
10pub const START_KEYS: [KeyCode; 2] = [KeyCode::Char('r'), KeyCode::Char('R')];
11pub const MAIN_MENU_KEYS: [KeyCode; 2] = [KeyCode::Char('m'), KeyCode::Char('M')];
12pub const PAUSE_KEYS: [KeyCode; 4] = [
14 KeyCode::Char('p'),
15 KeyCode::Char('P'),
16 KeyCode::Char(' '),
17 KeyCode::Home,
18];
19pub const RESET_KEYS: [KeyCode; 2] = [KeyCode::Char('r'), KeyCode::Char('R')];
20
21pub fn playing_input_loop(direction: &Arc<RwLock<Direction>>, gs: &Arc<RwLock<GameState>>) {
28 loop {
29 if let Ok(event::Event::Key(key)) = event::read()
30 && key.kind == KeyEventKind::Press
31 {
32 let mut gs_guard = gs.write().unwrap();
33 if let GameStatus::GameOver(selection) = gs_guard.status {
35 if NEXT_KEYS.contains(&key.code) {
36 gs_guard.status = GameStatus::GameOver(selection.next());
37 } else if PREVIOUS_KEYS.contains(&key.code) {
38 gs_guard.status = GameStatus::GameOver(selection.previous());
39 } else if ENTER_KEYS.contains(&key.code) {
40 match selection {
41 GameOverMenu::Restart => {
42 info!("Restarting the game ! ");
43 gs_guard.status = GameStatus::Restarting;
44 }
45 GameOverMenu::Menu => {
46 info!("Coming back to menu ! ");
47 gs_guard.status = GameStatus::Menu;
48 break;
49 }
50 GameOverMenu::Quit => {
51 error!("You choose to quit the game 😶🌫️ ");
52 gs_guard.status = GameStatus::ByeBye;
53 break;
54 }
55 }
56 }
57 }
58 if PAUSE_KEYS.contains(&key.code) {
61 if gs_guard.status == GameStatus::Playing {
63 info!("Game paused ! ⏸️ ");
64 gs_guard.status = GameStatus::Paused;
65 } else if gs_guard.status == GameStatus::Paused {
66 info!("Game restart after pausing ! ⏯️ ");
67 gs_guard.status = GameStatus::Playing;
68 }
69 } else if QUIT_KEYS.contains(&key.code) {
71 error!("You choose to quit the game 😶🌫️ ");
72 gs_guard.status = GameStatus::ByeBye;
73 break;
74 } else if MAIN_MENU_KEYS.contains(&key.code) {
76 warn!("Going back to menu ! 🗺️");
77 gs_guard.status = GameStatus::Menu;
78 break;
79 } else if RESET_KEYS.contains(&key.code) {
81 warn!("Game hot restart ! 🤖");
82 gs_guard.status = GameStatus::Restarting;
83 } else {
85 let direction_input = match key.code {
86 KeyCode::Left => Some(Direction::Left),
87 KeyCode::Right => Some(Direction::Right),
88 KeyCode::Down => Some(Direction::Down),
89 KeyCode::Up => Some(Direction::Up),
90 _ => None,
91 };
92 if let Some(dir) = direction_input {
93 *direction.write().unwrap() = dir;
94 }
95 }
96 }
97 }
98}