M2M Day 348: I’ve finally written a few lines of functional code

Max Deutsch
2 min readOct 15, 2017

--

This post is part of Month to Master, a 12-month accelerated learning project. For October, my goal is to defeat world champion Magnus Carlsen at a game of chess.

Yesterday, I laid out my four-step plan for building a human-executable chess algorithm.

Today, I started working on the first step: Creating the dataset.

In particular, I need to take the large corpus of chess games in Portable Game Notation (PGN) and programmatically analyze them and convert them into the correct form, featuring a modified bitboard input and a numerical evaluation output.

Luckily, there’s an amazing library on Github called Python Chess that makes this a lot easier.

As explained on Github, Python Chess is “a pure Python chess library with move generation and validation, PGN parsing and writing, Polyglot opening book reading, Gaviota tablebase probing, Syzygy tablebase probing and UCI engine communication”.

The parts I’m particular interested in are…

  1. PGN parsing, which allows my Python program to read any chess game in the PGN format.
  2. UCI (Universal Chess Interface) engine communication, which lets me directly interface with and leverage the power of the Stockfish chess engine for analysis purposes.

The documentation for Python Chess is also extremely good and filled with plenty of examples.

Today, using the Python Chess library, I was able to write a small program that can 1. Parse a PGN chess game, 2. Numerically evaluate each position, and 3. Print out each move, a visualization of the board after each move, and the evaluation (in centipawns) corresponding to each board position.

import chess
import chess.pgn
import chess.uci
board = chess.Board()
pgn = open("data/game1.pgn")
game = chess.pgn.read_game(pgn)
engine = chess.uci.popen_engine("stockfish")
engine.uci()
info_handler = chess.uci.InfoHandler()
engine.info_handlers.append(info_handler)
for move in game.main_line():engine.position(board)
engine.go(movetime=2000)
evaluation = info_handler.info["score"][1].cp
if not board.turn:
evaluation *= -1

print move
print evaluation
board.push_uci(move.uci())
print board

Now, I just need to convert this data into the correct form, so it can be used by my deep learning model (that I’ve yet to build) for the purposes of training / generating the algorithm.

I’m making progress…

Read the next post. Read the previous post.

Max Deutsch is an obsessive learner, product builder, and guinea pig for Month to Master.

If you want to follow along with Max’s year-long accelerated learning project, make sure to follow this Medium account.

--

--