chess-lab 0.2.1

Chess library with multiple variants and FEN/PGN support.
Documentation
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
use std::{collections::HashMap, fmt};

use crate::errors::MoveInfoError;

use super::{GameStatus, Piece, PieceType, Position};

/// Represents the type of a [Move]
///
#[derive(Debug, Clone, PartialEq)]
pub enum MoveType {
    /// A normal move
    Normal {
        /// Whether the move is a capture
        capture: bool,
        /// The [PieceType] to promote to
        promotion: Option<PieceType>,
    },
    /// A castle move
    Castle {
        /// The side of the board to castle on
        side: CastleType,
    },
    /// An en passant move
    EnPassant,
}

/// Represents the side of the board to castle on
///
#[derive(Debug, Clone, PartialEq)]
pub enum CastleType {
    /// The king side
    KingSide,
    /// The queen side
    QueenSide,
}

/// Represents a move in a chess game
///
#[derive(Debug, Clone, PartialEq)]
pub struct Move {
    /// The [Piece] that is moving
    pub piece: Piece,
    /// The [Position] the piece is moving from
    pub from: Position,
    /// The [Position] the piece is moving to
    pub to: Position,
    /// The [type](Move) of the move
    pub move_type: MoveType,
    /// The type of the piece that is captured, if any
    pub captured_piece: Option<PieceType>,
    /// The position of the rook, if the move is a castle
    pub rook_from: Option<Position>,
    /// A tuple of booleans representing the ambiguity of the move
    pub ambiguity: (bool, bool),
    /// Whether the move puts the opponent in check
    pub check: bool,
    /// Whether the move puts the opponent in checkmate
    pub checkmate: bool,
}

impl Move {
    /// Creates a new [Move]
    ///
    /// # Arguments
    /// * `piece`: The [Piece] that is moving
    /// * `from`: The [Position] the piece is moving from
    /// * `to`: The [Position] the piece is moving to
    /// * `move_type`: The [type](MoveType) of the move
    /// * `captured_piece`: The [Piece] that is captured, if any
    /// * `rook_from`: The [Position] of the rook, if the move is a castle
    /// * `ambiguity`: A tuple of booleans representing the ambiguity of the move
    /// * `check`: Whether the move puts the opponent in check
    /// * `checkmate`: Whether the move puts the opponent in checkmate
    ///
    /// # Returns
    /// A `Result<Move, MoveInfoError>`
    /// * `Ok(Move)`: The move if it is valid
    /// * `Err(MoveInfoError)`: The error if the move is invalid
    ///
    /// # Example
    /// ```
    /// use chess_lab::core::{Color, PieceType, Piece, Position, Move, MoveType};
    ///
    /// let piece = Piece::new(Color::White, PieceType::Pawn);
    /// let from = Position::new(4, 1).unwrap();
    /// let to = Position::new(4, 3).unwrap();
    /// let move_type = MoveType::Normal {
    ///     capture: false,
    ///     promotion: None,
    /// };
    /// let captured_piece = None;
    /// let rook_from = None;
    /// let ambiguity = (false, false);
    /// let mv = Move::new(
    ///     piece,
    ///     from,
    ///     to,
    ///     move_type,
    ///     captured_piece,
    ///     rook_from,
    ///     ambiguity,
    ///     false,
    ///     false
    /// ).unwrap();
    ///
    /// assert_eq!(mv.to_string(), "e4");
    /// ```
    ///
    pub fn new(
        piece: Piece,
        from: Position,
        to: Position,
        move_type: MoveType,
        captured_piece: Option<PieceType>,
        rook_from: Option<Position>,
        ambiguity: (bool, bool),
        check: bool,
        checkmate: bool,
    ) -> Result<Move, MoveInfoError> {
        let mov = Move {
            piece,
            from,
            to,
            move_type: move_type.clone(),
            captured_piece,
            rook_from,
            ambiguity,
            check,
            checkmate,
        };
        match &move_type {
            MoveType::Normal {
                capture: _,
                promotion,
            } => {
                if promotion.is_some() {
                    if piece.piece_type != PieceType::Pawn {
                        return Err(MoveInfoError::new(
                            String::from("The move is a promotion, but the piece is not a pawn"),
                            mov,
                        ));
                    }
                }
            }
            MoveType::Castle { side: _ } => {
                if piece.piece_type != PieceType::King {
                    return Err(MoveInfoError::new(
                        String::from("The move is a castle, but the piece is not a king"),
                        mov,
                    ));
                }
                if rook_from.is_none() {
                    return Err(MoveInfoError::new(
                        String::from("The move is a castle, but no rook position is provided"),
                        mov,
                    ));
                }
            }
            MoveType::EnPassant => {
                if piece.piece_type != PieceType::Pawn {
                    return Err(MoveInfoError::new(
                        String::from("The move is an en passant, but the piece is not a pawn"),
                        mov,
                    ));
                }
            }
        }
        Ok(mov)
    }
}

impl fmt::Display for Move {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let mut result = String::new();
        if self.piece.piece_type != PieceType::Pawn {
            result.push(self.piece.piece_type.to_char());
        }
        match &self.move_type {
            MoveType::Castle { side } => {
                result = match side {
                    CastleType::KingSide => "O-O".to_string(),
                    CastleType::QueenSide => "O-O-O".to_string(),
                };
            }
            MoveType::Normal { capture, promotion } => {
                let from_string = self.from.to_string();
                if self.ambiguity.0 || (PieceType::Pawn == self.piece.piece_type && *capture) {
                    result.push(from_string.chars().nth(0).unwrap());
                }
                if self.ambiguity.1 {
                    result.push(from_string.chars().nth(1).unwrap());
                }
                if *capture {
                    result.push('x');
                }
                result.push_str(&self.to.to_string());
                if let Some(promotion) = promotion {
                    result.push('=');
                    result.push(promotion.to_char());
                }
            }
            MoveType::EnPassant => {
                result.push_str(&self.from.to_string());
                result.push('x');
                result.push_str(&self.to.to_string());
            }
        }
        if self.checkmate {
            result.push('#');
        } else if self.check {
            result.push('+');
        }

        write!(f, "{}", result)
    }
}

/// Represents the information of a [Move]
///
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct MoveInfo {
    /// The number of halfmoves since the last capture or pawn move
    pub halfmove_clock: u32,
    /// The number of fullmoves
    pub fullmove_number: u32,
    /// The en passant target square
    pub en_passant: Option<Position>,
    /// The castling rights
    pub castling_rights: u8,
    /// The status of the [Game](crate::logic::Game)
    pub game_status: GameStatus,
    /// A map of previous board positions and their occurrence counts
    pub prev_positions: HashMap<String, u32>,
}

impl MoveInfo {
    /// Creates a new [MoveInfo]
    ///
    /// # Arguments
    /// * `halfmove_clock`: The number of halfmoves since the last capture or pawn move
    /// * `fullmove_number`: The number of fullmoves
    /// * `en_passant`: The en passant target square
    /// * `castling_rights`: The castling rights
    /// * `game_status`: The current [GameStatus]
    ///
    /// # Example
    /// ```
    /// use chess_lab::core::{GameStatus, MoveInfo};
    /// use std::collections::HashMap;
    ///
    /// let move_info = MoveInfo::new(0, 1, None, 0, GameStatus::InProgress, HashMap::new());
    ///
    /// assert_eq!(move_info.halfmove_clock, 0);
    /// assert_eq!(move_info.fullmove_number, 1);
    /// assert_eq!(move_info.en_passant, None);
    /// assert_eq!(move_info.castling_rights, 0);
    /// assert_eq!(move_info.game_status, GameStatus::InProgress);
    /// assert_eq!(move_info.prev_positions.len(), 0);
    /// ```
    ///
    pub fn new(
        halfmove_clock: u32,
        fullmove_number: u32,
        en_passant: Option<Position>,
        castling_rights: u8,
        game_status: GameStatus,
        prev_positions: HashMap<String, u32>,
    ) -> MoveInfo {
        MoveInfo {
            halfmove_clock,
            fullmove_number,
            en_passant,
            castling_rights,
            game_status,
            prev_positions,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Color, PieceType};

    #[test]
    fn test_move_display_normal() {
        let piece = Piece::new(Color::White, PieceType::Knight);
        let from = Position::new(1, 0).unwrap(); // b1
        let to = Position::new(2, 2).unwrap(); // c3
        let move_type = MoveType::Normal {
            capture: false,
            promotion: None,
        };
        let mv = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            None,
            (false, false),
            false,
            false,
        )
        .unwrap();
        assert_eq!(mv.to_string(), "Nc3");
    }

    #[test]
    fn test_move_display_capture() {
        let piece = Piece::new(Color::Black, PieceType::Bishop);
        let from = Position::new(2, 7).unwrap(); // c8
        let to = Position::new(5, 4).unwrap(); // f5
        let move_type = MoveType::Normal {
            capture: true,
            promotion: None,
        };
        let mv = Move::new(
            piece,
            from,
            to,
            move_type,
            Some(PieceType::Pawn),
            None,
            (false, false),
            true,
            false,
        )
        .unwrap();
        assert_eq!(mv.to_string(), "Bxf5+");
    }

    #[test]
    fn test_move_display_kingside_castle() {
        let piece = Piece::new(Color::White, PieceType::King);
        let from = Position::new(4, 0).unwrap(); // e1
        let to = Position::new(6, 0).unwrap(); // g1
        let move_type = MoveType::Castle {
            side: CastleType::KingSide,
        };
        let mv = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            Some(Position::new(7, 0).unwrap()), // h1
            (false, false),
            false,
            false,
        )
        .unwrap();
        assert_eq!(mv.to_string(), "O-O");
    }

    #[test]
    fn test_move_display_queenside_castle() {
        let piece = Piece::new(Color::Black, PieceType::King);
        let from = Position::new(4, 7).unwrap(); // e8
        let to = Position::new(2, 7).unwrap(); // c8
        let move_type = MoveType::Castle {
            side: CastleType::QueenSide,
        };
        let mv = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            Some(Position::new(0, 7).unwrap()), // a8
            (false, false),
            false,
            false,
        )
        .unwrap();
        assert_eq!(mv.to_string(), "O-O-O");
    }

    #[test]
    fn test_promoting_non_pawn_error() {
        let piece = Piece::new(Color::White, PieceType::Knight);
        let from = Position::new(6, 7).unwrap(); // g8
        let to = Position::new(7, 7).unwrap(); // h8
        let move_type = MoveType::Normal {
            capture: false,
            promotion: Some(PieceType::Queen),
        };
        let mv_result = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            None,
            (false, false),
            false,
            false,
        );
        assert!(mv_result.is_err());
    }

    #[test]
    fn test_castling_non_king_error() {
        let piece = Piece::new(Color::Black, PieceType::Queen);
        let from = Position::new(4, 7).unwrap(); // e8
        let to = Position::new(6, 7).unwrap(); // g8
        let move_type = MoveType::Castle {
            side: CastleType::KingSide,
        };
        let mv_result = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            Some(Position::new(7, 7).unwrap()), // h8
            (false, false),
            false,
            false,
        );
        assert!(mv_result.is_err());
    }

    #[test]
    fn test_castle_with_no_rook_error() {
        let piece = Piece::new(Color::White, PieceType::King);
        let from = Position::new(4, 0).unwrap(); // e1
        let to = Position::new(2, 0).unwrap(); // c1
        let move_type = MoveType::Castle {
            side: CastleType::QueenSide,
        };
        let mv_result = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            None, // No rook position provided
            (false, false),
            false,
            false,
        );
        assert!(mv_result.is_err());
    }

    #[test]
    fn test_en_passant_non_pawn_error() {
        let piece = Piece::new(Color::Black, PieceType::Bishop);
        let from = Position::new(3, 4).unwrap(); // d5
        let to = Position::new(4, 3).unwrap(); // e4
        let move_type = MoveType::EnPassant;

        let mv_result = Move::new(
            piece,
            from,
            to,
            move_type,
            None,
            None,
            (false, false),
            false,
            false,
        );
        assert!(mv_result.is_err());
    }
}