jordanbray / chess

A rust library to manage chess move generation
https://jordanbray.github.io/chess/
MIT License
234 stars 54 forks source link

Board.legal() fails after Board.null_move() #11

Closed mattbruv closed 6 years ago

mattbruv commented 6 years ago

The Board.legal() function fails at recognizing legal moves/pins after Board.null_move() is called. Take the following example position. The positions start exactly the same way except for the side to move. In the white example, it considers Ra2 illegal as it should. However in the exact same position, with white to move (after a null move from black), it considers Ra2 legal.

extern crate chess;

use chess::*;

fn main() {

    let pos_white     = Board::from_fen("4k3/3r4/8/8/8/8/3R4/3K4 w - - 0 1".to_owned()).unwrap();
    let mut pos_black = Board::from_fen("4k3/3r4/8/8/8/8/3R4/3K4 b - - 0 1".to_owned()).unwrap();

    let testmove = ChessMove::new(
        Square::from_string("d2".to_owned()).unwrap(),
        Square::from_string("a2".to_owned()).unwrap(),
        None);

    // Ra2 should fail because of the pin
    assert!(pos_white.legal(testmove) == false);

    // Same exact position, but black has the move.
    // Let's change the side to move to white via null_move
    pos_black = pos_black.null_move().unwrap();

    // Make sure white is the side to move
    assert!(pos_black.side_to_move() == Color::White);

    // Ra2 should be illegal, because the position is exactly the same as pos_white
    assert!(pos_black.legal(testmove) == false); // assertion failed
}
jordanbray commented 6 years ago

Clearly, the null_move() function is not updating the board state well enough to do proper legality checks. Let me look into this over the weekend and confirm and fix this issue.

mattbruv commented 6 years ago

Sounds good. Thanks a lot for making this library. It takes out so much of the heavy work that goes into making a chess engine and it has been a pleasure to use in my project so far.

jordanbray commented 6 years ago

No problem. Thanks for using the library. The stated goal of this project is to prevent every chess engine developer from writing their own move generator (I've been there myself.) I'm happy to take the burden off of other people in a useful way.

jordanbray commented 6 years ago

Sorry for forgetting about this one. The patch looks good, I tested it as well. It is merged and version 0.4.2 is released.