diff --git a/src/main.rs b/src/main.rs index 4c1fea8..0f0bede 100644 --- a/src/main.rs +++ b/src/main.rs @@ -43,7 +43,7 @@ fn main() { render(&snake, apple, length, (width, height)); enable_raw_mode().unwrap(); - change_dir(&mut direction); + change_dir(&mut direction, &now); disable_raw_mode().unwrap(); if let Some(crash) = move_snake(&mut snake, &direction, length, (width, height)) { match crash { @@ -56,8 +56,6 @@ fn main() { break; } eat(&snake, &mut apple, &mut length, &mut rng, (width, height)); - - while now.elapsed() < FRAME_TIME {} } exit(); @@ -82,8 +80,8 @@ fn exit() { std::process::exit(0); } -fn change_dir(direction: &mut Direction) { - if let Some(k) = key_input(FRAME_TIME) { +fn change_dir(direction: &mut Direction, now: &Instant) { + if let Some(k) = key_input(now) { match k { 'd' => { if *direction != Direction::Left { @@ -111,23 +109,17 @@ fn change_dir(direction: &mut Direction) { } } -fn key_input(timeout: Duration) -> Option { - let mut result = None; - if poll(timeout).ok()? { - if let Event::Key(k) = read().ok()? { - if let KeyCode::Char(c) = k.code { - result = Some(c); +fn key_input(now: &Instant) -> Option { + while now.elapsed() < FRAME_TIME { + if poll(Duration::from_secs(0)).ok()? { + if let Event::Key(k) = read().ok()? { + if let KeyCode::Char(c) = k.code { + return Some(c); + } } } } - while poll(Duration::from_secs(0)).ok()? { - if let Event::Key(k) = read().ok()? { - if let KeyCode::Char(c) = k.code { - result = Some(c); - } - } - } - result + None } fn move_snake(