tidy up user prompts
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
@@ -43,12 +43,11 @@ impl Board {
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, m: Move) -> Result<(), &str> {
|
||||
let i = m.x * 1 + m.y * 3;
|
||||
|
||||
if !self.is_valid_move(&m) {
|
||||
return Err("invalid move");
|
||||
}
|
||||
|
||||
let i = m.x * 1 + m.y * 3;
|
||||
self.cells[i] = m.piece;
|
||||
|
||||
match self.next {
|
||||
@@ -68,14 +67,13 @@ impl Board {
|
||||
|
||||
pub fn valid_moves_available(&self) -> bool {
|
||||
// check for draw condition
|
||||
let mut empty: usize = 0;
|
||||
for i in 0..self.cells.len() {
|
||||
if self.cells[i] == Cell::Empty {
|
||||
empty += 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
empty > 0
|
||||
return false;
|
||||
}
|
||||
|
||||
pub fn has_winner(&self) -> Option<Cell> {
|
||||
|
Reference in New Issue
Block a user