I am trying to write a program that will give out every possible move for every piece (one move deep) given the state of a board. I have already done this such that it works with everything except check. It will allow the king to move itself into check, and it will allow a piece to be moved out of the way such that it places the king in check. I can't think of an efficient way of removing these moves from the set of moves I generate.
I am storing the board as a list of lists, where each list is a row on the board. Black is at the top and white is at the bottom. Lowercase is black, uppercase is white.
P = pawn, R = rook, N = Knight, Q = Queen, K = King.
Therefore, the starting board looks like this:
board = [["r", "n", "b", "q", "k", "b", "n", "r"],
["p", "p", "p", "p", "p", "p", "p", "p"],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["P", "P", "P", "P", "P", "P", "P", "P"],
["R", "N", "B", "Q", "K", "B", "N", "R"]]
So for example, board[7][2]
is "B"
.
The moves are stored as a list of lists, where each sub list contains the current coordinates of the piece and a list of all available moves for said piece.
For example
[[[1, 0], [[2, 0], [3, 0]]], ...]
As the pawn at 1, 0
can move forward either once or twice.
These are then stored in two separate lists, white_moves
and black_moves
.
So, I think the best way to prevent the king from moving into check is seeing if any of the moves generated for the king are in the opponent's moves, and then removing them from the king's moves if they are.
Like
king_moves = set(king_moves) - set(enemy_moves)
However, I can't think of a good way of determining if the movement of one of our pieces will result in the king being exposed and thus in check.
import chess
,board = chess.Board('8/4k3/8/8/4R3/8/8/4K3 w - - 0 1')
to set up the board which you can print to test,print board
, and to generate moves (though legally it's impossible for it to be white's turn as black is in check),board.legal_moves
can be used. The library has all the features and functionalities you need for your purposes. Have fun!