1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::fmt;
use super::Color;
#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Debug)]
pub enum Piece {
Pawn,
Knight,
Bishop,
Rook,
Queen,
King,
}
pub const NUM_PIECES: usize = 6;
pub const ALL_PIECES: [Piece; NUM_PIECES] = [
Piece::Pawn,
Piece::Knight,
Piece::Bishop,
Piece::Rook,
Piece::Queen,
Piece::King,
];
impl Piece {
#[inline]
pub fn to_index(&self) -> usize {
*self as usize
}
#[inline]
pub fn to_string(&self, color: Color) -> String {
let piece = format!("{}", self);
match color {
Color::White => piece.to_uppercase(),
Color::Black => piece,
}
}
}
impl fmt::Display for Piece {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
match self {
Piece::Pawn => "p",
Piece::Knight => "n",
Piece::Bishop => "b",
Piece::Rook => "r",
Piece::Queen => "q",
Piece::King => "k",
}
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn to_index() {
assert_eq!(Piece::Pawn.to_index(), 0);
assert_eq!(Piece::Knight.to_index(), 1);
assert_eq!(Piece::Bishop.to_index(), 2);
assert_eq!(Piece::Rook.to_index(), 3);
assert_eq!(Piece::Queen.to_index(), 4);
assert_eq!(Piece::King.to_index(), 5);
}
#[test]
fn to_string_per_color() {
assert_eq!(Piece::Pawn.to_string(Color::White), "P");
assert_eq!(Piece::Knight.to_string(Color::White), "N");
assert_eq!(Piece::Bishop.to_string(Color::White), "B");
assert_eq!(Piece::Rook.to_string(Color::White), "R");
assert_eq!(Piece::Queen.to_string(Color::White), "Q");
assert_eq!(Piece::King.to_string(Color::White), "K");
assert_eq!(Piece::Pawn.to_string(Color::Black), "p");
assert_eq!(Piece::Knight.to_string(Color::Black), "n");
assert_eq!(Piece::Bishop.to_string(Color::Black), "b");
assert_eq!(Piece::Rook.to_string(Color::Black), "r");
assert_eq!(Piece::Queen.to_string(Color::Black), "q");
assert_eq!(Piece::King.to_string(Color::Black), "k");
}
#[test]
fn fmt() {
assert_eq!(format!("{}", Piece::Pawn), "p".to_string());
assert_eq!(format!("{}", Piece::Knight), "n".to_string());
assert_eq!(format!("{}", Piece::Bishop), "b".to_string());
assert_eq!(format!("{}", Piece::Rook), "r".to_string());
assert_eq!(format!("{}", Piece::Queen), "q".to_string());
assert_eq!(format!("{}", Piece::King), "k".to_string());
}
}