2025-04-07 02:04:18 +03:00
|
|
|
use crate::game::{Board, Cell, Move};
|
2025-04-06 18:37:49 +03:00
|
|
|
use crate::player::Player;
|
|
|
|
use std::io;
|
|
|
|
|
|
|
|
pub struct PlayerConsole {
|
|
|
|
name: String,
|
|
|
|
piece: Cell,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl PlayerConsole {
|
2025-04-07 02:04:18 +03:00
|
|
|
pub fn new(name: &str) -> impl Player {
|
2025-04-06 18:37:49 +03:00
|
|
|
PlayerConsole {
|
|
|
|
name: name.to_owned(),
|
2025-04-07 02:04:18 +03:00
|
|
|
piece: Cell::Empty,
|
2025-04-06 18:37:49 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn name(&self) -> &str {
|
|
|
|
return self.name.as_str();
|
|
|
|
}
|
|
|
|
|
2025-04-07 02:04:18 +03:00
|
|
|
pub fn start_new_game(&mut self, p: Cell) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
self.piece = p;
|
|
|
|
println!("{}, you are now playing {}", self.name, p);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn request_move(&self, _: &Board) -> Result<Move, Box<dyn std::error::Error>> {
|
2025-04-06 18:37:49 +03:00
|
|
|
let mut x: usize = 0;
|
|
|
|
let mut y: usize = 0;
|
|
|
|
|
|
|
|
loop {
|
2025-04-07 02:04:18 +03:00
|
|
|
println!("{}, it is your turn", self.name);
|
2025-04-06 18:37:49 +03:00
|
|
|
|
|
|
|
let mut s = String::new();
|
2025-04-07 02:04:18 +03:00
|
|
|
io::stdin().read_line(&mut s)?;
|
2025-04-06 18:37:49 +03:00
|
|
|
|
2025-04-07 02:04:18 +03:00
|
|
|
s = s.trim().into();
|
|
|
|
|
|
|
|
if s == "" {
|
|
|
|
return Err("player has surrendered".into());
|
|
|
|
} else if s.len() != 2 {
|
|
|
|
println!("invalid input. type board coordinates as a1, b2 etc...");
|
2025-04-06 18:37:49 +03:00
|
|
|
continue;
|
2025-04-07 02:04:18 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
for c in s.chars() {
|
|
|
|
match c {
|
|
|
|
'a' => y = 0,
|
|
|
|
'b' => y = 1,
|
|
|
|
'c' => y = 2,
|
|
|
|
'1' => x = 0,
|
|
|
|
'2' => x = 1,
|
|
|
|
'3' => x = 2,
|
|
|
|
_ => {
|
|
|
|
println!("invalid input: {}", c);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2025-04-06 18:37:49 +03:00
|
|
|
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Ok(Move {
|
|
|
|
x: x,
|
2025-04-07 02:04:18 +03:00
|
|
|
y: y,
|
|
|
|
piece: self.piece,
|
2025-04-06 18:37:49 +03:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Player for PlayerConsole {
|
2025-04-07 02:04:18 +03:00
|
|
|
fn start_new_game(&mut self, p: Cell) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
return self.start_new_game(p);
|
|
|
|
}
|
|
|
|
|
2025-04-06 18:37:49 +03:00
|
|
|
fn request_move(&self, b: &Board) -> Result<Move, Box<dyn std::error::Error>> {
|
|
|
|
self.request_move(b)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
self.name()
|
|
|
|
}
|
|
|
|
}
|