diff --git a/src/bin/d10p2.rs b/src/bin/d10p2.rs new file mode 100644 index 0000000..9bacf9c --- /dev/null +++ b/src/bin/d10p2.rs @@ -0,0 +1,14 @@ +use aoc22::{day10, util}; + +pub fn main() { + let instructions = day10::parse_instructions(&util::parse_input()); + let mut cpu = day10::CPU::new(instructions); + let mut crt = day10::CRT::new(); + + for _ in 0..240 { + crt.render(&cpu); + cpu.do_cycle().expect("No more instructions?"); + } + + crt.draw(); +} diff --git a/src/day10.rs b/src/day10.rs index dbe0b52..d7f4cfe 100644 --- a/src/day10.rs +++ b/src/day10.rs @@ -1,7 +1,7 @@ #[derive(Debug)] pub enum Instruction { Noop, - Addx(i32), + Addx(isize), } pub fn parse_instructions(input: &String) -> Vec { @@ -21,8 +21,9 @@ pub fn parse_instructions(input: &String) -> Vec { result } +#[derive(Debug)] pub struct CPU { - pub x: i32, + pub x: isize, pub cycle: isize, instructions: Vec, pc: usize, @@ -63,6 +64,41 @@ impl CPU { } pub fn signal_strength(&self) -> isize { - return (self.x as isize) * (self.cycle + 1); + return self.x * (self.cycle + 1); + } +} + +pub struct CRT { + pub pixels: [[char; 40]; 6], +} + +impl CRT { + pub fn new() -> CRT { + CRT { + pixels: [['.'; 40]; 6], + } + } + + pub fn render(&mut self, cpu: &CPU) { + let c = cpu.cycle; + assert!(c >= 0 && c < 240); + let x = c % 40; + let y = c / 40; + let sprite_pos = cpu.x - 1; + let px = &mut self.pixels[y as usize][x as usize]; + if x >= sprite_pos && x < sprite_pos + 3 { + *px = '#'; + } else { + *px = '.'; + } + } + + pub fn draw(&self) { + for y in 0..6 { + for x in 0..40 { + print!("{}", self.pixels[y][x]); + } + print!("\n"); + } } }