Skip to content

Commit dce349a

Browse files
committed
implement last instruction
1 parent 0410855 commit dce349a

File tree

2 files changed

+43
-7
lines changed

2 files changed

+43
-7
lines changed

src/cpu.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,20 @@ impl Cpu {
292292
}
293293
OpCode::GetKeyPress(x) => {
294294
// blocks until any key is pressed, then stores that key in rX
295-
// todo: implement
296-
self.program_counter -= 2;
295+
296+
// if we're not already tracking a key, start
297+
if !self.keyboard.is_tracking_next_key_release() {
298+
self.keyboard.track_next_key_release(true);
299+
}
300+
301+
// see if a key has been released yet
302+
if let Some(key) = self.keyboard.get_last_released_key() {
303+
self.keyboard.track_next_key_release(false);
304+
self.registers[x as usize] = key;
305+
} else {
306+
// no key released, so run this instruction again
307+
self.program_counter -= 2;
308+
}
297309
}
298310
OpCode::SetDelayTimer(x) => {
299311
// sets delay timer to value of rX

src/keyboard.rs

+29-5
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,52 @@
11
use winit::event::VirtualKeyCode;
22

33
pub struct KeyboardInput {
4-
key_states: [bool; 16]
4+
key_states: [bool; 16],
5+
last_released_key: Option<u8>,
6+
track_next_released_key: bool
57
}
68

79
impl KeyboardInput {
810
pub fn new() -> Self {
911
KeyboardInput {
10-
key_states: [false; 16]
12+
key_states: [false; 16],
13+
last_released_key: None,
14+
track_next_released_key: false
1115
}
1216
}
1317

14-
/// Sets a key state.
18+
/// Checks if we're tracking the next key release
19+
pub fn is_tracking_next_key_release(&self) -> bool {
20+
self.track_next_released_key
21+
}
22+
23+
/// Tracks for the next key
24+
pub fn track_next_key_release(&mut self, track: bool) {
25+
self.last_released_key = None;
26+
self.track_next_released_key = track;
27+
}
28+
29+
/// Gets the last released key if we're waiting for it
30+
pub fn get_last_released_key(&self) -> Option<u8> {
31+
self.last_released_key
32+
}
33+
34+
/// Sets a key state
1535
pub fn set_key_pressed(&mut self, key: u8, pressed: bool) {
1636
self.key_states[key as usize] = pressed;
37+
38+
if !pressed && self.track_next_released_key {
39+
self.last_released_key = Some(key);
40+
}
1741
}
1842

19-
/// Checks if a key is currently pressed.
43+
/// Checks if a key is currently pressed
2044
pub fn is_key_pressed(&self, key: u8) -> bool {
2145
self.key_states[key as usize]
2246
}
2347
}
2448

25-
/// Gets a virtual key code from a CHIP-8 key.
49+
/// Gets a virtual key code from a CHIP-8 key
2650
pub fn get_keycode_from_key(key: u8) -> Option<VirtualKeyCode> {
2751
// CHIP-8 keyboard is mapped to PC as follows:
2852

0 commit comments

Comments
 (0)