1pub mod piece_color;
2pub mod piece_type;
3
4use piece_color::*;
5use piece_type::*;
6use std::fmt::{Debug, Formatter};
7
8#[derive(Copy, Clone, PartialEq, Eq)]
9pub struct Piece(pub u32);
10
11impl Piece {
12 pub fn get_color(&self) -> PieceColor {
13 if self.is_black() {
14 PieceColor::Black
15 } else {
16 PieceColor::White
17 }
18 }
19 pub fn get_type(&self) -> Option<PieceType> {
20 let result = match self.0 % 8 {
21 PAWN => PieceType::Pawn(self.0 > 32),
22 KNIGHT => PieceType::Knight,
23 KING => PieceType::King,
24 ROOK => PieceType::Rook,
25 QUEEN => PieceType::Queen,
26 BISHOP => PieceType::Bishop,
27 _ => return None,
28 };
29 Some(result)
30 }
31 pub(crate) fn is_white(&self) -> bool {
32 (8..16).contains(&(self.0 % 32))
33 }
34 pub(crate) fn is_black(&self) -> bool {
35 (16..24).contains(&(self.0 % 32))
36 }
37 pub fn is_piece(&self) -> bool {
38 self.get_type().is_some()
39 }
40
41 pub fn get_icon(&self) -> Option<&str> {
42 self.get_type()
43 .map(|piece_type| match (piece_type, self.get_color()) {
44 (PieceType::Rook, PieceColor::White) => "sprites/white_rook.png",
45 (PieceType::Pawn(_), PieceColor::White) => "sprites/white_pawn.png",
46 (PieceType::Bishop, PieceColor::White) => "sprites/white_bishop.png",
47 (PieceType::Queen, PieceColor::White) => "sprites/white_queen.png",
48 (PieceType::King, PieceColor::White) => "sprites/white_king.png",
49 (PieceType::Knight, PieceColor::White) => "sprites/white_knight.png",
50 (PieceType::Rook, PieceColor::Black) => "sprites/black_rook.png",
51 (PieceType::Pawn(_), PieceColor::Black) => "sprites/black_pawn.png",
52 (PieceType::Bishop, PieceColor::Black) => "sprites/black_bishop.png",
53 (PieceType::Queen, PieceColor::Black) => "sprites/black_queen.png",
54 (PieceType::King, PieceColor::Black) => "sprites/black_king.png",
55 (PieceType::Knight, PieceColor::Black) => "sprites/black_knight.png",
56 })
57 }
58}
59
60impl Debug for Piece {
61 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
62 let piece = if self.is_black() {
63 match (self.0 % 32) - BLACK {
64 PAWN => {
65 if self.0 > 32 {
66 "BP!"
67 } else {
68 "BP"
69 }
70 }
71 KING => "BK",
72 QUEEN => "BQ",
73 ROOK => "BR",
74 BISHOP => "BB",
75 KNIGHT => "BN",
76 _ => "□",
77 }
78 } else if self.is_white() {
79 match (self.0 % 32) - WHITE {
80 PAWN => {
81 if self.0 > 32 {
82 "WP!"
83 } else {
84 "WP"
85 }
86 }
87 KING => "WK",
88 QUEEN => "WQ",
89 ROOK => "WR",
90 BISHOP => "WB",
91 KNIGHT => "WN",
92 _ => "■",
93 }
94 } else if self.0 == 100 {
95 "▪"
96 } else {
97 ""
98 };
99
100 write!(f, "{:<3}", piece)
101 }
102}