diff --git a/src/emulator.rs b/src/emulator.rs index 146fc9f..9c9c21a 100644 --- a/src/emulator.rs +++ b/src/emulator.rs @@ -164,7 +164,18 @@ where /// Handle the input fn handle_input(&mut self) { - self.last_key_pressed = self.input_module.get_key_pressed(); + if let Some(key_pressed) = self.input_module.get_key_pressed() { + if key_pressed == 0xFF { + // Exit requested + self.display.clear(); + println!("Thank you for playing! See you next time! :-)"); + std::process::exit(0); + } else { + self.last_key_pressed = Option::from((key_pressed & 0xF) as u8) + } + } else { + self.last_key_pressed = None; + } } /// Should make an audible beep. diff --git a/src/input.rs b/src/input.rs index 3a2913c..682e74c 100644 --- a/src/input.rs +++ b/src/input.rs @@ -6,14 +6,14 @@ use std::time::Duration; pub trait InputModule { /// Returns the key value of the corresponding pressed key. /// None if no key is pressed. - fn get_key_pressed(&mut self) -> Option; + fn get_key_pressed(&mut self) -> Option; } /// NoInput always returns none when queried for input. pub struct NoInput; impl InputModule for NoInput { - fn get_key_pressed(&mut self) -> Option { + fn get_key_pressed(&mut self) -> Option { None } } @@ -37,7 +37,7 @@ impl Default for CrossTermInput { } impl InputModule for CrossTermInput { - fn get_key_pressed(&mut self) -> Option { + fn get_key_pressed(&mut self) -> Option { if !self.initialized { panic!("CrossTermInput needs to be constructed using ::new") } @@ -48,60 +48,31 @@ impl InputModule for CrossTermInput { if let Ok(event) = read_result { match event { Event::Key(key_event) => match key_event.code { + KeyCode::Esc => { + return Some(0xFF); + }, KeyCode::Char(character) => { let lowercase_character = character.to_lowercase(); for char in lowercase_character { - match char { - '1' => { - return Some(1); - } - '2' => { - return Some(2); - } - '3' => { - return Some(3); - } - '4' => { - return Some(0xC); - } - 'q' => { - return Some(4); - } - 'w' => { - return Some(5); - } - 'e' => { - return Some(6); - } - 'r' => { - return Some(0xD); - } - 'a' => { - return Some(7); - } - 's' => { - return Some(8); - } - 'd' => { - return Some(9); - } - 'f' => { - return Some(0xE); - } - 'z' => { - return Some(0xA); - } - 'x' => { - return Some(0); - } - 'c' => { - return Some(0xB); - } - 'v' => { - return Some(0xF); - } - _ => {} - } + return match char { + '1' => Some(1), + '2' => Some(2), + '3' => Some(3), + '4' => Some(0xC), + 'q' => Some(4), + 'w' => Some(5), + 'e' => Some(6), + 'r' => Some(0xD), + 'a' => Some(7), + 's' => Some(8), + 'd' => Some(9), + 'f' => Some(0xE), + 'z' => Some(0xA), + 'x' => Some(0), + 'c' => Some(0xB), + 'v' => Some(0xF), + _ => None, + }; } } _ => {}