chessrs/piece/
mod.rs

1use crate::*;
2pub use inverse_moves::*;
3pub use piece_move::*;
4
5mod inverse_moves;
6mod piece_move;
7
8#[derive(Debug, Copy, Clone, PartialEq, Eq)]
9pub struct Piece {
10    pub byte: u8,
11    pub coords: Coords,
12}
13
14impl Piece {
15    pub fn new(byte: u8, coords: (usize, usize)) -> Self {
16        Piece {
17            byte,
18            coords: coords.into(),
19        }
20    }
21
22    pub fn from_coords(byte: u8, coords: Coords) -> Self {
23        Piece { byte, coords }
24    }
25
26    pub fn is_empty(&self) -> bool {
27        self.byte == 0
28    }
29
30    pub fn color(&self) -> u8 {
31        ((self.byte & 0b1000) != 0) as u8
32    }
33
34    pub fn piece_type(&self) -> u8 {
35        self.byte & 0b0111
36    }
37
38    pub fn is_home_row(&self) -> bool {
39        (self.coords.y == 1 && self.byte == 0b0001) || (self.coords.y == 6 && self.byte == 0b1001)
40    }
41
42    pub fn empty() -> Self {
43        Piece {
44            byte: 0,
45            coords: Coords::default(),
46        }
47    }
48}
49
50impl Display for Piece {
51    fn fmt(&self, f: &mut Formatter) -> fmtResult {
52        let piece = match self.byte {
53            0b0000 => ' ',
54            0b0001 => '♟',
55            0b0010 => '♜',
56            0b0011 => '♞',
57            0b0100 => '♝',
58            0b0101 => '♛',
59            0b0110 => '♚',
60            0b1001 => '♙',
61            0b1010 => '♖',
62            0b1011 => '♘',
63            0b1100 => '♗',
64            0b1101 => '♕',
65            0b1110 => '♔',
66            _ => unreachable!(),
67        };
68
69        write!(f, "{}", piece)
70    }
71}
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub enum PieceType {
75    Pawn = 0b1,
76    Rook = 0b10,
77    Knight = 0b11,
78    Bishop = 0b100,
79    Queen = 0b101,
80    King = 0b110,
81    None = 0,
82}
83
84impl PieceType {
85    pub fn iter() -> impl Iterator<Item = PieceType> {
86        // Define the order in which the pieces should be iterated
87        static PIECE_TYPES: [PieceType; 6] = [
88            PieceType::Pawn,
89            PieceType::Knight,
90            PieceType::Bishop,
91            PieceType::Rook,
92            PieceType::Queen,
93            PieceType::King,
94        ];
95
96        PIECE_TYPES.iter().cloned()
97    }
98}