chess game in python code example

Example 1: generate pgn of chess game python

>>> import chess.pgn
>>>
>>> pgn = open("data/pgn/kasparov-deep-blue-1997.pgn")
>>>
>>> first_game = chess.pgn.read_game(pgn)
>>> second_game = chess.pgn.read_game(pgn)
>>>
>>> first_game.headers["Event"]
'IBM Man-Machine, New York USA'
>>>
>>> # Iterate through all moves and play them on a board.
>>> board = first_game.board()
>>> for move in first_game.mainline_moves():
...     board.push(move)
...
>>> board
Board('4r3/6P1/2p2P1k/1p6/pP2p1R1/P1B5/2P2K2/3r4 b - - 0 45')

Example 2: chess game analysis python

with engine.analysis(...) as analysis:
    for info in analysis:
        print(info.get("score"))

Example 3: chess in python

# If you haven't installed chess yet...
import os
os.system("pip install pychess")

# Else start here
import chess

# This is the start position
board = chess.Board()

# You can then play moves this way
board.push_san("e4")
board.push_san("Nc6")

# Get the fen this way...
print(board.fen())
# r1bqkbnr/pppppppp/2n5/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 1 2

# ...or print the board, ascii-style.
print(board)
# r . b q k b n r
# p p p p p p p p
# . . n . . . . .
# . . . . . . . .
# . . . . P . . .
# . . . . . . . .
# P P P P . P P P
# R N B Q K B N R