Daan Noordenbos

PGN parser

Since I want to post analysis of my chess games on this blog I needed to find a way of displaying chess games. I could have embedded a lichess game to display my games, but as a small and fun project I decided to create my own parser which takes in a chess game and has as output a markdown file. Chess games are most commonly stored in the .pgn file format. The PGN format is a text-based file format which records moves, comments, variations and game details.

The downside of PGN files is that they are designed to be human readable which makes reading them for a computer very bothersome. Therefore, I used the Python chess library to load in the pgn file and to deal with the chess logic. After loading in the game the parser will traverse the game tree of the game and build up the output text. The output it generates has a few neat features:

  1. Displays game details in headers.
  2. Moves in variations use unicode symbols as pieces making it language agnostic and easier to read.
  3. The mainline is bold.
  4. Odd variations depths are italic to distinguish variations and their sub-variations,
  5. Adding [D] in the pgn file will result in a diagram being added in the output.
  6. Support of (basic) numeric annotation glyphs.

The result would be something like the following, which I hope you will agree with looks quite nice.

Edwin de Jonge (1716) - Daan Noordenbos (2107)

NOSBO (3), 2022.03.01

1.d4 ♘f6 2.c4 g6 3.♘f3 ♗g7 4.♘c3 O-O 5.e4 d6 6.♗e2 ♘bd7 The sideline that I often use against weaker players to avoid the exchange variation of the Kings Indian Defence 7.O-O e5 8.dxe5 dxe5 9.♕c2 ♘h5

9…c6 This move is the computer choice. However it does weaking d6 and since white is still very flexible he can often play Nf3-d2-c4-d6 10.g3 ♘c5!? Trying to quickly take the d4 square 11.♗e3

11.♖d1 ♕e8 12.♘d5 ♘e6 13.♘g5 This is annoying ♘xg5 14.♗xg5 f6 15.♗e3 ♖f7 16.♗xh5

16.g4 ♘f4 17.♘xf4 exf4 18.♗xf4 And white has a clear advantage 16…gxh5 During the game I thought that this would be fine 11…♘e6 12.♖fd1 ♘d4? Based on a miscalculation

12…♕e8 White has an edge here but black can still attack with f7-f5 13.♘xd4 exd4 14.♘b5

14.c5 This was critical, but I thought that this would be fine. c6 15.♗xh5 gxh5 16.♘e2 This is rather strong ♗g4 This does not actually do that much 17.♗xd4 ♗xe2 18.♗xg7 ♗xd1 19.♖xd1+- 14…c5 15.♗xh5 gxh5 16.♗f4 ♗g4 17.♖e1 This is the line I wanted when I played Nd4, I thought that a knight on d6 would not be that active. however I missed that Nb5-c7-d5 plants the knight firmly on d5 ♕d7 18.♕d3

18.♘c7 d3 19.♕d2 f5 This was my intention 20.♘xa8

20.exf5+- 20…fxe4 21.♖xe4 ♗f3 22.♖e3 ♖xf4 23.♖xd3 ♖d4 24.♖xd4 cxd4 25.♖e1 And white can actually defend f5

18…♖ae8! 19.♗d6 a6 20.♗xf8 ♖xf8 21.♘a3 f5 And the inactive knight is decisive 19.f3 fxe4 20.fxe4 a6 This is a nasty suprise, now it is lost 21.♘a3 h4 22.♘b1 ♗h3 23.♘d2 ♖xf4 A cute finish 0-1