Most efficient way to generate legal king moves?
Posted: Sat Feb 04, 2017 8:13 pm
I'm using a 12x10 board representation.
I'm currently stuck at 1.8s for a perft 6 (c++), but the way I generate king moves is highly inefficient.
For each king move, I execute it and loop through each enemy piece to see if I put it in check.
For both castlings, I loop through each enemy piece and see if they attack the two squares adjacent to the king.
The first problem is not as slow as the second, but is the most consistent and therefore the most time consuming.
The second is very slow but only occurs when all the squares between king and rooks are empty, and castling permissions are up. I still really want to completely change the logic.
I have a few ideas, mostly incremental, but they seem like a mess to implement and prone to errors, which I'm tired to fix. Does anyone have a clean solution for this problem?
As a bonus to not make another thread: is it, in your experience, more efficient to add a "dead" boolean to each piece and verify each time you loop, or place dead pieces at the end of your array and keep track of the count so you don't have to check if the piece is dead anymore?
This is a sample code that verifies that my king is not in check:
I'm currently stuck at 1.8s for a perft 6 (c++), but the way I generate king moves is highly inefficient.
For each king move, I execute it and loop through each enemy piece to see if I put it in check.
For both castlings, I loop through each enemy piece and see if they attack the two squares adjacent to the king.
The first problem is not as slow as the second, but is the most consistent and therefore the most time consuming.
The second is very slow but only occurs when all the squares between king and rooks are empty, and castling permissions are up. I still really want to completely change the logic.
I have a few ideas, mostly incremental, but they seem like a mess to implement and prone to errors, which I'm tired to fix. Does anyone have a clean solution for this problem?
As a bonus to not make another thread: is it, in your experience, more efficient to add a "dead" boolean to each piece and verify each time you loop, or place dead pieces at the end of your array and keep track of the count so you don't have to check if the piece is dead anymore?
This is a sample code that verifies that my king is not in check:
Code: Select all
Piece** board = game.getBoard();
Piece* enemyPieces = game.getPieces()[1 - piece.side];
board[toSquare] = &piece;
board[piece.square] = (Piece*)&piece::NO_PIECE;
for (int i = 0; i < 16; i++) {
Piece& ePiece = enemyPieces[i];
if (!ePiece.dead && ePiece != toPiece) {
if (sqattack::attacksSquare(ePiece, toSquare, game)) {
board[piece.square] = &piece;
board[toSquare] = &toPiece;
return true;
}
}
}
board[piece.square] = &piece;
board[toSquare] = &toPiece;
return false;