Add display

This commit is contained in:
Michael Kohl 2021-04-02 23:03:20 +07:00
parent 3dc79b8975
commit 966a714fae
3 changed files with 62 additions and 14 deletions

View File

@ -1,6 +1,37 @@
const WIDTH: u32 = 64;
const HEIGHT: u32 = 32;
pub const WIDTH: usize = 64;
pub const HEIGHT: usize = 32;
pub const SCALE_FACTOR: u32 = 10;
pub const WINDOW_WIDTH: u32 = WIDTH * SCALE_FACTOR;
pub const WINDOW_HEIGHT: u32 = HEIGHT * SCALE_FACTOR;
pub const WINDOW_WIDTH: u32 = WIDTH as u32 * SCALE_FACTOR;
pub const WINDOW_HEIGHT: u32 = HEIGHT as u32 * SCALE_FACTOR;
pub struct Screen {
pixels: [[bool; WIDTH]; HEIGHT],
}
impl Screen {
pub fn new() -> Screen {
Screen {
pixels: [[false; WIDTH]; HEIGHT],
}
}
pub fn pixel_set(&mut self, x: usize, y: usize) -> () {
self.pixels[y][x] = true;
}
pub fn is_pixel_set(&self, x: usize, y: usize) -> bool {
self.pixels[y][x]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_can_set_a_pixel() {
let mut screen = Screen::new();
screen.pixel_set(5, 5);
assert!(screen.is_pixel_set(5, 5));
}
}

View File

@ -1,3 +1,4 @@
use crate::chip8::display::Screen;
use crate::chip8::keyboard::Keyboard;
use crate::chip8::memory::Memory;
use crate::chip8::registers::Registers;
@ -8,16 +9,17 @@ pub struct Chip8 {
pub registers: Registers,
pub stack: Stack,
pub keyboard: Keyboard,
pub screen: Screen,
}
impl Chip8 {
pub fn new() -> Chip8 {
let chip8 = Chip8 {
Chip8 {
memory: Memory::new(),
registers: Registers::new(),
stack: Stack::new(),
keyboard: Keyboard::new(),
};
chip8
screen: Screen::new(),
}
}
}

View File

@ -1,4 +1,6 @@
mod chip8;
use chip8::display;
use chip8::emulator::Chip8;
use sdl2::event::Event;
@ -10,6 +12,9 @@ const EMULATOR_WINDOW_TITLE: &str = "Rust CHIP-8";
fn main() -> Result<(), String> {
let mut chip8 = Chip8::new();
chip8.screen.pixel_set(0, 0);
chip8.screen.pixel_set(10, 2);
chip8.screen.pixel_set(42, 23);
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
@ -17,8 +22,8 @@ fn main() -> Result<(), String> {
let window = video_subsystem
.window(
EMULATOR_WINDOW_TITLE,
chip8::display::WINDOW_WIDTH,
chip8::display::WINDOW_HEIGHT,
display::WINDOW_WIDTH,
display::WINDOW_HEIGHT,
)
.position_centered()
.build()
@ -33,12 +38,22 @@ fn main() -> Result<(), String> {
canvas.clear();
let mut event_pump = sdl_context.event_pump()?;
let mut i = 0;
'mainloop: loop {
i = (i + 1) % 255;
canvas.set_draw_color(Color::RGB(i, 64, 255 - i));
canvas.fill_rect(Rect::new(10, 10, 620, 300))?;
canvas.set_draw_color(Color::RGB(255, 255, 255));
for y in 0..display::HEIGHT {
for x in 0..display::WIDTH {
if chip8.screen.is_pixel_set(x, y) {
canvas.fill_rect(Rect::new(
(x as u32 * display::SCALE_FACTOR) as i32,
(y as u32 * display::SCALE_FACTOR) as i32,
display::SCALE_FACTOR,
display::SCALE_FACTOR,
))?;
}
}
}
for event in event_pump.poll_iter() {
match event {