refactor, add lobby

This commit is contained in:
2026-01-04 17:45:57 +03:00
parent c3bcf44048
commit 5426da7d07
7 changed files with 153 additions and 137 deletions

View File

@@ -1,7 +1,5 @@
use std::io;
use crate::game::{Board, Cell};
use crate::player::{Player, PlayerConsole};
use crate::player::Player;
pub struct Engine {
players: Vec<Box<dyn Player>>,
@@ -11,15 +9,10 @@ pub struct Engine {
}
impl Engine {
pub fn new() -> Engine {
// TODO: accept players as args
let p1 = PlayerConsole::new("Gopher");
let p2 = PlayerConsole::new("Rustacean");
pub fn new(p1: Box<dyn Player>, p2: Box<dyn Player>) -> Engine {
let board = Board::new();
Engine {
players: vec![Box::new(p1), Box::new(p2)],
players: vec![p1, p2],
turn: 0,
board: board,
x: 0,
@@ -41,32 +34,16 @@ impl Engine {
// switch sides
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
let m = self.players[self.turn].request_move(&self.board)?;
let next = (self.turn + 1) % 2;
if !self.board.is_valid_move(&m) {
println!("invalid move");
continue;
}
@@ -75,46 +52,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...");
self.players[self.turn].message("You win!")?;
self.players[next].message("You loose!")?;
break;
}
if !self.board.valid_moves_available() {
cls();
home();
println!("It's a draw!");
println!("{}", self.board);
request_input("press Enter to continue");
self.players[self.turn].message("It's a draw!")?;
self.players[next].message("It's a draw!")?;
break;
}
self.turn = (self.turn + 1) % 2
self.turn = next
}
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
}