added feature/bug that skips frame wait if input was received which ensures handling all inputs

This commit is contained in:
2024-04-04 22:03:28 +02:00
parent 3475f19663
commit aca609bbb0

View File

@@ -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<char> {
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<char> {
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(