Tuesday, October 16, 2007

How to parse a chess PGN file using JRuby and Chesspresso

I have a lot of chess PGN files with many chess games inside. What I want, is to have some way of filtering this collection e.g. by player names or by opening. Ideally, I'd like to use either Ruby or Python to do that.

My first approach was to find a pure Ruby library and use it. Unfortunately, I couldn't find any good one. No luck with any Python module either. I didn't want to use .Net platform in this case, but I did a quick google search with no good results...

The last hope was the Java platform. This time I was lucky and found Chesspresso. A quick test proved that the library is mature, exposes a very nice API and is actually very fast.
Even though I have a lot of experience with Java language, I don't fancy implementing my projects in statically typed languages. I find Ruby or Python much more readable and testable.

My choice is now clear - JRuby.
include Java
require 'Chesspresso-lib'
include_class 'chesspresso.pgn.PGNReader'

pgn_reader = PGNReader.new 'twic675.pgn'

while game = pgn_reader.parse_game do
if game.white.include?('Shirov')
puts game
  • The output in my case is:
Shirov,A - Naiditsch,A 1/2-1/2 (2007.10.08)
Shirov,A - Almasi,Z 1-0 (2007.10.09)

more funny pictures

No comments: