chip8/src/periph.rs

129 lines
2.7 KiB
Rust
Raw Normal View History

2020-06-25 13:13:09 -05:00
#[derive(Copy, Clone)]
pub struct Display {
pub buf: [u8; Self::SCREEN_SIZE],
}
impl Display {
const SCREEN_SIZE: usize = 64 * 32;
pub fn clear(&mut self) {
self.buf = [0x0; Self::SCREEN_SIZE]
}
pub fn draw_sprite(&mut self, coords: (u8, u8), data: &[u8]) -> bool {
let x = coords.0;
let y = coords.1;
let mut set_vf = false;
// Each Byte is a row, and there are n bytes in data
// When writing, x should not change but y should be incremented
// after each iteration in the loop.
for (i, byte) in data.iter().enumerate() {
// Access every bit of the byte
for j in 0..8 {
let bit = (byte >> j) & 0x01;
let display_index = j as usize + 8 * i as usize;
let old_value = self.buf[display_index];
self.buf[display_index] ^= bit;
if old_value == 0x01 && self.buf[display_index] == 0x00 {
set_vf = true;
}
}
}
set_vf
2020-06-25 13:13:09 -05:00
}
}
impl Default for Display {
fn default() -> Self {
Display {
buf: [0x0; Self::SCREEN_SIZE],
2020-06-25 13:13:09 -05:00
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct Timer {
remaining: u8,
enabled: bool,
}
impl Default for Timer {
fn default() -> Self {
Timer {
remaining: 0,
enabled: false,
}
}
}
impl Timer {
pub fn set(&mut self, secs: u8) {
self.remaining = secs;
self.enabled = true;
}
pub fn get(&self) -> u8 {
self.remaining
}
pub fn tick(&mut self) {
if self.enabled {
self.remaining -= 1;
if self.remaining == 0 {
println!("Beep!");
self.enabled = false;
}
}
}
}
#[derive(Debug, Copy, Clone)]
pub struct Keypad {
keys: [bool; 16],
}
impl Default for Keypad {
fn default() -> Self {
Self { keys: [false; 16] }
}
}
impl Keypad {
pub fn get_any_pressed(&self) -> Option<u8> {
for (i, key) in self.keys.iter().enumerate() {
2020-06-26 15:54:18 -05:00
if *key {
return Some(i as u8);
2020-06-25 13:13:09 -05:00
}
}
None
}
pub fn reset(&mut self) {
self.keys = [false; 16];
}
pub fn get_overview(&self) -> [bool; 16] {
self.keys
}
pub fn is_pressed(&self, key: u8) -> bool {
self.keys[key as usize]
}
pub fn set_all(&mut self, keys: [bool; 16]) {
self.keys = keys;
}
pub fn set_key(&mut self, index: usize) {
self.keys[index] = true;
}
2020-06-25 13:13:09 -05:00
pub fn unset_key(&mut self, index: usize) {
self.keys[index] = false;
2020-06-25 13:13:09 -05:00
}
}