Move some functionality into the new Engine mod

This will help with separating the "thinking" logic from the move rules
and stuff.
This commit is contained in:
2021-12-21 21:07:19 +01:00
parent 802b069269
commit 95c0ccfbd2
4 changed files with 83 additions and 44 deletions

View File

@@ -1,5 +1,6 @@
use crate::board;
use crate::board::GridAxis;
use crate::engine;
use std::io::BufRead;
impl std::fmt::Display for board::Color {
@@ -140,20 +141,18 @@ impl board::Board {
}
pub struct Ui {
board: board::Board,
engine: engine::Engine,
}
impl Ui {
pub fn new() -> Self {
let mut board = board::Board::new();
board.reset();
Ui {
board,
engine: engine::Engine::new(),
}
}
fn get_state(&self, args: &[&str]) -> Result<String, String> {
if let [] = args {
let result = format!("{}", self.board);
let result = format!("{}", self.engine.get_state());
Ok(result)
} else {
Err("get_state takes no args".to_owned())
@@ -161,9 +160,12 @@ impl Ui {
}
fn set_state(&mut self, args: &[&str]) -> Result<String, String> {
if let [state_str] = args {
self.board = board::Board::parse(state_str)
.map_err(|_| format!("Error parsing state {}", state_str))?;
let result = format!("{}", self.board);
self.engine.set_state(
board::Board::parse(state_str).map_err(|_| {
format!("Error parsing state {}", state_str)
})?,
);
let result = format!("{}", self.engine.get_state());
Ok(result)
} else {
Err("set_state takes 1 arg".to_owned())
@@ -175,12 +177,12 @@ impl Ui {
board::Position::parse(position_str).map_err(|_| {
format!("Error parsing position {}", position_str)
})?;
match self.board.get_legal_moves(&position) {
None => {
match self.engine.get_legal_moves(&position) {
Err(_) => {
let error = format!("No moves possible from {}", position);
Err(error)
}
Some(positions) => Ok(positions
Ok(positions) => Ok(positions
.iter()
.map(|pos| format!("{}", pos))
.collect()),
@@ -195,12 +197,12 @@ impl Ui {
.map_err(|_| format!("Error parsing source {}", source_str))?;
let target = board::Position::parse(target_str)
.map_err(|_| format!("Error parsing target {}", target_str))?;
match self.board.make_move(&source, target) {
match self.engine.make_move(&source, target) {
Err(()) => Err(format!(
"Move not possible {}-{}",
source_str, target_str
)),
Ok(()) => Ok(self.board.to_string()),
Ok(()) => Ok(format!("{}", self.engine.get_state())),
}
} else {
Err("make_move takes 2 args".to_owned())