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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
|
use crate::{bitboard::{Bitboard, serialize_bitboard}, moves::Move, attacks::Attacks};
#[derive(Debug)]
pub struct Board {
pub pieces: [Bitboard; 12],
pub occupancy: Bitboard,
pub ply: u16,
attacks: Attacks,
}
#[derive(Debug, num_enum::FromPrimitive)]
#[repr(usize)]
pub enum PieceType {
#[default]
Pawn,
Knight,
Bishop,
Rook,
Queen,
King,
PawnBlack,
KnightBlack,
BishopBlack,
RookBlack,
QueenBlack,
KingBlack,
}
const PIECE_CHARS: [&str; 12] = [
"♟︎", "♞", "♝", "♜", "♛", "♚",
"♙", "♘", "♗", "♖", "♕", "♔",
];
#[allow(unused)]
impl Board {
#[allow(non_snake_case)]
pub fn from_FEN(fen: String) -> Self {
let mut pieces = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let mut rank = 7;
let mut file = 0i32;
for character in fen.chars() {
let index = rank * 8 + file;
let position = 1 << index.clamp(0, 63);
if character.is_numeric() {
let digit = match character.to_digit(10) {
None => todo!("What to do here?"),
Some(digit) => digit,
};
if digit > 0 && digit <= 8 {
file += digit as i32;
}
} else {
match character {
'P' => pieces[PieceType::Pawn as usize] |= position,
'N' => pieces[PieceType::Knight as usize] |= position,
'B' => pieces[PieceType::Bishop as usize] |= position,
'R' => pieces[PieceType::Rook as usize] |= position,
'Q' => pieces[PieceType::Queen as usize] |= position,
'K' => pieces[PieceType::King as usize] |= position,
'p' => pieces[PieceType::PawnBlack as usize] |= position,
'n' => pieces[PieceType::KnightBlack as usize] |= position,
'b' => pieces[PieceType::BishopBlack as usize] |= position,
'r' => pieces[PieceType::RookBlack as usize] |= position,
'q' => pieces[PieceType::QueenBlack as usize] |= position,
'k' => pieces[PieceType::KingBlack as usize] |= position,
'/' => {
rank -= 1;
file = -1; // So it becomes 0
},
' ' => { break }, // TODO: break for now, parse everything else later
'-' => {}, // TODO
'w' => {}, // TODO
_ => todo!("Unexpected character!"),
}
file += 1;
}
}
let mut board = Self { pieces, occupancy: 0, ply: 0, attacks: Attacks::new() };
board.update_occupancy();
board
}
fn update_occupancy(&mut self) {
self.occupancy = 0;
// TODO: reduce
for piece in self.pieces {
self.occupancy |= piece;
}
}
fn empty(&self) -> Bitboard {
!self.occupancy
}
fn pieces_by_color(&self, color: Color) -> [Bitboard; 6] {
let mut pieces = [0; 6];
for piece_type in 0..6 {
pieces[piece_type] = self.pieces[piece_type + 6 * color as usize];
}
pieces
}
fn color_occupancy(&self, color: Color) -> Bitboard {
let mut occupancy = 0;
for piece in self.pieces_by_color(color) {
occupancy |= piece;
}
occupancy
}
pub fn print(&self) {
println!();
for rank in (0..8).rev() {
print!("{}|", rank + 1);
for file in 0..8 {
let index = rank * 8 + file;
let position: Bitboard = 1 << index;
let mut found = false;
for (piece_type, piece_bitboard) in self.pieces.iter().enumerate() {
if (piece_bitboard & position) > 0 {
found = true;
print!("{} ", PIECE_CHARS[piece_type]);
}
}
if !found {
print!(". ");
}
}
println!();
}
println!(" a b c d e f g h");
}
pub fn generate_moves(&self, color: Color) -> Vec<Move> {
let mut moves = Vec::with_capacity(1024);
let opponent_occupancy = self.color_occupancy(Color::from(1 - color as u8));
let available_targets = opponent_occupancy | self.empty();
for (piece_type, piece) in self.pieces_by_color(color).iter().enumerate() {
match PieceType::from(piece_type) {
PieceType::Pawn => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.pawn[color as usize][source as usize] & opponent_occupancy) {
moves.push(Move { source, target });
};
for target in serialize_bitboard(self.attacks.pawn_pushes[color as usize][source as usize] & available_targets) {
moves.push(Move { source, target });
};
}
}
PieceType::King => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.king[source as usize] & available_targets) {
moves.push(Move { source, target });
};
}
}
PieceType::Knight => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.knight[source as usize] & available_targets) {
moves.push(Move { source, target });
};
}
}
PieceType::Bishop => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.bishop(self.occupancy, source) & available_targets) {
moves.push(Move { source, target });
};
}
}
PieceType::Rook => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.rook(self.occupancy, source) & available_targets) {
moves.push(Move { source, target });
};
}
}
PieceType::Queen => {
for source in serialize_bitboard(*piece) {
for target in serialize_bitboard(self.attacks.queen(self.occupancy, source) & available_targets) {
moves.push(Move { source, target });
};
}
}
_ => todo!("Incorrect piece type")
}
}
moves
}
/// *Blindlessly* apply a move without any validation
/// Move should be validated beforehand
pub fn apply_move(&mut self, mov: Move) {
// Target
match self.pieces
.iter()
.enumerate()
.find(|(piece_type, p)| *p & mov.target.to_bitboard() > 0)
{
Some((piece, bitboard)) => {
self.pieces[piece] ^= mov.target.to_bitboard();
},
None => {},
};
// Source
match self.pieces
.iter()
.enumerate()
.find(|(piece_type, p)| *p & mov.source.to_bitboard() > 0)
{
Some((piece, bitboard)) => {
self.pieces[piece] ^= mov.source.to_bitboard();
self.pieces[piece] |= mov.target.to_bitboard();
},
None => panic!("Move is malformed: source piece not found"),
};
}
}
#[derive(Clone, Copy, PartialEq, num_enum::FromPrimitive)]
#[repr(u8)]
pub enum Color {
#[default]
White,
Black,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{bitboard::{pop_count, bitscan, print}, square::Square};
const DEFAULT_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
#[test]
fn test_square_enum() {
assert_eq!(Square::A1 as u8, 0);
assert_eq!(Square::F1 as u8, 5);
assert_eq!(Square::H8 as u8, 63);
}
#[test]
fn test_from_fen() {
let fen = String::from(DEFAULT_FEN);
let board = Board::from_FEN(fen);
board.print();
print(board.empty(), "Empty squares");
assert_eq!(pop_count(board.pieces[PieceType::Pawn as usize]), 8);
assert_eq!(pop_count(board.pieces[PieceType::Knight as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::Bishop as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::Rook as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::Queen as usize]), 1);
assert_eq!(pop_count(board.pieces[PieceType::King as usize]), 1);
assert_eq!(pop_count(board.pieces[PieceType::PawnBlack as usize]), 8);
assert_eq!(pop_count(board.pieces[PieceType::KnightBlack as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::BishopBlack as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::RookBlack as usize]), 2);
assert_eq!(pop_count(board.pieces[PieceType::QueenBlack as usize]), 1);
assert_eq!(pop_count(board.pieces[PieceType::KingBlack as usize]), 1);
assert_eq!(bitscan(board.pieces[PieceType::King as usize]), Square::E1);
assert_eq!(bitscan(board.pieces[PieceType::QueenBlack as usize]), Square::D8);
assert_eq!(pop_count(board.occupancy), 32);
assert_eq!(pop_count(board.empty()), 32);
assert_eq!(pop_count(board.color_occupancy(Color::White)), 16);
assert_eq!(pop_count(board.color_occupancy(Color::Black)), 16);
}
#[test]
fn test_generate_moves_starting_position() {
let fen = String::from(DEFAULT_FEN);
let board = Board::from_FEN(fen);
let moves = board.generate_moves(Color::White);
let black_moves = board.generate_moves(Color::Black);
assert_eq!(moves.len(), 20);
assert_eq!(black_moves.len(), 20);
for mov in moves {
mov.print();
}
}
#[test]
fn test_apply_move() {
let fen = String::from("q1b2k2/5p1p/4p1pb/pPPp4/3N4/3nPB2/P2QKnR1/1R6 w - - 0 25");
let mut board = Board::from_FEN(fen);
board.print();
let black_move = Move { source: Square::F7, target: Square::F5 };
println!("\n{:?}", black_move);
board.apply_move(black_move);
board.print();
assert!(board.pieces[PieceType::PawnBlack as usize] & Square::F7.to_bitboard() == 0);
assert!(board.pieces[PieceType::PawnBlack as usize] & Square::F5.to_bitboard() > 0);
let white_move = Move { source: Square::D2, target: Square::A5 };
println!("\n{:?}", white_move);
board.apply_move(white_move);
board.print();
assert!(board.pieces[PieceType::PawnBlack as usize] & Square::A5.to_bitboard() == 0, "Target piece should be captured");
assert!(board.pieces[PieceType::Queen as usize] & Square::D2.to_bitboard() == 0);
assert!(board.pieces[PieceType::Queen as usize] & Square::A5.to_bitboard() > 0);
}
}
|