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
use chess::{
BitBoard, ChessMove, Color, File, Rank, Square, EMPTY, NUM_COLORS,
};
type PromoArray = [BitBoard; NUM_COLORS];
fn empty() -> PromoArray {
[EMPTY; NUM_COLORS]
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Promotions {
promos: PromoArray,
}
impl Promotions {
pub fn new(promos: &PromoArray) -> Self {
Promotions { promos: *promos }
}
pub fn is_promo(&self, color: Color, sq: Square) -> bool {
self.promos[color.to_index()] & BitBoard::from_square(sq) != EMPTY
}
pub fn add_square(&mut self, color: Color, sq: Square) {
self.promos[color.to_index()] |= BitBoard::from_square(sq);
}
pub fn clear_square(&mut self, color: Color, sq: Square) {
self.promos[color.to_index()] &= !BitBoard::from_square(sq);
}
pub fn record_move(&mut self, mover: Color, mv: ChessMove) {
if mv.get_promotion().is_some() {
self.add_square(mover, mv.get_dest());
return;
}
if self.is_promo(mover, mv.get_source()) {
self.clear_square(mover, mv.get_source());
self.add_square(mover, mv.get_dest());
}
self.clear_square(!mover, mv.get_dest());
}
pub fn from_fen(fen: &str) -> Promotions {
let mut bit_boards = [EMPTY; 2];
for (row, rank_idx) in fen.split('/').zip((0..8_usize).rev()) {
let mut file_idx = 0;
let mut last_color = Color::White;
for ch in row.chars() {
match ch {
'1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' => {
file_idx += (ch as usize) - ('0' as usize)
}
'p' | 'n' | 'b' | 'r' | 'q' | 'k' => {
last_color = Color::Black;
file_idx += 1;
}
'P' | 'N' | 'B' | 'R' | 'Q' | 'K' => {
last_color = Color::White;
file_idx += 1;
}
'~' => {
let file = File::from_index(file_idx - 1);
let rank = Rank::from_index(rank_idx);
let sq = Square::make_square(rank, file);
let bitboard = BitBoard::from_square(sq);
bit_boards[last_color.to_index()] |= bitboard;
}
_ => {}
}
}
}
Promotions::new(&bit_boards)
}
}
impl Default for Promotions {
#[inline]
fn default() -> Self {
Promotions { promos: empty() }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PromotionsParseError {
fen: String,
}
#[test]
fn parse_promos() {
let promos = Promotions::from_fen("Q~4rk1/8/8/8/8/8/8/R3K2R");
assert!(promos.is_promo(Color::White, Square::A8));
}