nozaq / shogi-rs

A Bitboard-based shogi library in Rust. Board representation, move generation/validation and time control utilities.
https://docs.rs/shogi/latest/shogi/
MIT License
46 stars 3 forks source link

Figure out if the position is checkmate, drawn (repetition) #13

Open ZelphirKaltstahl opened 6 years ago

ZelphirKaltstahl commented 6 years ago

How would you figure out if a player has won in a position?

nozaq commented 6 years ago

@ZelphirKaltstahl When you call Position#make_move() and the resulting position after the move is invalid, it returns MoveError. You can detect checkmate and repetition using this result as follows.

1. Checkmate

If you get MoveError::InCheck from make_move(), this means that the move is illegal since the king is still in check even after making a move. Given the king is already in check, you can detect the player is checkmated by trying every possible moves and check if no legal move exist. Position#move_candidates() could be used to produce possible moves though, it's necessary to call it with each piece on the board. Currently the only way to get each piece on the board is to iterate through all squares and call [Position#piece_at()])(https://nozaq.github.io/shogi-rs/shogi/position/struct.Position.html#method.piece_at). I'm thinking to implement an easier way to iterate over pieces of the particular player, which hopefully improve the performance of iteration.

2. Repetition

This case is simple. If you get MoveError::Repetition after making a move, that means the game should be drawn because of repetition. Note that there is a special case in repetition situation called Perpetual Check(see https://en.wikipedia.org/wiki/Shogi). MoveError::PerpetualCheckWin and MoveError::PerpetualCheckLose exist for this case.

Hope this would help, please let me know if you have other questions :)

ZelphirKaltstahl commented 6 years ago

Thanks for your response. I already thought of trying all moves, but was hoping there was something better. It should still be OKish performance, but of course a more efficient way would be great. I would also need to try with inserting pieces everywhere, unless I involve some logic about what piece puts the king in check and squares where it can be etc.

Thanks for the hint about perpetual check as well, I only recently learned about that on https://www.gnu.org/software/gnushogi/manual/The-rules-of-shogi.html .