Files
rttt/player/human.rs

76 lines
1.7 KiB
Rust
Raw Normal View History

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, p: Cell) -> impl Player {
2025-04-06 18:37:49 +03:00
PlayerConsole {
name: name.to_owned(),
piece: p,
}
}
pub fn name(&self) -> &str {
return self.name.as_str();
}
2025-04-07 02:04:18 +03:00
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 {
fn request_move(&self, b: &Board) -> Result<Move, Box<dyn std::error::Error>> {
self.request_move(b)
}
fn name(&self) -> &str {
self.name()
}
}