Skip to content
BytePatterns

Legal Moves That Keep the King Safe

HardLow-Level Design#board-model#move-generation#check-detection~35m

Problem

Model a chess board with kings, queens, rooks, bishops and knights (no pawns, no castling). A position is a dict from square to piece, such as {"e1": "K", "e8": "r"}, with white pieces in upper case and black in lower case. Write analyse(position, white) for the side to move. A move is legal if the piece can reach the square, sliding pieces stop at the first occupied square and may capture it only if it holds an enemy, and afterwards the mover's own king is not attacked. Return the state, "checkmate", "stalemate", "check" or "play", together with the sorted legal moves written as from-square plus to-square, like "e2e4".

Examples

Input:  {"h8": "k", "g7": "Q", "f6": "K"}, black to move
Output: ('checkmate', [])
Why:    the queen attacks every square around the king and the white king guards the queen
Input:  {"a8": "k", "b6": "Q", "c1": "K"}, black to move
Output: ('stalemate', [])
Why:    the king is not attacked, but every square it could step to is
Input:  {"e1": "K", "e8": "r", "b4": "b", "c3": "N", "h8": "k"}, white to move
Output: ('check', ['e1d1', 'e1d2', 'e1f1', 'e1f2'])
Why:    edge case, the knight could block on e2 or e4, but the bishop pins it to the king

Hints

0 / 3

Stuck on the idea rather than the code? Chess Board Model covers it.