Last active
December 30, 2022 01:29
-
-
Save sean3z/ec62318e860b224007d50362a4b3089e to your computer and use it in GitHub Desktop.
Example nibble parsing for Chip-8 emulator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn emulate_cycle(&mut self) { | |
self.fetch_opcode(); | |
self.execute_opcode(); | |
// okay, PCs are much faster these days | |
// threw this cheeky delay in to slow things down | |
thread::sleep(time::Duration::from_micros(500)); | |
} | |
fn fetch_opcode(&mut self) { | |
self.opcode = (self.memory[self.program as usize] as u16) << 8 | (self.memory[(self.program + 1) as usize] as u16); | |
} | |
fn execute_opcode(&mut self) { | |
match self.opcode & 0xf000 { | |
0x0000 => self.op_0xxx(), | |
0x1000 => self.op_1xxx(), | |
0x2000 => self.op_2xxx(), | |
// .. remaining opcodes | |
_ => not_implemented(self.opcode as usize, self.program) | |
} | |
} | |
// Clear the display or Return from subroutine | |
fn op_0xxx(&mut self) { | |
match self.opcode & 0x000F { | |
0x0000 => { self.display.clear() } | |
0x000E => { | |
self.stack_pointer -= 1; | |
self.program = self.stack[self.stack_pointer] as usize; | |
} | |
_ => { not_implemented(self.opcode as usize, self.program) } | |
} | |
self.program += 2; | |
} | |
// Jumps to address | |
fn op_1xxx(&mut self) { self.program = self.op_nnn() as usize; } | |
// Calls subroutine | |
fn op_2xxx(&mut self) { | |
self.stack[self.stack_pointer] = self.program as u16; | |
self.stack_pointer += 1; | |
self.program = self.op_nnn() as usize; | |
} | |
fn op_x(&self) -> usize { ((self.opcode & 0x0F00) >> 8) as usize } | |
fn op_y(&self) -> usize { ((self.opcode & 0x00F0) >> 4) as usize } | |
fn op_n(&self) -> u8 { (self.opcode & 0x000F) as u8 } | |
fn op_nn(&self) -> u8 { (self.opcode & 0x00FF) as u8 } | |
fn op_nnn(&self) -> u16 { self.opcode & 0x0FFF } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment