Files
rttt/player/human.rs
2025-04-07 03:25:32 +03:00

87 lines
2.0 KiB
Rust

use crate::game::{Board, Cell, Move};
use crate::player::Player;
use std::io;
pub struct PlayerConsole {
name: String,
piece: Cell,
}
impl PlayerConsole {
pub fn new(name: &str) -> impl Player {
PlayerConsole {
name: name.to_owned(),
piece: Cell::Empty,
}
}
pub fn name(&self) -> &str {
return self.name.as_str();
}
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>> {
let mut x: usize = 0;
let mut y: usize = 0;
loop {
println!("{}, it is your turn", self.name);
let mut s = String::new();
io::stdin().read_line(&mut s)?;
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...");
continue;
}
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;
}
}
}
break;
}
return Ok(Move {
x: x,
y: y,
piece: self.piece,
});
}
}
impl Player for PlayerConsole {
fn start_new_game(&mut self, p: Cell) -> Result<(), Box<dyn std::error::Error>> {
return self.start_new_game(p);
}
fn request_move(&self, b: &Board) -> Result<Move, Box<dyn std::error::Error>> {
self.request_move(b)
}
fn name(&self) -> &str {
self.name()
}
}