tidy up user prompts

This commit is contained in:
Dmitry Fedotov
2025-05-03 13:24:44 +03:00
parent b4b4166566
commit c3bcf44048
2 changed files with 46 additions and 6 deletions

View File

@@ -1,3 +1,5 @@
use std::io;
use crate::game::{Board, Cell};
use crate::player::{Player, PlayerConsole};
@@ -38,12 +40,26 @@ impl Engine {
self.run_single_game()?;
// switch sides
self.x = (self.x + 1) % 2
self.x = (self.x + 1) % 2;
match request_input("Press Enter to continue or \"q\" to quit.")
.as_str()
.trim()
{
"q" => {
return Ok(());
}
_ => {
continue;
}
}
}
}
fn run_single_game(&mut self) -> Result<(), Box<dyn std::error::Error>> {
loop {
cls();
home();
println!("{}", self.board);
// request move from player, fail if there is error
@@ -59,14 +75,20 @@ impl Engine {
// check if there is a winner
if let Some(_winner) = self.board.has_winner() {
cls();
home();
println!("{} wins!", self.players[self.turn].name());
println!("{}", self.board);
request_input("Press Enter to continue...");
break;
}
if !self.board.valid_moves_available() {
cls();
home();
println!("It's a draw!");
println!("{}", self.board);
request_input("press Enter to continue");
break;
}
@@ -76,3 +98,23 @@ impl Engine {
Ok(())
}
}
fn cls() {
print!("{}[2J", 27 as char);
}
fn home() {
print!("{}[H", 27 as char)
}
fn request_input(prompt: &str) -> String {
println!("{}", prompt);
let mut s = String::new();
match io::stdin().read_line(&mut s) {
Ok(_) => {}
Err(_) => {}
}
s
}