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
use crate::chessboard::Footprint;
use crate::{
BitBoard, ChessBoard, Color, FenLoadError, Move, MoveCreationError, MoveGen, Piece, PieceType,
Square, StrMoveCreationError,
};
use std::collections::HashMap;
/// The [`GameResult`] enum represents the result of a chess game.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum GameResult {
WhiteWins,
BlackWins,
Draw { reason: DrawReason },
}
/// The [`DrawReason`] enum represents the thing that caused a draw to occur.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DrawReason {
InsufficientMaterial,
Stalemate,
ThreefoldRepetition,
FiftyMoves,
}
/// The [`ChessGame`] struct represents a game of chess.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChessGame {
/// The game state.
state: ChessBoard,
/// The moves that can be made in the current position.
position_moves: Vec<Move>,
/// The reversible move history (for 3-fold repetition checking).
history: HashMap<Footprint, u8>,
/// The moves made in the game.
made_moves: Vec<Move>,
/// The result of the chess game.
result: Option<GameResult>,
}
impl ChessGame {
/// Creates a new [`ChessGame`] with the board in the starting position.
#[inline]
pub fn new() -> Self {
let state = ChessBoard::new();
Self::initialize_game(state)
}
/// Creates a new [`ChessGame`] with the board in the given fen position.
#[inline]
pub fn from_fen(fen: &str) -> Result<Self, FenLoadError> {
let state = ChessBoard::from_fen(fen)?;
Ok(Self::initialize_game(state))
}
/// Initializes a new [`ChessGame`].
fn initialize_game(state: ChessBoard) -> Self {
// Get the position moves.
let position_moves = MoveGen::legal(&state).to_vec();
// Initialize repetition history.
let mut history = HashMap::new();
history.insert(state.footprint(), 1);
// Create the game object.
let mut game = Self {
state,
position_moves,
history,
made_moves: vec![],
result: None,
};
// Look for terminal state.
game.look_for_terminal();
if game.result.is_some() {
game.position_moves.clear();
}
game
}
/// Makes a move.
///
/// If the game is over, an `Err` is returned.
///
/// # Examples
/// ```
/// use rchess::ChessGame;
///
/// // Create a new chess game
/// let mut game = ChessGame::new();
///
/// // Make a move in the chess game.
/// let mv = game.moves()[0];
/// game.make_move(mv).unwrap();
/// ```
#[inline]
pub fn make_move(&mut self, mv: Move) -> Result<(), ()> {
if self.result.is_some() {
return Err(());
}
self.state.make_move(mv);
self.made_moves.push(mv);
if let Move::Quiet { .. } = mv {
} else {
// Clear repetition history.
self.history.clear();
}
if let Some(count) = self.history.get_mut(&self.state.footprint()) {
*count += 1;
// Look for repetition.
if *count == 3 {
self.result = Some(GameResult::Draw {
reason: DrawReason::ThreefoldRepetition,
});
return Ok(());
}
} else {
self.history.insert(self.state.footprint(), 1);
}
self.position_moves = MoveGen::legal(&self.state).to_vec();
self.look_for_terminal();
Ok(())
}
/// Looks for a terminal state that is not a repetition.
fn look_for_terminal(&mut self) {
// Look for checkmate/stalemate.
if self.position_moves.is_empty() {
if self.state.checkers().is_empty() {
self.result = Some(GameResult::Draw {
reason: DrawReason::Stalemate,
})
} else {
self.result = Some(match self.state.turn() {
Color::White => GameResult::BlackWins,
Color::Black => GameResult::WhiteWins,
});
}
}
// Look for 50 move rule.
if self.state.halfmoves() >= 100 {
self.result = Some(GameResult::Draw {
reason: DrawReason::FiftyMoves,
})
}
if self.state.color_occupancy(Color::White).popcnt() == 1 {
if self.state.color_occupancy(Color::Black).popcnt() == 1 {
self.result = Some(GameResult::Draw {
reason: DrawReason::InsufficientMaterial,
})
} else if self.state.color_occupancy(Color::Black).popcnt() == 2 {
if !self.state.query(Piece::BLACK_BISHOP).is_empty()
|| !self.state.query(Piece::BLACK_KNIGHT).is_empty()
{
self.result = Some(GameResult::Draw {
reason: DrawReason::InsufficientMaterial,
})
}
}
} else if self.state.color_occupancy(Color::White).popcnt() == 2 {
if self.state.color_occupancy(Color::Black).popcnt() == 2 {
if self
.state
.query(Piece::WHITE_BISHOP)
.overlaps(BitBoard::WHITE_SQUARES)
{
if self
.state
.query(Piece::BLACK_BISHOP)
.overlaps(BitBoard::WHITE_SQUARES)
{
self.result = Some(GameResult::Draw {
reason: DrawReason::InsufficientMaterial,
})
}
} else if self
.state
.query(Piece::WHITE_BISHOP)
.overlaps(BitBoard::BLACK_SQUARES)
{
if self
.state
.query(Piece::BLACK_BISHOP)
.overlaps(BitBoard::BLACK_SQUARES)
{
self.result = Some(GameResult::Draw {
reason: DrawReason::InsufficientMaterial,
})
}
}
} else if self.state.color_occupancy(Color::Black).popcnt() == 1 {
if !self.state.query(Piece::WHITE_BISHOP).is_empty()
|| !self.state.query(Piece::WHITE_KNIGHT).is_empty()
{
self.result = Some(GameResult::Draw {
reason: DrawReason::InsufficientMaterial,
})
}
}
}
}
/// Returns `true` if the start and end squares make a legal move.
///
/// # Examples
/// ```
/// use rchess::{ChessGame, Square};
///
/// // Create a new chess game.
/// let game = ChessGame::new();
/// assert!(game.is_legal_move(Square::E2, Square::E4));
/// assert!(!game.is_legal_move(Square::E2, Square::E5));
/// ```
#[inline]
pub fn is_legal_move(&self, start: Square, end: Square) -> bool {
if self.result.is_some() {
return false;
}
MoveGen::is_legal(&self.state, start, end)
}
/// Attempts to turn a start and end square into a [`Move`].
///
/// Promotions default to a queen promotion.
///
/// # Examples
/// ```
/// use rchess::{ChessGame, Move, Square};
///
/// // Create a new chess game.
/// let game = ChessGame::new();
///
/// // Create the move "e2e4".
/// let mv = game.create_move(Square::E2, Square::E4).unwrap();
/// assert_eq!(mv, Move::DoublePawnPush { start: Square::E2, end: Square::E4 });
/// ```
#[inline]
pub fn create_move(&self, start: Square, end: Square) -> Result<Move, MoveCreationError> {
if self.result().is_some() {
return Err(MoveCreationError);
}
MoveGen::create_move(&self.state, start, end)
}
/// Attempts to turn a start and end square into a [`Move`].
///
/// The promotion target is set, but the move is ot necessarily a promotion.
///
/// # Examples
/// ```
/// use rchess::{ChessGame, Move, PieceType, Square};
///
/// // Create a new chess game.
/// let game = ChessGame::from_fen("3k4/PK6/8/8/8/8/8/8 w - -").unwrap();
///
/// // Promote to a knight.
/// let mv = game.create_promote_move(Square::A7, Square::A8, PieceType::Knight).unwrap();
/// assert_eq!(mv, Move::Promote { start: Square::A7, end: Square::A8, target: PieceType::Knight });
///
/// // Make a normal non-promotion move.
/// let mv = game.create_promote_move(Square::B7, Square::B8, PieceType::Knight).unwrap();
/// assert_eq!(mv, Move::Quiet { start: Square::B7, end: Square::B8, moving: PieceType::King });
/// ```
#[inline]
pub fn create_promote_move(
&self,
start: Square,
end: Square,
target: PieceType,
) -> Result<Move, MoveCreationError> {
if self.result().is_some() {
return Err(MoveCreationError);
}
MoveGen::create_promotion_move(&self.state, start, end, target)
}
/// Attempts to convert a string in algebraic chess notation, into a [`Move`].
///
/// # Examples
/// ```
/// use rchess::{ChessGame, Move, Square};
///
/// // Create a new chess game.
/// let game = ChessGame::new();
///
/// // Create the move "e2e4".
/// let mv = game.create_str_move("e2e4").unwrap();
/// assert_eq!(mv, Move::DoublePawnPush { start: Square::E2, end: Square::E4 });
/// ```
#[inline]
pub fn create_str_move(&self, str: &str) -> Result<Move, StrMoveCreationError> {
if self.result().is_some() {
return Err(StrMoveCreationError::IllegalMove(MoveCreationError));
}
MoveGen::create_str_move(&self.state, str)
}
/// Gets a reference to the underlying [`ChessBoard`].
#[inline]
pub fn board(&self) -> &ChessBoard {
&self.state
}
/// Gets a reference to all the moves made in the [`ChessGame`].
#[inline]
pub fn made_moves(&self) -> &Vec<Move> {
&self.made_moves
}
/// Gets the result of the [`ChessGame`], if any.
#[inline]
pub fn result(&self) -> Option<GameResult> {
self.result
}
/// Gets a list of possible moves for the active color to make.
#[inline]
pub fn moves(&self) -> &Vec<Move> {
&self.position_moves
}
}
impl Default for ChessGame {
/// The default for a [`ChessGame`] is a chess game in the starting position.
fn default() -> Self {
Self::new()
}
}