commit 5210a85ad5036c3aff9bbcc757763582d5bea59a from: Witcher01 date: Sun Aug 1 16:16:22 2021 UTC basic instruction stuff commit - 00098d83918691e91c4ecd0f18bd9e542c5ce9a1 commit + 5210a85ad5036c3aff9bbcc757763582d5bea59a blob - 11a1422a4ad5b4db09bfa55ee568cb7b7a36c4d9 blob + 51185056fdf6742a81bcb84add7490c87fd0d846 --- src/chip8.rs +++ src/chip8.rs @@ -1,3 +1,5 @@ +use std::path::Path; + use crate::drivers::VideoDriver; #[derive(Debug)] @@ -27,10 +29,14 @@ pub struct Chip8 { video_driver: VideoDriver, } +#[derive(Debug, Clone)] /// Instructions of the Chip8. pub enum Instruction { /// Clears the screen. CLS, + /// Default type for empty instruction field. + /// This is not an actual instruction. + EMPTY, } impl Chip8 { @@ -55,10 +61,26 @@ impl Chip8 { Instruction::CLS => { self.video_driver.clear(); }, + _ => { + return Err(String::from("unknown instruction")); + } }; Ok(()) } + + pub fn run(&mut self, file_path: &Path) -> Result<(), String> { + let bytes = std::fs::read(file_path).expect("reading file"); + let instructions = convert_to_instructions(bytes)?; + + for i in instructions { + println!("executing instruction {:?} at line {}", i, self.pc); + self.execute(i)?; + self.pc = self.pc + 1; + } + + Ok(()) + } } // this makes the code easier to read @@ -66,11 +88,23 @@ impl Chip8 { pub fn raw_to_instruction(instruction: u16) -> Result { match instruction { // CLS - 0x00E0 => { - return Ok(Instruction::CLS) - }, + 0x00E0 => return Ok(Instruction::CLS), _ => { return Err(format!("{:x}: not an instruction", instruction)); } } } + +fn convert_to_instructions(bytes: Vec) -> Result, String> { + // since 2 bytes make up 1 instruction this vec only needs to be half as big + let mut instructions: Vec = vec![Instruction::EMPTY; bytes.len() / 2]; + + let iter = bytes.chunks(2); + + for (i, e) in iter.enumerate() { + let t: u16 = (e[0] as u16) << 8 | (e[1] as u16); + instructions[i] = raw_to_instruction(t)?; + } + + Ok(instructions) +} blob - b2d6b056b7cfc8cc73a88825087bab39f390f2a8 blob + 241c01253dc57db35535095597b5d5f28ea2856e --- src/main.rs +++ src/main.rs @@ -4,14 +4,14 @@ mod drivers; use chip8::Chip8; use minifb::{Window, WindowOptions}; +use std::path::Path; fn main() -> Result<(), String> { - let mut w = Window::new("yac8e", 64, 32, WindowOptions::default()) - .expect("Unable to open a window"); + let _w = + Window::new("yac8e", 64, 32, WindowOptions::default()).expect("Unable to open a window"); - let chip8 = Chip8::new(); + let mut chip8 = Chip8::new(); + let file_path = Path::new("test.ch8"); - std::thread::sleep(std::time::Duration::from_secs(1)); - - Ok(()) + chip8.run(&file_path) }