Day 10, puzzle 2
This commit is contained in:
parent
05f3d9411a
commit
b7005f244d
|
@ -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();
|
||||
}
|
42
src/day10.rs
42
src/day10.rs
|
@ -1,7 +1,7 @@
|
|||
#[derive(Debug)]
|
||||
pub enum Instruction {
|
||||
Noop,
|
||||
Addx(i32),
|
||||
Addx(isize),
|
||||
}
|
||||
|
||||
pub fn parse_instructions(input: &String) -> Vec<Instruction> {
|
||||
|
@ -21,8 +21,9 @@ pub fn parse_instructions(input: &String) -> Vec<Instruction> {
|
|||
result
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CPU {
|
||||
pub x: i32,
|
||||
pub x: isize,
|
||||
pub cycle: isize,
|
||||
instructions: Vec<Instruction>,
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue