add engine

This commit is contained in:
Dmitry Fedotov
2025-04-06 18:37:49 +03:00
parent aae44cd587
commit e84d6c6054
8 changed files with 246 additions and 33 deletions

44
engine/engine.rs Normal file
View File

@@ -0,0 +1,44 @@
use crate::game;
use crate::player;
pub struct Engine {
players: Vec<player::PlayerConsole>,
turn: usize,
board: game::Board,
}
impl Engine {
pub fn new() -> Engine {
let p1 = player::PlayerConsole::new("P1", game::CELL_X);
let p2 = player::PlayerConsole::new("P2", game::CELL_O);
let board = game::Board::new();
Engine {
players: vec![p1, p2],
turn: 0,
board: board,
}
}
pub fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
loop {
let m = self.players[self.turn].request_move(&self.board)?;
let ok = self.board.put(m);
if !ok {
continue;
}
let winner = self.board.has_winner();
if winner != game::CELL_EMPTY {
println!("the winner is {}", self.players[self.turn].name());
break;
}
self.turn = (self.turn + 1) % 2
}
Ok(())
}
}

3
engine/mod.rs Normal file
View File

@@ -0,0 +1,3 @@
mod engine;
pub use engine::Engine;