♚ Hello Chess ♛
Created by Nate Solon. Email: nate.solon@gmail.com
Get Games ⛳️
First you'll use the lichess API to download some games. Lichess is the second-biggest online chess server in the world. It's free and open source.
pip install chess python-lichess
import lichess.api
from lichess.format import SINGLE_PGN
You can download the games of any player provided you know their username. Maybe you'd like to check your own games... or a potential opponent?
Let's get the latest game from Magnus Carlsen, the World Chess Champion, whose username happens to be DrNykterstein. "Nykter" is Norwegian for "sober"... 🤔
user = "DrNykterstein" # Magnus Carlsen! You can change this to any lichess user.
Chess games are often stored in PGN format, which is just a text file with information about the game and the moves.
pgn = lichess.api.user_games(user, max=1, format=SINGLE_PGN)
print(pgn)
Experienced chess players can read the moves by sight, but it's no problem if you can't. In the next section you'll use the python-chess
library to read the game. For now, let's save our pgn.
with open("magnus.pgn", "w") as f:
f.write(pgn)
Read Games 🤓
In this section you'll use the pgn module of python-chess to open and read a pgn file.
import chess
import chess.pgn
pgn = open("magnus.pgn")
game = chess.pgn.read_game(pgn)
You can see the current board position right in the notebook!
board = game.board()
board
Nice! But this is just the starting position, not very interesting. Let's make some moves...
for i, move in enumerate(game.mainline_moves()):
board.push(move)
if i == 20:
break
board
Looks like a tense middlegame! Who's winning? If only you could ask a chess master...
Analyze Games 🧐
In this section you'll use Stockfish, the current strongest chess engine in the world, to analyze a position.
First you need to download Stockfish. If you're running this notebook on Colab, the command below will work. If running locally, you can download the appropriate version of Stockfish.
! wget https://stockfishchess.org/files/stockfish_14_linux_x64_popcnt.zip && \
unzip stockfish_14_linux_x64_popcnt.zip stockfish_14_linux_x64_popcnt/stockfish_14_x64_popcnt
import chess.engine
python-chess
has an engine module as well. How convenient! To connect to the engine, all you need is the location of the Stockfish executable.
engine = chess.engine.SimpleEngine.popen_uci("/content/stockfish_14_linux_x64_popcnt/stockfish_14_x64_popcnt")
Let's instruct the engine to analyze the current position for 1 second.
info = engine.analyse(board, chess.engine.Limit(time=1))
info
This is a little confusing, but for the moment all you need is the score. This represents who's winning in the current position.
info['score'].pov(chess.WHITE)
Cp means centipawns. 100 centipawns = 1 pawn. So according to the engine, from White's pov (point of view) the evaluation is +68. White is ahead by a little less than a pawn. It seems Magnus has the upper hand.