improved command parsing

This commit is contained in:
Max Nuding 2022-12-10 07:37:03 +00:00
parent 8ae3092389
commit d42491f71a

View File

@ -7,11 +7,22 @@ enum Command {
} }
impl Command { impl Command {
fn from_str(s: &str) -> Self { fn from_str(s: &str) -> Self {
if s == "noop" { match s {
Self::Noop "noop" => Command::Noop,
} else { s => {
let sp = s.split_once(' ').unwrap(); let (c, i) = s.split_once(' ').unwrap();
Self::AddX(sp.1.parse().unwrap()) match (c, i.parse::<i32>()) {
("addx", Ok(i)) => Self::AddX(i),
_ => unreachable!(),
}
}
}
}
fn num_cycles(&self) -> usize {
match self {
Self::Noop => 1,
Self::AddX(_) => 2,
} }
} }
} }
@ -32,9 +43,11 @@ pub fn run() {
let mut pixels = [false; LINE_WIDTH]; let mut pixels = [false; LINE_WIDTH];
let mut rows = vec![]; let mut rows = vec![];
'outer: loop { 'outer: loop {
// Part 1
if cycle == 20 || (cycle > 20 && (cycle - 20) % LINE_WIDTH == 0) { if cycle == 20 || (cycle > 20 && (cycle - 20) % LINE_WIDTH == 0) {
sig_str.push(cycle as i32 * v); sig_str.push(cycle as i32 * v);
} }
if is_busy == 0 { if is_busy == 0 {
match lines.next() { match lines.next() {
Some(s) => { Some(s) => {
@ -43,17 +56,16 @@ pub fn run() {
Command::Noop => {} Command::Noop => {}
Command::AddX(x) => { Command::AddX(x) => {
v_new += x; v_new += x;
is_busy = 1;
} }
} };
is_busy = cmd.num_cycles();
} }
_ => { _ => {
break 'outer; break 'outer;
} }
}; };
} else {
is_busy -= 1;
} }
is_busy -= 1;
let pixel = (cycle - 1) % LINE_WIDTH; let pixel = (cycle - 1) % LINE_WIDTH;
let is_lit = pixel.abs_diff(v as usize) <= SPRITE_WIDTH_HALF; let is_lit = pixel.abs_diff(v as usize) <= SPRITE_WIDTH_HALF;