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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
|
use crate::{bitboard::{Bitboard, BitboardFns}, moves::{Move, MoveKind}, attacks::Attacks, square::Square, board::io::IO};
use self::{ttable::{TranspositionTable, TTABLE_SIZE}, zobrist::ZobristSeed};
pub mod io;
mod zobrist;
mod engine;
mod ttable;
#[derive(Debug, Clone, Copy)]
pub enum CastlingSide {
King,
Queen,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Board {
pub ply: u16,
pub piece_sets: [Bitboard; 12],
/// Castling rights indexed by Color and CastlingSide
pub castling_rights: [[bool; 2]; 2],
/// En passsant target square
pub ep_target: Option<Square>,
// Computed values
pub occupancy: Bitboard,
/// Zobrist hash of the current position
pub hash: u64,
// TODO: remove
transposition_table: TranspositionTable,
zobrist_seed: ZobristSeed,
attacks: Attacks,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, num_enum::FromPrimitive)]
#[repr(usize)]
pub enum PieceType {
#[default]
Pawn,
Knight,
Bishop,
Rook,
Queen,
King,
PawnBlack,
KnightBlack,
BishopBlack,
RookBlack,
QueenBlack,
KingBlack,
}
impl PieceType {
pub fn without_color(&self) -> Self {
let index = *self as usize;
Self::from(index % 6)
}
// Return the price of the peice
pub fn static_eval(&self) -> f32 {
match self.without_color() {
PieceType::Pawn => 1.0,
PieceType::Bishop => 3.3,
PieceType::Knight => 3.2,
PieceType::Rook => 5.0,
PieceType::Queen => 9.0,
PieceType::King => 0.,
_ => panic!("Piece should be without color"),
}
}
}
impl Board {
pub fn new() -> Self {
let default_fen = String::from("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
Self::from_FEN(default_fen)
}
/// Color to move at this ply
pub fn color(&self) -> Color {
Color::from(self.ply as u8 % 2)
}
fn update_occupancy(&mut self) {
self.occupancy = self.piece_sets.iter().fold(0, |acc, bitboard| acc | bitboard)
}
fn empty(&self) -> Bitboard {
!self.occupancy
}
fn pieces_by_color(&self, color: Color) -> &[Bitboard] {
match color {
Color::White => &self.piece_sets[0..6],
Color::Black => &self.piece_sets[6..12],
}
}
fn color_occupancy(&self, color: Color) -> Bitboard {
self.pieces_by_color(color).iter().fold(0, |acc, bitboard| acc | bitboard)
}
fn ep_bitboard(&self) -> Bitboard {
let color = self.color();
match self.ep_target {
Some(square) => {
let rank = square.rank();
if (rank == 2 && color == Color::Black) || (rank == 5 && color == Color::White) {
square.to_bitboard()
} else {
0
}
}
None => 0,
}
}
pub fn generate_pseudolegal_moves(&self) -> Vec<Move> {
let mut result = Vec::new();
result.append(&mut self.generate_moves_core(true));
result.append(&mut self.generate_moves_core(false));
result
}
pub fn generate_moves_core(&self, tactical_only: bool) -> Vec<Move> {
let color = self.color();
let player_pieces = self.pieces_by_color(color);
let mut moves = Vec::with_capacity(256);
let empty = self.empty();
let targets = if tactical_only {
self.color_occupancy(color.flip()) ^ match color {
// Exclude opponent king because we can't capture it
Color::White => self.piece_sets[PieceType::KingBlack as usize],
Color::Black => self.piece_sets[PieceType::King as usize],
}
} else {
empty
};
let kind = if tactical_only {
MoveKind::Capture
} else {
MoveKind::Quiet
};
for (piece_id, piece) in player_pieces.iter().enumerate() {
for source in piece.serialize() {
let piece_type = PieceType::from(piece_id);
let move_targets = match piece_type {
PieceType::Bishop => self.attacks.bishop(self.occupancy, source),
PieceType::Rook => self.attacks.rook(self.occupancy, source),
PieceType::Queen => self.attacks.queen(self.occupancy, source),
PieceType::Knight => self.attacks.knight[source as usize],
PieceType::King => self.attacks.king[source as usize],
PieceType::Pawn => if tactical_only {
self.attacks.pawn[color as usize][source as usize]
} else {
self.attacks.pawn_pushes[color as usize][source as usize]
},
_ => panic!("Incorrect piece type"),
};
// Generalized attack/move pattern for all pieces
for target in (move_targets & targets).serialize() {
moves.push(Move { source, target, kind });
// Promotions
if piece_type == PieceType::Pawn {
if target.rank() == 7 {
for promo_type in [PieceType::Bishop, PieceType::Knight, PieceType::Rook, PieceType::Queen] {
moves.push(Move { source, target, kind: MoveKind::Promotion(promo_type)})
}
} else if target.rank() == 0 {
for promo_type in [PieceType::BishopBlack, PieceType::KnightBlack, PieceType::RookBlack, PieceType::QueenBlack] {
moves.push(Move { source, target, kind: MoveKind::Promotion(promo_type)})
}
}
}
}
// En Passant
if piece_type == PieceType::Pawn && tactical_only {
for target in (move_targets & self.ep_bitboard()).serialize() {
moves.push(Move { source, target, kind: MoveKind::EnPassant });
}
}
}
}
if !tactical_only {
// Double Pushes
// Make sure no blocking piece is standing in front of the pawns
// that are potential double-push sources
let able_to_double_push_mask = match color {
Color::White => empty >> 8,
Color::Black => empty << 8,
};
for source in (player_pieces[PieceType::Pawn as usize] & able_to_double_push_mask).serialize() {
for target in (self.attacks.pawn_double_pushes[color as usize][source as usize] & empty).serialize() {
moves.push(Move { source, target, kind: MoveKind::DoublePush });
};
}
// Castling
let king_home_position = match color {
Color::White => Square::E1,
Color::Black => Square::E8,
};
if player_pieces[PieceType::King as usize].bitscan() == king_home_position {
for rook_square in player_pieces[PieceType::Rook as usize]
.serialize()
.iter()
.filter(|rook_square| rook_square.rank() == king_home_position.rank())
{
match rook_square.file() {
0 => {
let all_empty = [
king_home_position.west_one(),
king_home_position.west_one().west_one(),
king_home_position.west_one().west_one().west_one(),
].iter().all(|square| empty & square.to_bitboard() > 0);
let any_checks = [
king_home_position,
king_home_position.west_one(),
king_home_position.west_one().west_one(),
].iter().any(|square| self.is_square_attacked(*square, color.flip()));
if all_empty && !any_checks && self.castling_rights[color as usize][CastlingSide::Queen as usize] {
moves.push(Move {
source: king_home_position,
target: king_home_position.west_one().west_one(),
kind: MoveKind::Castle,
})
}
},
7 => {
let all_empty = [
king_home_position.east_one(),
king_home_position.east_one().east_one(),
].iter().all(|square| empty & square.to_bitboard() > 0);
let any_checks = [
king_home_position,
king_home_position.east_one(),
king_home_position.east_one().east_one(),
].iter().any(|square| self.is_square_attacked(*square, color.flip()));
if all_empty && !any_checks && self.castling_rights[color as usize][CastlingSide::King as usize] {
moves.push(Move {
source: king_home_position,
target: king_home_position.east_one().east_one(),
kind: MoveKind::Castle,
})
}
},
_ => {},
}
}
}
}
return moves
}
/// Count pseudo-legal moves without actually generating them
/// Also exclude all moves that put a piece under attack of a pawn - so called safe mobility
pub fn mobility(&self, color: Color) -> f32 {
let mut mobility = 0.;
let opponent_occupancy = self.color_occupancy(color.flip());
let player_pieces = self.pieces_by_color(color);
let opponent_pawns = match color {
Color::Black => self.piece_sets[PieceType::Pawn as usize],
Color::White => self.piece_sets[PieceType::PawnBlack as usize],
};
let pawn_attacked_squares = opponent_pawns.serialize().iter().fold(0u64, |acc, square| {
acc | self.attacks.pawn[color.flip() as usize][*square as usize]
});
// Exclude squares controlled by enemy pawns from mobility
let empty = self.empty() & !pawn_attacked_squares;
for (piece_type, piece) in player_pieces.iter().enumerate() {
match PieceType::from(piece_type) {
PieceType::Pawn => {
for source in piece.serialize() {
let ep_bitboard = match self.ep_target {
Some(square) => {
let rank = square.rank();
if (rank == 2 && color == Color::Black) || (rank == 5 && color == Color::White) {
square.to_bitboard()
} else {
0
}
}
None => 0,
};
mobility += (self.attacks.pawn[color as usize][source as usize] & (opponent_occupancy | ep_bitboard)).pop_count() as f32;
mobility += (self.attacks.pawn_pushes[color as usize][source as usize] & empty).pop_count() as f32;
}
let able_to_double_push_mask = match color {
Color::White => empty >> 8,
Color::Black => empty << 8,
};
for source in (*piece & able_to_double_push_mask).serialize() {
mobility += (self.attacks.pawn_double_pushes[color as usize][source as usize] & empty).pop_count() as f32;
}
}
PieceType::King => {
for source in piece.serialize() {
mobility += (self.attacks.king[source as usize] & (empty | opponent_occupancy)).pop_count() as f32;
// Castling
let king_home_position = match color {
Color::White => Square::E1,
Color::Black => Square::E8,
};
if *piece == king_home_position.to_bitboard() {
for rook_square in player_pieces[PieceType::Rook as usize]
.serialize()
.iter()
.filter(|rook_square| rook_square.rank() == king_home_position.rank())
{
match rook_square.file() {
0 => {
let castle_line = [
king_home_position.west_one(),
king_home_position.west_one().west_one(),
];
let all_empty = castle_line.iter().all(|square| empty & square.to_bitboard() > 0);
let any_checks = castle_line.iter().any(|square| self.is_square_attacked(*square, color.flip()));
if all_empty && !any_checks && self.castling_rights[color as usize][CastlingSide::Queen as usize] {
mobility += 1.;
}
},
7 => {
let castle_line = [
king_home_position.east_one(),
king_home_position.east_one().east_one(),
];
let all_empty = castle_line.iter().all(|square| empty & square.to_bitboard() > 0);
let any_checks = castle_line.iter().any(|square| self.is_square_attacked(*square, color.flip()));
if all_empty && !any_checks && self.castling_rights[color as usize][CastlingSide::King as usize] {
mobility += 1.;
}
},
_ => {},
}
}
}
}
}
PieceType::Knight => {
for source in piece.serialize() {
mobility += (self.attacks.knight[source as usize] & (empty | opponent_occupancy)).pop_count() as f32;
}
}
PieceType::Bishop => {
for source in piece.serialize() {
mobility += (self.attacks.bishop(self.occupancy, source) & (empty | opponent_occupancy)).pop_count() as f32;
}
}
PieceType::Rook => {
for source in piece.serialize() {
mobility += (self.attacks.rook(self.occupancy, source) & (empty | opponent_occupancy)).pop_count() as f32;
}
}
PieceType::Queen => {
// Do not account queen in mobility
}
incorrect_type => panic!("Incorrect piece type: {:?}", incorrect_type),
}
}
mobility
}
fn piece_by_square(&self, square: Square) -> Option<PieceType> {
let square_bb = square.to_bitboard();
self.piece_sets
.iter()
.enumerate()
.find(|(_, bitboard)| *bitboard & square_bb > 0)
.and_then(|(pt, _)| Some(PieceType::from(pt)))
}
/// *Blindlessly* apply a move without any validation
/// Legality test should still be performed
pub fn make_move(&mut self, mov: Move) -> Option<PieceType> {
let move_source_bb = mov.source.to_bitboard();
let move_target_bb = mov.target.to_bitboard();
// Remove existing piece (if any) from target square
let mut captured_piece = match self.piece_by_square(mov.target) {
Some(target_piece) => {
self.piece_sets[target_piece as usize] ^= move_target_bb;
self.hash ^= self.zobrist_seed[(target_piece as usize) * 64 + mov.target as usize];
Some(target_piece)
},
None => None,
};
// En Passant captures diffirently
if mov.kind == MoveKind::EnPassant {
debug_assert!(captured_piece.is_none(), "No capture should be found at this point");
let captured_square = Square::from_coords(mov.source.rank(), mov.target.file());
captured_piece = match self.piece_by_square(captured_square) {
Some(pawn_type) => {
let captured_bb = captured_square.to_bitboard();
self.piece_sets[pawn_type as usize] ^= captured_bb;
self.occupancy ^= captured_bb;
self.hash ^= self.zobrist_seed[pawn_type as usize* 64 + captured_square as usize];
Some(pawn_type)
},
None => panic!("Pawn captured by En Passant was not found"),
}
}
// Move a piece from source square to target
let source_piece = match self.piece_by_square(mov.source) {
Some(source_piece) => {
let source_id = source_piece as usize;
match mov.kind {
MoveKind::Promotion(promotion_piece) => {
let promo_id = promotion_piece as usize;
self.piece_sets[source_id] ^= move_source_bb;
self.occupancy ^= move_source_bb;
self.hash ^= self.zobrist_seed[source_id * 64 + mov.source as usize];
self.piece_sets[promo_id] |= move_target_bb;
self.occupancy |= move_target_bb;
self.hash ^= self.zobrist_seed[promo_id * 64 + mov.target as usize];
},
_ => {
self.piece_sets[source_id] ^= move_source_bb;
self.occupancy ^= move_source_bb;
self.hash ^= self.zobrist_seed[source_id * 64 + mov.source as usize];
self.piece_sets[source_id] |= move_target_bb;
self.occupancy |= move_target_bb;
self.hash ^= self.zobrist_seed[source_id * 64 + mov.target as usize];
}
}
PieceType::from(source_piece)
},
None => {
self.print();
panic!("{:?} is malformed: source piece not found", mov);
}
};
// When castling, also move a rook
if mov.kind == MoveKind::Castle {
debug_assert!(mov.source.file() == 4, "Castle can only be done from E file");
let (rook_source_file, rook_target_file) = match mov.target.file() {
2 => (0, 3),
6 => (7, 5),
_ => panic!("Malformed castle, target square invalid: {:?}", mov),
};
let rook_source_square = Square::from_coords(mov.target.rank(), rook_source_file);
let rook_source_bb = rook_source_square.to_bitboard();
let rook_target_square = Square::from_coords(mov.target.rank(), rook_target_file);
let rook_target_bb = rook_target_square.to_bitboard();
match self.piece_by_square(rook_source_square) {
Some(rook_type) => {
let rook_id = rook_type as usize;
self.piece_sets[rook_id] ^= rook_source_bb;
self.occupancy ^= rook_source_bb;
self.hash ^= self.zobrist_seed[rook_id * 64 + rook_source_square as usize];
self.piece_sets[rook_id] |= rook_target_bb;
self.occupancy |= rook_target_bb;
self.hash ^= self.zobrist_seed[rook_id * 64 + rook_target_square as usize];
},
None => panic!("Rook was not found when castling"),
}
}
// Double push should set En Passant target square
self.ep_target = if mov.kind == MoveKind::DoublePush {
self.hash ^= self.zobrist_seed[64 * 12 + 4 + mov.source.file() as usize];
match mov.source.rank() {
1 => Some(mov.source.nort_one()),
6 => Some(mov.source.sout_one()),
rank => panic!("Double-push was used from invalid rank({}) when trying to make {:?}", rank, mov),
}
} else { None };
// Withdraw castling rights when moving rooks or king
let source_color = Color::from_piece(source_piece) as usize;
match source_piece.without_color() {
PieceType::King => {
self.castling_rights[source_color][CastlingSide::King as usize] = false;
self.castling_rights[source_color][CastlingSide::Queen as usize] = false;
self.hash ^= self.zobrist_seed[64 * 12 + source_color * 2 + 0];
self.hash ^= self.zobrist_seed[64 * 12 + source_color * 2 + 1];
},
PieceType::Rook => {
match mov.source.file() {
0 => {
self.castling_rights[source_color][CastlingSide::Queen as usize] = false;
self.hash ^= self.zobrist_seed[64 * 12 + source_color * 2 + CastlingSide::Queen as usize];
}
7 => {
self.castling_rights[source_color][CastlingSide::King as usize] = false;
self.hash ^= self.zobrist_seed[64 * 12 + source_color * 2 + CastlingSide::King as usize];
}
_ => {},
}
},
_ => {},
}
self.ply += 1;
self.hash ^= self.zobrist_seed[780];
captured_piece
}
/// Completely reverse make_move as if it never happened
pub fn unmake_move(
&mut self,
mov: Move,
captured_piece: Option<PieceType>,
previous_ep_target: Option<Square>,
previous_castling_rights: [[bool; 2]; 2],
previous_hash: u64,
) {
let move_source_bb = mov.source.to_bitboard();
let move_target_bb = mov.target.to_bitboard();
// Move a piece from target square back to source square
match self.piece_by_square(mov.target) {
Some(source_piece) => {
match mov.kind {
MoveKind::Promotion(promotion_piece) => {
let promo_id = promotion_piece as usize;
self.piece_sets[promo_id] ^= move_target_bb;
self.occupancy ^= move_target_bb;
let source_id = match Color::from_piece(promotion_piece) {
Color::White => PieceType::Pawn,
Color::Black => PieceType::PawnBlack,
} as usize;
self.piece_sets[source_id] |= move_source_bb;
self.occupancy |= move_source_bb;
}
_ => {
let source_id = source_piece as usize;
self.piece_sets[source_id] ^= move_target_bb;
self.occupancy ^= move_target_bb;
self.piece_sets[source_id] |= move_source_bb;
self.occupancy |= move_source_bb;
}
}
},
None => panic!("Trying to unmake move which was not made: no piece was found on target square"),
};
// If unmaking castle, also return rook to its place
if mov.kind == MoveKind::Castle {
let (rook_source_file, rook_target_file) = match mov.target.file() {
2 => (0, 3),
6 => (7, 5),
_ => panic!("Malformed castle, target square invalid: {:?}", mov),
};
let rook_source_bb = Square::from_coords(mov.target.rank(), rook_source_file).to_bitboard();
let rook_target_bb = Square::from_coords(mov.target.rank(), rook_target_file).to_bitboard();
match self.piece_sets
.iter()
.enumerate()
.find(|(_, bitboard)| *bitboard & rook_target_bb > 0)
{
Some((rook_type, _)) => {
self.piece_sets[rook_type] |= rook_source_bb;
self.occupancy |= rook_source_bb;
self.piece_sets[rook_type] ^= rook_target_bb;
self.occupancy ^= rook_target_bb;
},
None => panic!("Rook was not found when castling"),
}
}
// Return captured piece to target square
match captured_piece {
Some(target_piece) => {
match mov.kind {
// Return pawn captured by En Passant pawn if needed
MoveKind::EnPassant => {
let original_dead_pawn_bb = Square::from_coords(mov.source.rank(), mov.target.file()).to_bitboard();
self.piece_sets[target_piece as usize] |= original_dead_pawn_bb;
self.occupancy |= original_dead_pawn_bb;
},
_ => {
self.piece_sets[target_piece as usize] |= move_target_bb;
self.occupancy |= move_target_bb;
},
}
},
None => {}
}
self.ep_target = previous_ep_target;
self.castling_rights = previous_castling_rights;
self.hash = previous_hash;
self.ply -= 1;
}
fn is_square_attacked(&self, square: Square, attacker_color: Color) -> bool {
for (piece_type, piece) in self.pieces_by_color(attacker_color).iter().enumerate() {
match PieceType::from(piece_type) {
PieceType::Queen => {
if self.attacks.queen(self.occupancy, square) & piece > 0 {
return true
}
}
PieceType::Knight => {
if self.attacks.knight[square as usize] & piece > 0 {
return true
}
}
PieceType::Bishop => {
if self.attacks.bishop(self.occupancy, square) & piece > 0 {
return true
}
}
PieceType::Rook => {
if self.attacks.rook(self.occupancy, square) & piece > 0 {
return true
}
}
PieceType::Pawn => {
if self.attacks.pawn[attacker_color.flip() as usize][square as usize] & piece > 0 {
return true
}
}
PieceType::King => {
if self.attacks.king[square as usize] & piece > 0 {
return true
}
}
_ => panic!("Unexpected piece type! Pieces by color should be considered white")
}
}
false
}
fn is_king_in_check(&self, color: Color) -> bool {
let king_bb = match color {
Color::White => self.piece_sets[PieceType::King as usize],
Color::Black => self.piece_sets[PieceType::KingBlack as usize],
};
let square = king_bb.bitscan();
self.is_square_attacked(square, color.flip())
}
}
#[derive(Debug, Clone, Copy, PartialEq, num_enum::FromPrimitive)]
#[repr(u8)]
pub enum Color {
#[default]
White,
Black,
}
impl Color {
pub fn flip(&self) -> Self {
match self {
Self::White => Self::Black,
Self::Black => Self::White,
}
}
pub fn from_piece(piece: PieceType) -> Self {
if (piece as u8) < 6 {
Self::White
} else {
Self::Black
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{bitboard::BitboardFns, square::Square, board::zobrist::Zobrist};
#[test]
fn 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 new_from_default_fen() {
let board = Board::new();
board.print();
board.empty().print("Empty squares");
assert_eq!(board.piece_sets[PieceType::Pawn as usize].pop_count(), 8);
assert_eq!(board.piece_sets[PieceType::Knight as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::Bishop as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::Rook as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::Queen as usize].pop_count(), 1);
assert_eq!(board.piece_sets[PieceType::King as usize].pop_count(), 1);
assert_eq!(board.piece_sets[PieceType::PawnBlack as usize].pop_count(), 8);
assert_eq!(board.piece_sets[PieceType::KnightBlack as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::BishopBlack as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::RookBlack as usize].pop_count(), 2);
assert_eq!(board.piece_sets[PieceType::QueenBlack as usize].pop_count(), 1);
assert_eq!(board.piece_sets[PieceType::KingBlack as usize].pop_count(), 1);
assert_eq!(board.piece_sets[PieceType::King as usize].bitscan(), Square::E1);
assert_eq!(board.piece_sets[PieceType::QueenBlack as usize].bitscan(), Square::D8);
assert_eq!(board.occupancy.pop_count(), 32);
assert_eq!(board.empty().pop_count(), 32);
assert_eq!(board.color_occupancy(Color::White).pop_count(), 16);
assert_eq!(board.color_occupancy(Color::Black).pop_count(), 16);
}
#[test]
fn generate_pseudolegal_moves_starting_position() {
let mut board = Board::new();
let moves = board.generate_pseudolegal_moves();
board.ply += 1;
let black_moves = board.generate_pseudolegal_moves();
assert_eq!(moves.len(), 20);
assert_eq!(black_moves.len(), 20);
for mov in moves {
mov.print();
}
}
#[test]
fn mobility() {
let board = Board::new();
let white = board.mobility(Color::White);
let black = board.mobility(Color::Black);
assert_eq!(white, 20.);
assert_eq!(black, 20.);
}
#[test]
fn make_move() {
let fen = String::from("q1b2k2/5p1p/4p1pb/pPPp4/3N4/3nPB2/P2QKnR1/1R6 w - - 0 25");
let mut board = Board::from_FEN(fen);
let initial_board = board.clone();
board.print();
let black_move = Move { source: Square::F7, target: Square::F5, kind: MoveKind::Quiet };
println!("\n{:?}", black_move);
match board.make_move(black_move) {
Some(..) => panic!("No piece should be captured"),
None => {},
};
board.print();
let hash = board.hash;
board.compute_hash();
assert_eq!(hash, board.hash, "Hash should be correctly updated after move");
assert!(board.piece_sets[PieceType::PawnBlack as usize] & Square::F7.to_bitboard() == 0);
assert!(board.piece_sets[PieceType::PawnBlack as usize] & Square::F5.to_bitboard() > 0);
assert!(board.ply == 1);
let white_move = Move { source: Square::D2, target: Square::A5, kind: MoveKind::Capture };
println!("\n{:?}", white_move);
match board.make_move(white_move) {
Some(captured) => assert!(captured == PieceType::PawnBlack),
None => panic!("A piece should be captured"),
};
board.print();
assert!(board.piece_sets[PieceType::PawnBlack as usize] & Square::A5.to_bitboard() == 0, "Target piece should be captured");
assert!(board.piece_sets[PieceType::Queen as usize] & Square::D2.to_bitboard() == 0);
assert!(board.piece_sets[PieceType::Queen as usize] & Square::A5.to_bitboard() > 0);
assert_ne!(board.occupancy, initial_board.occupancy, "Occupancy should change after make_move");
assert!(board.ply == 2);
}
#[test]
fn unmake_move() {
let fen = String::from("q1b2k2/5p1p/4p1pb/pPPp4/3N4/3nPB2/P2QKnR1/1R6 w - - 0 25");
let mut board = Board::from_FEN(fen);
let initial_board = board.clone();
let mov = Move { source: Square::D2, target: Square::A5, kind: MoveKind::Capture };
board.print();
let captured_piece = board.make_move(mov);
board.print();
board.unmake_move(mov, captured_piece, None, board.castling_rights, initial_board.hash);
board.print();
assert_eq!(board, initial_board, "Board state after unmake_move should be the same as before make_move");
}
#[test]
fn is_square_attacked() {
let board = Board::new();
assert_eq!(board.is_square_attacked(Square::E2, Color::White), true);
assert_eq!(board.is_square_attacked(Square::E2, Color::Black), false);
assert_eq!(board.is_square_attacked(Square::E4, Color::White), false);
assert_eq!(board.is_square_attacked(Square::B6, Color::Black), true);
}
#[test]
fn moved_king_castle() {
let fen = String::from("4k2r/ppp1n3/8/4R1Pp/5P2/q1P5/P1P1BP2/1K1R4 b - - 2 22");
let mut board = Board::from_FEN(fen);
board.ply += 1;
// Shuffle kings around, returning to the same position
board.make_move(Move { source: Square::E8, target: Square::F8, kind: MoveKind::Quiet });
board.make_move(Move { source: Square::B1, target: Square::A1, kind: MoveKind::Quiet });
board.make_move(Move { source: Square::F8, target: Square::E8, kind: MoveKind::Quiet });
board.make_move(Move { source: Square::A1, target: Square::B1, kind: MoveKind::Quiet });
let moves = board.generate_pseudolegal_moves();
let castle = moves.iter().find(|m| **m == Move { source: Square::E8, target: Square::G8, kind: MoveKind::Castle });
println!("{:?}", board.castling_rights);
assert!(castle.is_none(), "Castle should not be allowed after king has moved");
}
}
|