I am trying to figure out an algorithm to extract the number of each piece that both black and white have from a PGN file.

Right now I have all of the moves tokenized(i.e. c("e4", "d6", "Nc3", "f5", "exf5", "Bxf5", "Qh5", "g6"...), but I'm not sure where to proceed next. So far I know that identifying the "x" characters is necessary, but I am not sure what to do as the notation only identifies the capture square, and not what type of piece is captured.

  • 2
    At what moment do you want the piece count? The start of the game, the end, or some arbitrary point in the middle? Also, the 'x' character is not always present in some PGN input; a more robust method to track pieces would be to just make each move in some internal board representation.
    – Remellion
    Commented Jan 7, 2020 at 5:25

1 Answer 1


You'd have some data structure, such as a 2-D 8x8 array, storing the current piece in each square of the board. Everytime you read a new move, update the array appropriately. Then, when you see a capture like "exf5", check what piece is stored in the "f5" square of the array.

You'll have to be careful with en passant captures. For example, in the case of 1.e4 c5 2.e5 d5 3.exd6, you should be checking the element in the array 1 row above (for d5). In order to detect when an en passant has occurred, see if a pawn captured on to an empty square. For example, 3.exd6 is White's e5-pawn capturing on to the empty d6-square, so it must be en passant.

  • The PGN specification was originally part of the SAN kit, which did much, perhaps all, of this: listing legal moves, making moves, etc. There is a SANKit project at SourceForge, which seems to be closely related. It might be useful.
    – user24765
    Commented Nov 30, 2020 at 8:16

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.