board_game/heuristic/
chess.rs

1use std::cmp::{max, Ordering};
2
3use chess::{Piece, ALL_PIECES};
4
5use crate::ai::minimax::Heuristic;
6use crate::ai::solver::SolverHeuristic;
7use crate::board::Board;
8use crate::games::chess::ChessBoard;
9
10#[derive(Debug)]
11pub struct ChessPieceValueHeuristic;
12
13impl Heuristic<ChessBoard> for ChessPieceValueHeuristic {
14    type V = i32;
15
16    fn value(&self, board: &ChessBoard, length: u32) -> Self::V {
17        if board.is_done() {
18            return SolverHeuristic.value(board, length).to_i32();
19        }
20
21        let mut total = 0;
22
23        for piece in ALL_PIECES {
24            let value = match piece {
25                Piece::Pawn => 1,
26                Piece::Knight | Piece::Bishop => 3,
27                Piece::Rook => 5,
28                Piece::Queen => 9,
29                Piece::King => 0,
30            };
31
32            for square in *board.inner().pieces(piece) {
33                // we can unwrap here since we're iterating over the squares that contain the current piece,
34                //   so we know the square must also have a color
35                if board.inner().color_on(square).unwrap() == board.inner().side_to_move() {
36                    total += value;
37                } else {
38                    total -= value;
39                }
40            }
41        }
42
43        total
44    }
45
46    fn merge(old: Self::V, new: Self::V) -> (Self::V, Ordering) {
47        (max(old, new), new.cmp(&old))
48    }
49}