c2g/drawer/
utils.rs

1use shakmaty::{self, File, Rank, Role, Square};
2
3/// A piece in a chess board
4#[derive(Debug)]
5pub struct PieceInBoard {
6    pub square: Square,
7    pub role: Role,
8    pub color: shakmaty::Color,
9}
10
11impl PieceInBoard {
12    /// Create a new King in the board
13    pub fn new_king(square: shakmaty::Square, color: shakmaty::Color) -> Self {
14        PieceInBoard {
15            square,
16            color,
17            role: Role::King,
18        }
19    }
20
21    /// Flip at the h1-a8 diagonal in place
22    pub fn flip_anti_diagonal(&mut self) {
23        self.square = self.square.flip_anti_diagonal();
24    }
25
26    /// Flip vertically and horizontally
27    pub fn flip_both(&mut self) {
28        self.square = self.square.flip_vertical().flip_horizontal();
29    }
30}
31
32/// Check if a square contains a coordinate. Coordindates are found in the A file
33/// and first rank
34pub fn has_coordinate(s: &Square, flip: bool) -> bool {
35    if (s.rank() == Rank::First || s.file() == File::A) && flip == false {
36        true
37    } else if (s.rank() == Rank::Eighth || s.file() == File::H) && flip == true {
38        true
39    } else {
40        false
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_piece_in_board_new_king() {
50        let piece = PieceInBoard::new_king(Square::new(0), shakmaty::Color::Black);
51        assert_eq!(piece.role, Role::King);
52    }
53
54    #[test]
55    fn test_has_coordinate() {
56        let square = Square::new(0); // A1
57        assert!(has_coordinate(&square, false));
58
59        let square = Square::new(9); // B2
60        assert!(!has_coordinate(&square, false));
61
62        let square = Square::new(56); // A8
63        assert!(has_coordinate(&square, false));
64    }
65
66    #[test]
67    fn test_has_coordinate_flip() {
68        let square = Square::new(0); // A1
69        assert!(!has_coordinate(&square, true));
70
71        let square = Square::new(7); // H1
72        assert!(has_coordinate(&square, true));
73
74        let square = Square::new(63); // H8
75        assert!(has_coordinate(&square, true));
76    }
77}