Files
rttt/engine/engine.rs

121 lines
2.8 KiB
Rust
Raw Normal View History

2025-05-03 13:24:44 +03:00
use std::io;
2025-04-07 02:04:18 +03:00
use crate::game::{Board, Cell};
use crate::player::{Player, PlayerConsole};
2025-04-06 18:37:49 +03:00
pub struct Engine {
2025-04-07 02:04:18 +03:00
players: Vec<Box<dyn Player>>,
2025-04-06 18:37:49 +03:00
turn: usize,
2025-04-07 02:04:18 +03:00
board: Board,
x: usize,
2025-04-06 18:37:49 +03:00
}
impl Engine {
pub fn new() -> Engine {
2025-04-07 02:04:18 +03:00
// TODO: accept players as args
let p1 = PlayerConsole::new("Gopher");
let p2 = PlayerConsole::new("Rustacean");
2025-04-06 18:37:49 +03:00
2025-04-07 02:04:18 +03:00
let board = Board::new();
2025-04-06 18:37:49 +03:00
Engine {
2025-04-07 02:04:18 +03:00
players: vec![Box::new(p1), Box::new(p2)],
2025-04-06 18:37:49 +03:00
turn: 0,
board: board,
2025-04-07 02:04:18 +03:00
x: 0,
2025-04-06 18:37:49 +03:00
}
}
pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
loop {
2025-04-07 02:04:18 +03:00
// setup new game for players
self.players[self.x].start_new_game(Cell::X)?;
self.players[(self.x + 1) % 2].start_new_game(Cell::O)?;
// reset board
self.board.reset();
self.turn = self.x;
// run game
self.run_single_game()?;
// switch sides
2025-05-03 13:24:44 +03:00
self.x = (self.x + 1) % 2;
match request_input("Press Enter to continue or \"q\" to quit.")
.as_str()
.trim()
{
"q" => {
return Ok(());
}
_ => {
continue;
}
}
2025-04-07 02:04:18 +03:00
}
}
fn run_single_game(&mut self) -> Result<(), Box<dyn std::error::Error>> {
loop {
2025-05-03 13:24:44 +03:00
cls();
home();
2025-04-07 02:04:18 +03:00
println!("{}", self.board);
// request move from player, fail if there is error
2025-04-06 18:37:49 +03:00
let m = self.players[self.turn].request_move(&self.board)?;
2025-04-07 02:04:18 +03:00
if !self.board.is_valid_move(&m) {
println!("invalid move");
2025-04-06 18:37:49 +03:00
continue;
}
2025-04-07 02:04:18 +03:00
// apply move
self.board.apply(m)?;
// check if there is a winner
if let Some(_winner) = self.board.has_winner() {
2025-05-03 13:24:44 +03:00
cls();
home();
2025-04-07 02:04:18 +03:00
println!("{} wins!", self.players[self.turn].name());
println!("{}", self.board);
2025-05-03 13:24:44 +03:00
request_input("Press Enter to continue...");
2025-04-07 02:04:18 +03:00
break;
}
if !self.board.valid_moves_available() {
2025-05-03 13:24:44 +03:00
cls();
home();
2025-04-07 02:04:18 +03:00
println!("It's a draw!");
println!("{}", self.board);
2025-05-03 13:24:44 +03:00
request_input("press Enter to continue");
2025-04-06 18:37:49 +03:00
break;
}
self.turn = (self.turn + 1) % 2
}
Ok(())
}
}
2025-05-03 13:24:44 +03:00
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
}