I have made a chess engine, and it seems from cProfile that my most expensive function is the one that calculates attack squares for both players. Here is the cProfile results for a perft function I wrote that goes 4 ply deep: https://i.stack.imgur.com/TADwV.jpg

The reason why my calculate attack squares function is so expensive is because every time a move is made in perft, the position is a new one, and attack squares for both players have to be recalculated. My question is this: Is there a more efficient way to be calculating attack squares for both players? Is there a way I can avoid having to recalculate attack squares for all 32 pieces every time a move is made in perft? Thank you.

https://repl.it/@kasparov/ImportantNotedCoderesource My code for anyone who's curious

  • 2
    These questions, while tangentially chess-related, seem like you would get more response in a programming forum. Sep 25, 2019 at 13:01
  • You could use the list of existing attack squares from the previous position, and then update it accordingly with just the changes the last move made on the new position. This is more efficient than recalculating entirely. Sep 28, 2019 at 23:16

1 Answer 1


It may help to keep a list of each piece and the squares it attacks for the position.

Then when a move occurs, you can reduce the work calculating for the pieces that don't move. Non-moving kings, knights, and pawns will attack the same squares as before. Non-moving queens, bishops, and rooks only need to be recalculated if a piece moved to or away from a square they attacked.

Then you can update the attack squares of the pieces that actually moved.

  • Caveat: if you capture en passant you have to take into account that a square the moving pawn never occupied is now empty (the square of the captured pawn).
    – 11684
    Sep 27, 2019 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.