read all inputs after polling and use the last one to always use newest input
This commit is contained in:
34
src/main.rs
34
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<char> {
|
||||
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(
|
||||
|
||||
Reference in New Issue
Block a user