added event on key press with crossterm

This commit is contained in:
thatscringebro 2025-03-22 23:36:28 -04:00
parent 87f8a916dc
commit b4f6db070a
2 changed files with 87 additions and 8 deletions

View File

@ -6,5 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
crossterm = "0.28.1"
left-pad = "1.0.1"
rand = "0.9.0"

View File

@ -1,16 +1,94 @@
mod models;
use crate::models::taquin::*;
use crossterm::event::{read, Event, KeyCode, KeyEvent};
use crossterm::terminal::enable_raw_mode;
use left_pad::leftpad;
use std::io::{self, Write};
fn main() {
let _ = enable_raw_mode();
let mut taquin_game: TaquinGame = TaquinGame::new();
let mut playing: bool = true;
taquin_game.init_grid();
draw_game(taquin_game);
draw_game(&taquin_game);
// enable_raw_mode().expect("Could not enable raw mode");
while playing {
let mut message = "";
let mut user_cheated: bool = false;
match read().unwrap() {
Event::Key(KeyEvent {
code: KeyCode::Char('q'),
..
}) => {
playing = false;
message = "Bye bye!";
}
Event::Key(KeyEvent {
code: KeyCode::Char('r'),
..
}) => {
taquin_game.init_grid();
user_cheated = false;
message = "New game started";
}
Event::Key(KeyEvent {
code: KeyCode::Char('s'),
..
}) => {
taquin_game.resolve();
user_cheated = true;
message = "Too hard?";
}
Event::Key(KeyEvent {
code: KeyCode::Up, ..
}) => {
if !taquin_game.move_to(Directions::Up) {
message = "Cannot move any more up";
}
}
Event::Key(KeyEvent {
code: KeyCode::Down,
..
}) => {
if !taquin_game.move_to(Directions::Down) {
message = "Cannot move any more down";
}
}
Event::Key(KeyEvent {
code: KeyCode::Left,
..
}) => {
if !taquin_game.move_to(Directions::Left) {
message = "Cannot move any more left";
}
}
Event::Key(KeyEvent {
code: KeyCode::Right,
..
}) => {
if !taquin_game.move_to(Directions::Right) {
message = "Cannot move any more right";
}
}
_ => {
message = "error";
}
}
if taquin_game.is_grid_done() && !user_cheated {
message = "Yahoo! Good job!";
}
draw_game(&taquin_game);
print!("{}\r\n", message);
let _ = io::stdout().flush();
}
}
fn draw_game(game: TaquinGame) {
fn draw_game(game: &TaquinGame) {
print!("{}[2J", 27 as char);
let grid = game.grid();
for i in 0..ROWS * 2 + 1 {
@ -60,14 +138,14 @@ fn draw_game(game: TaquinGame) {
print!("High score: {}", game.high_score());
}
let _ = io::stdout().flush();
println!("");
print!("\r\n");
}
println!("Arrows to move");
println!("Q: Quit");
println!("R: Restart");
println!("S: Solve");
print!("Arrows to move\r\n");
print!("Q: Quit\r\n");
print!("R: Restart\r\n");
print!("S: Solve\r\n");
let _ = io::stdout().flush();
}
fn is_even(num: usize) -> bool {