From aca609bbb0bd459c6694f5097acb67499559e664 Mon Sep 17 00:00:00 2001 From: Vegard Matthey Date: Thu, 4 Apr 2024 22:03:28 +0200 Subject: [PATCH] added feature/bug that skips frame wait if input was received which ensures handling all inputs --- src/main.rs | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) 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(