candidate 0.0.5

This is a fast chess move generator. It has a very good set of documentation, so you should take advantage of that. It (now) generates all lookup tables with a build.rs file, which means that very little pseudo-legal move generation requires branching. There are some convenience functions that are exposed to, for example, find all the squares between two squares. This uses a copy-on-make style structure, and the Board structure is as slimmed down as possible to reduce the cost of copying the board. There are places to improve perft-test performance further, but I instead opt to be more feature-complete to make it useful in real applications. For example, I generate both a hash of the board and a pawn-hash of the board for use in evaluation lookup tables (using Zobrist hashing). There are two ways to generate moves, one is faster, the other has more features that will be useful if making a chess engine. See the documentation for more details.
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
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
use crate::board::{Board, BoardStatus};
use crate::chess_move::ChessMove;
use crate::color::Color;
use crate::error::Error;
use crate::movegen::MoveGen;
use crate::piece::Piece;
use std::borrow::Borrow;
use std::str::FromStr;
#[cfg(any(feature = "instrument_game", feature = "instrument_all"))]
use tracing::instrument;

/// Contains all actions supported within the game
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Eq)]
pub enum Action {
    MakeMove(ChessMove),
    OfferDraw(Color),
    AcceptDraw,
    DeclareDraw,
    Resign(Color),
}

/// What was the result of this game?
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum GameResult {
    WhiteCheckmates,
    WhiteResigns,
    BlackCheckmates,
    BlackResigns,
    Stalemate,
    DrawAccepted,
    DrawDeclared,
}

/// For UI/UCI Servers, store a game object which allows you to determine
/// draw by 3 fold repitition, draw offers, resignations, and moves.
///
/// This structure is slow compared to using `Board` directly, so it is
/// not recommended for engines.
#[derive(Clone, Debug)]
pub struct Game {
    start_pos: Board,
    moves: Vec<Action>,
    #[cfg(feature = "cache_game_state")]
    boards: Vec<Board>,
}

impl Game {
    /// Create a new `Game` with the initial position.
    ///
    /// ```
    /// use candidate::{Game, Board};
    ///
    /// let game = Game::new();
    /// assert_eq!(game.current_position(), Board::default());
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn new() -> Game {
        Game {
            start_pos: Board::default(),
            moves: vec![],
            #[cfg(feature = "cache_game_state")]
            boards: vec![Board::default()],
        }
    }

    pub fn get_boards(&self) -> &Vec<Board> {
        &self.boards
    }

    /// Create a new `Game` with a specific starting position.
    ///
    /// ```
    /// use candidate::{Game, Board};
    ///
    /// let game = Game::new_with_board(Board::default());
    /// assert_eq!(game.current_position(), Board::default());
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn new_with_board(board: Board) -> Game {
        Game {
            start_pos: board,
            moves: vec![],
            #[cfg(feature = "cache_game_state")]
            boards: vec![board],
        }
    }

    /// Get all actions made in this game (moves, draw offers, resignations, etc.)
    ///
    /// ```
    /// use candidate::{Game, MoveGen, Color};
    ///
    /// let mut game = Game::new();
    /// let mut movegen = MoveGen::new_legal(&game.current_position());
    ///
    /// game.make_move(movegen.next().expect("At least one valid move"));
    /// game.resign(Color::Black);
    /// assert_eq!(game.actions().len(), 2);
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn actions(&self) -> &Vec<Action> {
        &self.moves
    }

    /// What is the status of this game?
    ///
    /// ```
    /// use candidate::Game;
    ///
    /// let game = Game::new();
    /// assert!(game.result().is_none());
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn result(&self) -> Option<GameResult> {
        match self.current_position().status() {
            BoardStatus::Checkmate => {
                if self.side_to_move() == Color::White {
                    Some(GameResult::BlackCheckmates)
                } else {
                    Some(GameResult::WhiteCheckmates)
                }
            }
            BoardStatus::Stalemate => Some(GameResult::Stalemate),
            BoardStatus::Ongoing => {
                if self.moves.len() == 0 {
                    None
                } else if self.moves[self.moves.len() - 1] == Action::AcceptDraw {
                    Some(GameResult::DrawAccepted)
                } else if self.moves[self.moves.len() - 1] == Action::DeclareDraw {
                    Some(GameResult::DrawDeclared)
                } else if self.moves[self.moves.len() - 1] == Action::Resign(Color::White) {
                    Some(GameResult::WhiteResigns)
                } else if self.moves[self.moves.len() - 1] == Action::Resign(Color::Black) {
                    Some(GameResult::BlackResigns)
                } else {
                    None
                }
            }
        }
    }

    /// Create a new `Game` object from an FEN string.
    ///
    /// ```
    /// use candidate::{Game, Board};
    ///
    /// // This is the better way:
    /// # {
    /// use std::str::FromStr;
    /// let game: Game = Game::from_str("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").expect("Valid FEN");
    /// let game2: Result<Game, _> = Game::from_str("Invalid FEN");
    /// assert!(game2.is_err());
    /// # }
    ///
    /// // This still works
    /// # {
    /// let game = Game::new_from_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1").expect("Valid FEN");
    /// let game2 = Game::new_from_fen("Invalid FEN");
    /// assert!(game2.is_none());
    /// # }
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    #[deprecated(since = "3.1.0", note = "Please use Game::from_str(fen)? instead.")]
    pub fn new_from_fen(fen: &str) -> Option<Game> {
        Game::from_str(fen).ok()
    }

    /// Get the current position on the board from the `Game` object.
    ///
    /// ```
    /// use candidate::{Game, Board};
    ///
    /// let game = Game::new();
    /// assert_eq!(game.current_position(), Board::default());
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn current_position(&self) -> Board {
        #[cfg(feature = "cache_game_state")]
        {
            self.boards.last().expect("At least one board").clone()
        }
        #[cfg(not(feature = "cache_game_state"))]
        {
            let mut copy = self.start_pos;

            for x in self.moves.iter() {
                if let Action::MakeMove(m) = *x {
                    copy = copy.make_move_new(m);
                }
            }

            copy
        }
    }

    /// Determine if a player can legally declare a draw by 3-fold repetition or 50-move rule.
    ///
    /// ```
    /// use candidate::{Game, Square, ChessMove};
    ///
    /// let b1c3 = ChessMove::new(Square::B1, Square::C3, None);
    /// let c3b1 = ChessMove::new(Square::C3, Square::B1, None);
    ///
    /// let b8c6 = ChessMove::new(Square::B8, Square::C6, None);
    /// let c6b8 = ChessMove::new(Square::C6, Square::B8, None);
    ///
    /// let mut game = Game::new();
    /// assert_eq!(game.can_declare_draw(), false);
    ///
    /// game.make_move(b1c3);
    /// game.make_move(b8c6);
    /// game.make_move(c3b1);
    /// game.make_move(c6b8);
    ///
    /// assert_eq!(game.can_declare_draw(), false); // position has shown up twice
    ///
    /// game.make_move(b1c3);
    /// game.make_move(b8c6);
    /// game.make_move(c3b1);
    /// game.make_move(c6b8);
    /// assert_eq!(game.can_declare_draw(), true); // position has shown up three times
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn can_declare_draw(&self) -> bool {
        if self.result().is_some() {
            return false;
        }

        let mut legal_moves_per_turn: Vec<(u64, Vec<ChessMove>)> = vec![];

        let mut board = self.start_pos;
        let mut reversible_moves = 0;

        // Loop over each move, counting the reversible_moves for draw by 50 move rule,
        // and filling a list of legal_moves_per_turn list for 3-fold repitition
        legal_moves_per_turn.push((board.get_hash(), MoveGen::new_legal(&board).collect()));
        for x in self.moves.iter() {
            if let Action::MakeMove(m) = *x {
                let white_castle_rights = board.castle_rights(Color::White);
                let black_castle_rights = board.castle_rights(Color::Black);
                if board.piece_on(m.get_source()) == Some(Piece::Pawn) {
                    reversible_moves = 0;
                    legal_moves_per_turn.clear();
                } else if board.piece_on(m.get_dest()).is_some() {
                    reversible_moves = 0;
                    legal_moves_per_turn.clear();
                } else {
                    reversible_moves += 1;
                }
                board = board.make_move_new(m);

                if board.castle_rights(Color::White) != white_castle_rights
                    || board.castle_rights(Color::Black) != black_castle_rights
                {
                    reversible_moves = 0;
                    legal_moves_per_turn.clear();
                }
                legal_moves_per_turn.push((board.get_hash(), MoveGen::new_legal(&board).collect()));
            }
        }

        if reversible_moves >= 100 {
            return true;
        }

        // Detect possible draw by 3 fold repitition
        let last_moves = legal_moves_per_turn[legal_moves_per_turn.len() - 1].clone();

        for i in 1..(legal_moves_per_turn.len() - 1) {
            for j in 0..i {
                if legal_moves_per_turn[i] == last_moves && legal_moves_per_turn[j] == last_moves {
                    return true;
                }
            }
        }

        return false;
    }

    /// Declare a draw by 3-fold repitition or 50-move rule.
    ///
    /// ```
    /// use candidate::{Game, Square, ChessMove};
    ///
    /// let b1c3 = ChessMove::new(Square::B1, Square::C3, None);
    /// let c3b1 = ChessMove::new(Square::C3, Square::B1, None);
    ///
    /// let b8c6 = ChessMove::new(Square::B8, Square::C6, None);
    /// let c6b8 = ChessMove::new(Square::C6, Square::B8, None);
    ///
    /// let mut game = Game::new();
    /// assert_eq!(game.can_declare_draw(), false);
    ///
    /// game.make_move(b1c3);
    /// game.make_move(b8c6);
    /// game.make_move(c3b1);
    /// game.make_move(c6b8);
    ///
    /// assert_eq!(game.can_declare_draw(), false); // position has shown up twice
    ///
    /// game.make_move(b1c3);
    /// game.make_move(b8c6);
    /// game.make_move(c3b1);
    /// game.make_move(c6b8);
    /// assert_eq!(game.can_declare_draw(), true); // position has shown up three times
    /// game.declare_draw();
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn declare_draw(&mut self) -> bool {
        if self.can_declare_draw() {
            self.moves.push(Action::DeclareDraw);
            true
        } else {
            false
        }
    }

    /// Make a chess move on the board
    ///
    /// ```
    /// use candidate::{Game, MoveGen};
    ///
    /// let mut game = Game::new();
    ///
    /// let mut movegen = MoveGen::new_legal(&game.current_position());
    ///
    /// game.make_move(movegen.next().expect("At least one legal move"));
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn make_move(&mut self, chess_move: ChessMove) -> Option<String> {
        if self.result().is_some() {
            return None;
        }

        let initial_position = self.current_position();
        if !initial_position.legal(chess_move) {
            return None;
        }

        #[cfg(feature = "cache_game_state")]
        {
            self.boards.push(initial_position.make_move_new(chess_move));
        }

        self.moves.push(Action::MakeMove(chess_move));
        Some(Self::generate_san(
            &initial_position,
            &self.current_position(),
            chess_move,
        ))
    }

    // Generate SAN for a given board and move.
    // Move must be legal.
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    fn generate_san(initial_board: &Board, final_board: &Board, chess_move: ChessMove) -> String {
        let mut san = String::new();

        // Add piece type if not pawn
        let piece = initial_board
            .piece_on(chess_move.get_source())
            .expect("the move is valid");

        // if the move is a castle, return the appropriate string
        if piece == Piece::King
            && chess_move.get_source().get_file() == crate::file::File::E
            && chess_move.get_dest().get_rank() == chess_move.get_source().get_rank()
        {
            if chess_move.get_dest().get_file() == crate::file::File::G {
                return "O-O".to_string();
            } else if chess_move.get_dest().get_file() == crate::file::File::C {
                return "O-O-O".to_string();
            }
        }
        if piece != Piece::Pawn {
            san.push(
                // white is uppercase??
                piece
                    .to_string(Color::White)
                    .to_uppercase()
                    .chars()
                    .next()
                    .expect("a piece has a valid string notation"),
            );
        }
        let is_capture = initial_board.piece_on(chess_move.get_dest()).is_some()
            || initial_board.en_passant_target() == Some(chess_move.get_dest());

        if is_capture {
            if piece == Piece::Pawn {
                san.push(
                    chess_move
                        .get_source()
                        .to_string()
                        .chars()
                        .next()
                        .expect("a square has a valid string notation"),
                );
            }

            san.push('x');
        }

        san.push_str(&chess_move.get_dest().to_string());

        let promotion = chess_move.get_promotion();
        if let Some(promotion) = promotion {
            san.push_str(&format!("={promotion}").to_uppercase());
        }

        if final_board.has_checkers() {
            if MoveGen::has_legal_moves(final_board) {
                san.push('+');
            } else {
                san.push('#');
            }
        }

        san
    }

    /// Who's turn is it to move?
    ///
    /// ```
    /// use candidate::{Game, Color};
    ///
    /// let game = Game::new();
    /// assert_eq!(game.side_to_move(), Color::White);
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn side_to_move(&self) -> Color {
        #[cfg(feature = "cache_game_state")]
        {
            self.current_position().side_to_move()
        }
        #[cfg(not(feature = "cache_game_state"))]
        {
            let move_count = self
                .moves
                .iter()
                .filter(|m| match *m {
                    Action::MakeMove(_) => true,
                    _ => false,
                })
                .count()
                + if self.start_pos.side_to_move() == Color::White {
                    0
                } else {
                    1
                };

            if move_count % 2 == 0 {
                Color::White
            } else {
                Color::Black
            }
        }
    }

    /// Offer a draw to my opponent.  `color` is the player who offered the draw.  The draw must be
    /// accepted before my opponent moves.
    ///
    /// ```
    /// use candidate::{Game, Color};
    ///
    /// let mut game = Game::new();
    /// game.offer_draw(Color::White);
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn offer_draw(&mut self, color: Color) -> bool {
        if self.result().is_some() {
            return false;
        }
        self.moves.push(Action::OfferDraw(color));
        return true;
    }

    /// Accept a draw offer from my opponent.
    ///
    /// ```
    /// use candidate::{Game, MoveGen, Color};
    ///
    /// let mut game = Game::new();
    /// game.offer_draw(Color::Black);
    /// assert_eq!(game.accept_draw(), true);
    ///
    /// let mut game2 = Game::new();
    /// let mut movegen = MoveGen::new_legal(&game2.current_position());
    /// game2.offer_draw(Color::Black);
    /// game2.make_move(movegen.next().expect("At least one legal move"));
    /// assert_eq!(game2.accept_draw(), false);
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn accept_draw(&mut self) -> bool {
        if self.result().is_some() {
            return false;
        }
        if self.moves.len() > 0 {
            if self.moves[self.moves.len() - 1] == Action::OfferDraw(Color::White)
                || self.moves[self.moves.len() - 1] == Action::OfferDraw(Color::Black)
            {
                self.moves.push(Action::AcceptDraw);
                return true;
            }
        }

        if self.moves.len() > 1 {
            if self.moves[self.moves.len() - 2] == Action::OfferDraw(!self.side_to_move()) {
                self.moves.push(Action::AcceptDraw);
                return true;
            }
        }

        false
    }

    /// `color` resigns the game
    ///
    /// ```
    /// use candidate::{Game, Color};
    ///
    /// let mut game = Game::new();
    /// game.resign(Color::White);
    /// ```
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    pub fn resign(&mut self, color: Color) -> bool {
        if self.result().is_some() {
            return false;
        }
        self.moves.push(Action::Resign(color));
        return true;
    }
}

impl FromStr for Game {
    type Err = Error;
    #[cfg_attr(
        any(feature = "instrument_game", feature = "instrument_all"),
        instrument
    )]
    fn from_str(fen: &str) -> Result<Self, Self::Err> {
        Ok(Game::new_with_board(Board::from_str(fen)?))
    }
}

#[cfg(test)]
pub fn fake_pgn_parser(moves: &str) -> Game {
    moves
        .split_whitespace()
        .filter(|s| !s.ends_with("."))
        .fold(Game::new(), |mut g, m| {
            g.make_move(ChessMove::from_san(&g.current_position(), m).expect("Valid SAN Move"));
            g
        })
}

#[test]
pub fn test_can_declare_draw() {
    let game = fake_pgn_parser(
        "1. Nc3 d5 2. e3 Nc6 3. Nf3 Nf6 4. Bb5 a6 5. Bxc6+ bxc6 6. Ne5 Qd6 7. d4 Nd7
                8. f4 Nxe5 9. dxe5 Qg6 10. O-O Bf5 11. e4 Bxe4 12. Nxe4 Qxe4 13. Re1 Qb4
                14. e6 f6 15. Be3 g6 16. Qd4 Qxd4 17. Bxd4 Bh6 18. g3 g5 19. f5 g4 20. Rad1
                Rg8 21. b3 Rb8 22. c4 dxc4 23. bxc4 Rd8 24. Kg2 Rc8 25. Bc5 Rg5 26. Rd7 Bf8
                27. Rf1 a5 28. Kg1 a4 29. Bb4 Rh5 30. Rf4 Rg5 31. Rf1 Rh5 32. Rf4 Rg5 33.
                Ba5",
    );
    assert!(!game.can_declare_draw());

    // three fold
    let game = fake_pgn_parser("1. Nc3 Nf6 2. Nb1 Ng8 3. Nc3 Nf6 4. Nb1 Ng8 5. Nc3 Nf6 6. Nb1 Ng8");
    assert!(game.can_declare_draw());

    // three fold (again)
    let game = fake_pgn_parser("1. Nc3 Nf6 2. Nb1 Ng8 3. Nc3 Nf6 4. Nb1 Ng8 5. Nc3 Nf6 6. Nb1");
    assert!(game.can_declare_draw());

    // three fold, but with a move at the end that breaks the draw cycle
    let game =
        fake_pgn_parser("1. Nc3 Nf6 2. Nb1 Ng8 3. Nc3 Nf6 4. Nb1 Ng8 5. Nc3 Nf6 6. Nb1 Ng8 7. e4");
    assert!(!game.can_declare_draw());

    // three fold, but with a move at the end that breaks the draw cycle
    let game =
        fake_pgn_parser("1. Nc3 Nf6 2. Nb1 Ng8 3. Nc3 Nf6 4. Nb1 Ng8 5. Nc3 Nf6 6. Nb1 Ng8 7. e4");
    assert!(!game.can_declare_draw());

    // fifty move rule
    let game = fake_pgn_parser("1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Nd2 a5 10. Rb1 Nd7 11. a3 f5 12. b4 Kh8 13. f3 Ng8 14. Qc2 Ngf6 15. Nb5 axb4 16. axb4 Nh5 17. g3 Ndf6 18. c5 Bd7 19. Rb3 Nxg3 20. hxg3 Nh5 21. f4 exf4 22. c6 bxc6 23. dxc6 Nxg3 24. Rxg3 fxg3 25. cxd7 g2 26. Rf3 Qxd7 27. Bb2 fxe4 28. Rxf8+ Rxf8 29. Bxg7+ Qxg7 30. Qxe4 Qf6 31. Nf3 Qf4 32. Qe7 Rf7 33. Qe6 Rf6 34. Qe8+ Rf8 35. Qe7 Rf7 36. Qe6 Rf6 37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ra1 93. Nfe6+ Kh6 94. Be8 Ra8 95. Bc6 Ra1 96. Kf6 Kh7 97. Ng5+ Kh8 98. Nde6 Ra6 99. Be8 Ra8 100. Bh5 Ra1 101. Bg6 Rf1+ 102. Ke7 Ra1 103. Nf7+ Kg8 104. Nh6+ Kh8 105. Nf5 Ra7+ 106. Kf6 Ra1 107. Ne3 Re1 108. Nd5 Rg1 109. Bf5 Rf1 110. Ndf4 Ra1 111. Ng6+ Kg8 112. Ne7+ Kh8");
    assert!(!game.can_declare_draw());
}

#[test]
pub fn test_make_move() {
    use crate::square::Square;

    let mut game = Game::new();

    #[rustfmt::skip]
    let move_list = [
        (ChessMove::new(Square::D2, Square::D4, None), "d4"),
        (ChessMove::new(Square::D2, Square::D4, None), ""),
        (ChessMove::new(Square::D7, Square::D5, None), "d5"),
        (ChessMove::new(Square::C2, Square::C4, None), "c4"),
        (ChessMove::new(Square::D5, Square::C4, None), "dxc4"),
        (ChessMove::new(Square::D1, Square::A4, None), "Qa4+"),
        (ChessMove::new(Square::C8, Square::D7, None), "Bd7"),
        (ChessMove::new(Square::A4, Square::C4, None), "Qxc4"),
        (ChessMove::new(Square::G8, Square::F6, None), "Nf6"),
        (ChessMove::new(Square::E2, Square::E4, None), "e4"),
        (ChessMove::new(Square::F6, Square::D5, None), "Nd5"),
        (ChessMove::new(Square::E4, Square::D5, None), "exd5"),
        (ChessMove::new(Square::E7, Square::E5, None), "e5"),
        (ChessMove::new(Square::D5, Square::E6, None), "dxe6"), // en passant
        (ChessMove::new(Square::D8, Square::H4, None), "Qh4"),
        (ChessMove::new(Square::C4, Square::D5, None), "Qd5"),
        (ChessMove::new(Square::F8, Square::B4, None), "Bb4+"),
        (ChessMove::new(Square::C1, Square::D2, None), "Bd2"),
        (ChessMove::new(Square::E8, Square::G8, None), "O-O"),
        (ChessMove::new(Square::B1, Square::C3, None), "Nc3"),
        (ChessMove::new(Square::H4, Square::H6, None), "Qh6"),
        (ChessMove::new(Square::E1, Square::C1, None), "O-O-O"),
        (ChessMove::new(Square::H6, Square::H4, None), "Qh4"),
        (ChessMove::new(Square::E6, Square::D7, None), "exd7"),
        (ChessMove::new(Square::H4, Square::H3, None), "Qh3"),
        (ChessMove::new(Square::D7, Square::D8, Some(Piece::Queen)), "d8=Q"),
        (ChessMove::new(Square::F8, Square::D8, None), "Rxd8"),
        (ChessMove::new(Square::C3, Square::B1, None), "Nb1"),
        (ChessMove::new(Square::B4, Square::D2, None), "Bxd2+"),
        (ChessMove::new(Square::B1, Square::D2, None), "Nxd2"),
        (ChessMove::new(Square::H3, Square::D3, None), "Qd3"),
        (ChessMove::new(Square::D5, Square::D8, None), "Qxd8#"),
    ];

    for (mv, expected_san) in move_list.iter() {
        let san = game.make_move(*mv);
        if (*expected_san).len() == 0 {
            assert_eq!(san, None);
        } else {
            assert_eq!(
                san,
                Some(expected_san.to_string()),
                "\n'{}' for move: '{}' didn't match the expected san ({}). position: \n{}",
                san.clone().unwrap_or_default(),
                mv,
                expected_san,
                game.current_position().color_combined(Color::White)
                    | game.current_position().color_combined(Color::Black)
            );
        }
    }
}