Implement dummy chess solver
It chooses a random available move ¯\_(ツ)_/¯
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
use crate::board;
|
||||
use rand::seq::IteratorRandom;
|
||||
|
||||
pub struct Engine {
|
||||
board: board::Board,
|
||||
@@ -21,23 +22,47 @@ impl Engine {
|
||||
pub fn get_legal_moves(
|
||||
&self,
|
||||
position: &board::Position,
|
||||
) -> Result<Vec<board::Position>, ()> {
|
||||
Ok(self
|
||||
.board
|
||||
.find_moves(position)?
|
||||
.chain(self.board.find_captures(position)?)
|
||||
.collect())
|
||||
) -> Result<impl Iterator<Item = board::Position> + '_, ()> {
|
||||
if self.board.occupied(position) {
|
||||
Ok(self
|
||||
.board
|
||||
.find_moves(position)
|
||||
.unwrap()
|
||||
.chain(self.board.find_captures(position).unwrap()))
|
||||
} else {
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
pub fn make_move(
|
||||
&mut self,
|
||||
source: &board::Position,
|
||||
target: board::Position,
|
||||
) -> Result<(), ()> {
|
||||
if !self.get_legal_moves(source)?.contains(&target) {
|
||||
if !self.get_legal_moves(source)?.any(|pos| pos == target) {
|
||||
Err(())
|
||||
} else {
|
||||
// We checked that there is a piece at source in get_legal_moves
|
||||
self.board.relocate(source, target)
|
||||
}
|
||||
}
|
||||
pub fn choose_move(
|
||||
&self,
|
||||
color: &board::Color,
|
||||
) -> Option<(board::Position, board::Position)> {
|
||||
self.board
|
||||
.iter()
|
||||
.filter_map(|(source, piece)| {
|
||||
if &piece.color == color {
|
||||
if let Ok(targets) = self.get_legal_moves(source) {
|
||||
Some(targets.map(|target| (source.clone(), target)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
.choose(&mut rand::thread_rng())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user