From 3475f19663fc3c9809ff9cb8d7371c9aff58fd9b Mon Sep 17 00:00:00 2001 From: Vegard Matthey Date: Thu, 4 Apr 2024 20:57:37 +0200 Subject: [PATCH] read all inputs after polling and use the last one to always use newest input --- src/main.rs | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/src/main.rs b/src/main.rs index 418a719..4c1fea8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,12 +1,9 @@ use crossterm::{ - cursor::{Hide, Show}, event::{poll, read, Event, KeyCode}, terminal::{disable_raw_mode, enable_raw_mode, size}, - ExecutableCommand, }; use rand::prelude::*; use std::collections::VecDeque; -use std::io::stdout; use std::time::{Duration, Instant}; const FRAME_TIME: Duration = Duration::from_millis(100); @@ -33,17 +30,13 @@ fn main() { let mut snake: VecDeque<(u16, u16)> = vec![(0, 0), (1, 0), (2, 0)].into(); let mut direction = Direction::Right; let mut length = snake.len(); - - stdout().execute(Hide).unwrap(); - let (width, height) = size().unwrap_or((20, 20)); - println!("width {width}, height: {height}"); let (width, height) = ((width - 2) / 2, height - 5); + let mut rng = thread_rng(); - let mut apple = ( - rng.gen_range(0..width), - rng.gen_range(0..height), - ); + let mut apple = (rng.gen_range(0..width), rng.gen_range(0..height)); + + print!("\x1b[?25l"); // Hides cursor loop { let now = Instant::now(); @@ -78,17 +71,14 @@ fn eat( (width, height): (u16, u16), ) { if snake.contains(apple) { - *apple = ( - rng.gen_range(0..width), - rng.gen_range(0..height), - ); + *apple = (rng.gen_range(0..width), rng.gen_range(0..height)); *length += 1; } } fn exit() { disable_raw_mode().unwrap(); - stdout().execute(Show).unwrap(); + print!("\x1b[?25h"); // Shows cursor std::process::exit(0); } @@ -122,14 +112,22 @@ 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 { - return Some(c); + result = Some(c); } } } - None + 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 } fn move_snake(