• Stars
    star
    2,157
  • Rank 21,378 (Top 0.5 %)
  • Language
    Python
  • License
    GNU General Publi...
  • Created about 12 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A chess library for Python, with move generation and validation, PGN parsing and writing, Polyglot opening book reading, Gaviota tablebase probing, Syzygy tablebase probing, and UCI/XBoard engine communication

python-chess: a chess library for Python

Test status PyPI package Docs Chat on Gitter

Introduction

python-chess is a chess library for Python, with move generation, move validation, and support for common formats. This is the Scholar's mate in python-chess:

>>> import chess

>>> board = chess.Board()

>>> board.legal_moves  # doctest: +ELLIPSIS
<LegalMoveGenerator at ... (Nh3, Nf3, Nc3, Na3, h3, g3, f3, e3, d3, c3, ...)>
>>> chess.Move.from_uci("a8a1") in board.legal_moves
False

>>> board.push_san("e4")
Move.from_uci('e2e4')
>>> board.push_san("e5")
Move.from_uci('e7e5')
>>> board.push_san("Qh5")
Move.from_uci('d1h5')
>>> board.push_san("Nc6")
Move.from_uci('b8c6')
>>> board.push_san("Bc4")
Move.from_uci('f1c4')
>>> board.push_san("Nf6")
Move.from_uci('g8f6')
>>> board.push_san("Qxf7")
Move.from_uci('h5f7')

>>> board.is_checkmate()
True

>>> board
Board('r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4')

Installing

Requires Python 3.7+. Download and install the latest release:

pip install chess

Documentation

Features

  • Includes mypy typings.

  • IPython/Jupyter Notebook integration. SVG rendering docs.

    >>> board  # doctest: +SKIP
    r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR
  • Chess variants: Standard, Chess960, Suicide, Giveaway, Atomic, King of the Hill, Racing Kings, Horde, Three-check, Crazyhouse. Variant docs.

  • Make and unmake moves.

    >>> Nf3 = chess.Move.from_uci("g1f3")
    >>> board.push(Nf3)  # Make the move
    
    >>> board.pop()  # Unmake the last move
    Move.from_uci('g1f3')
  • Show a simple ASCII board.

    >>> board = chess.Board("r1bqkb1r/pppp1Qpp/2n2n2/4p3/2B1P3/8/PPPP1PPP/RNB1K1NR b KQkq - 0 4")
    >>> print(board)
    r . b q k b . r
    p p p p . Q p p
    . . n . . n . .
    . . . . p . . .
    . . B . P . . .
    . . . . . . . .
    P P P P . P P P
    R N B . K . N R
  • Detects checkmates, stalemates and draws by insufficient material.

    >>> board.is_stalemate()
    False
    >>> board.is_insufficient_material()
    False
    >>> board.outcome()
    Outcome(termination=<Termination.CHECKMATE: 1>, winner=True)
  • Detects repetitions. Has a half-move clock.

    >>> board.can_claim_threefold_repetition()
    False
    >>> board.halfmove_clock
    0
    >>> board.can_claim_fifty_moves()
    False
    >>> board.can_claim_draw()
    False

    With the new rules from July 2014, a game ends as a draw (even without a claim) once a fivefold repetition occurs or if there are 75 moves without a pawn push or capture. Other ways of ending a game take precedence.

    >>> board.is_fivefold_repetition()
    False
    >>> board.is_seventyfive_moves()
    False
  • Detects checks and attacks.

    >>> board.is_check()
    True
    >>> board.is_attacked_by(chess.WHITE, chess.E8)
    True
    
    >>> attackers = board.attackers(chess.WHITE, chess.F3)
    >>> attackers
    SquareSet(0x0000_0000_0000_4040)
    >>> chess.G2 in attackers
    True
    >>> print(attackers)
    . . . . . . . .
    . . . . . . . .
    . . . . . . . .
    . . . . . . . .
    . . . . . . . .
    . . . . . . . .
    . . . . . . 1 .
    . . . . . . 1 .
  • Parses and creates SAN representation of moves.

    >>> board = chess.Board()
    >>> board.san(chess.Move(chess.E2, chess.E4))
    'e4'
    >>> board.parse_san('Nf3')
    Move.from_uci('g1f3')
    >>> board.variation_san([chess.Move.from_uci(m) for m in ["e2e4", "e7e5", "g1f3"]])
    '1. e4 e5 2. Nf3'
  • Parses and creates FENs, extended FENs and Shredder FENs.

    >>> board.fen()
    'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
    >>> board.shredder_fen()
    'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w HAha - 0 1'
    >>> board = chess.Board("8/8/8/2k5/4K3/8/8/8 w - - 4 45")
    >>> board.piece_at(chess.C5)
    Piece.from_symbol('k')
  • Parses and creates EPDs.

    >>> board = chess.Board()
    >>> board.epd(bm=board.parse_uci("d2d4"))
    'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - bm d4;'
    
    >>> ops = board.set_epd("1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - bm Qd1+; id \"BK.01\";")
    >>> ops == {'bm': [chess.Move.from_uci('d6d1')], 'id': 'BK.01'}
    True
  • Detects absolute pins and their directions.

  • Reads Polyglot opening books. Docs.

    >>> import chess.polyglot
    
    >>> book = chess.polyglot.open_reader("data/polyglot/performance.bin")
    
    >>> board = chess.Board()
    >>> main_entry = book.find(board)
    >>> main_entry.move
    Move.from_uci('e2e4')
    >>> main_entry.weight
    1
    
    >>> book.close()
  • Reads and writes PGNs. Supports headers, comments, NAGs and a tree of variations. Docs.

    >>> import chess.pgn
    
    >>> with open("data/pgn/molinari-bordais-1979.pgn") as pgn:
    ...     first_game = chess.pgn.read_game(pgn)
    
    >>> first_game.headers["White"]
    'Molinari'
    >>> first_game.headers["Black"]
    'Bordais'
    
    >>> first_game.mainline()  # doctest: +ELLIPSIS
    <Mainline at ... (1. e4 c5 2. c4 Nc6 3. Ne2 Nf6 4. Nbc3 Nb4 5. g3 Nd3#)>
    
    >>> first_game.headers["Result"]
    '0-1'
  • Probe Gaviota endgame tablebases (DTM, WDL). Docs.

  • Probe Syzygy endgame tablebases (DTZ, WDL). Docs.

    >>> import chess.syzygy
    
    >>> tablebase = chess.syzygy.open_tablebase("data/syzygy/regular")
    
    >>> # Black to move is losing in 53 half moves (distance to zero) in this
    >>> # KNBvK endgame.
    >>> board = chess.Board("8/2K5/4B3/3N4/8/8/4k3/8 b - - 0 1")
    >>> tablebase.probe_dtz(board)
    -53
    
    >>> tablebase.close()
  • Communicate with UCI/XBoard engines. Based on asyncio. Docs.

    >>> import chess.engine
    
    >>> engine = chess.engine.SimpleEngine.popen_uci("stockfish")
    
    >>> board = chess.Board("1k1r4/pp1b1R2/3q2pp/4p3/2B5/4Q3/PPP2B2/2K5 b - - 0 1")
    >>> limit = chess.engine.Limit(time=2.0)
    >>> engine.play(board, limit)  # doctest: +ELLIPSIS
    <PlayResult at ... (move=d6d1, ponder=c1d1, info={...}, draw_offered=False, resigned=False)>
    
    >>> engine.quit()

Selected projects

If you like, share interesting things you are using python-chess for, for example:

https://github.com/niklasf/python-chess/blob/master/docs/images/syzygy.png?raw=true

https://syzygy-tables.info/

A website to probe Syzygy endgame tablebases

https://github.com/niklasf/python-chess/blob/master/docs/images/maia.png?raw=true

https://maiachess.com/

A human-like neural network chess engine

https://github.com/niklasf/python-chess/blob/master/docs/images/clente-chess.png?raw=true

clente/chess

Oppinionated wrapper to use python-chess from the R programming language

https://github.com/niklasf/python-chess/blob/master/docs/images/crazyara.png?raw=true

https://crazyara.org/

Deep learning for Crazyhouse

https://github.com/niklasf/python-chess/blob/master/docs/images/jcchess.png?raw=true

http://johncheetham.com

A GUI to play against UCI chess engines

https://github.com/niklasf/python-chess/blob/master/docs/images/pettingzoo.png?raw=true

https://pettingzoo.farama.org

A multi-agent reinforcement learning environment

https://github.com/niklasf/python-chess/blob/master/docs/images/cli-chess.png?raw=true

cli-chess

A highly customizable way to play chess in your terminal

Acknowledgements

Thanks to the Stockfish authors and thanks to Sam Tannous for publishing his approach to avoid rotated bitboards with direct lookup (PDF) alongside his GPL2+ engine Shatranj. Some move generation ideas are taken from these sources.

Thanks to Ronald de Man for his Syzygy endgame tablebases. The probing code in python-chess is very directly ported from his C probing code.

Thanks to Kristian Glass for transferring the namespace chess on PyPI.

License

python-chess is licensed under the GPL 3 (or any later version at your option). Check out LICENSE.txt for the full text.

More Repositories

1

shakmaty

A Rust library for chess and chess variant rules and operations
Rust
179
star
2

chessops

Chess and chess variant rules and operations in TypeScript
TypeScript
86
star
3

rust-chessground

An experimental chessboard widget for Relm/GTK
Rust
63
star
4

web-boardimage

An HTTP service that renders chess board images
Python
61
star
5

rust-pgn-reader

Fast non-allocating and streaming reader for chess games in PGN notation
Rust
60
star
6

syzygy-tables.info

User interface and public API for probing Syzygy endgame tablebases
Python
58
star
7

node-irc-server

Implementation of the IRC server protocol using node.js
JavaScript
56
star
8

python-agentspeak

A Python-based interpreter for the agent-oriented programming language JASON
Python
48
star
9

build-raspbian-image

Builds a minimal Raspbian Stretch image
Shell
39
star
10

stockfish.pexe

The strong open source chess engine Stockfish as a PNaCl module
C++
23
star
11

rust-huffman-compress

A Rust library for Huffman compression given a propability distribution over arbitrary symbols
Rust
23
star
12

indexed.py

A Python dictionary that is indexed by insertion order
Python
20
star
13

shakmaty-syzygy

A Rust library to probe Syzygy endgame tablebases
Rust
17
star
14

python-asyncdgt

Communicate asynchronously with DGT boards
Python
15
star
15

double-checked-cell

A thread-safe lazily initialized cell using double-checked locking.
Rust
12
star
16

magics

Finding magic factors for bitboard based move generation
C
12
star
17

lila-websocket

Experimental WebSocket server for lichess.org - superceded by https://github.com/ornicar/lila-ws
Rust
10
star
18

python-tinyhtml

A tiny library to safely render compact HTML5 from Python expressions.
Python
10
star
19

git-rebase-patch

Rebase patches that no longer apply to HEAD
Shell
9
star
20

rust-btoi

Parse integers directly from ASCII byte slices
Rust
7
star
21

lila-openingexplorer3

Opening explorer for lichess.org
Rust
5
star
22

ip2proxy-rust

Rust library to query IP2Proxy BIN Data files
Rust
3
star
23

tbserve

Syzygy tablebase server
C++
3
star
24

fishnet-assets

Precompiled Stockfish binaries for fishnet
3
star
25

antichess-tree-server

HTTP API and C library to query Watkins antichess proof tables: 1. e3 is winning for White
C
2
star
26

rust-gaviota-sys

Low level Rust bindings for libgtb, a library for Gaviota tablebase probing
Rust
2
star
27

cloudflare-camo

A Cloudflare worker to proxy images for privacy, to avoid mixed content, and to add headers
TypeScript
2
star
28

media_feeds

Enable mapping imported sources to media fields.
PHP
1
star
29

chessclock

Various clock types for two player games
C++
1
star
30

lichess-stagebot

A bot waiting for deploy commands in the Slack channel
Python
1
star
31

project_git_default_branch

Let drupal.org module maintainers set the default branch for their repositories.
PHP
1
star
32

versioncontrol_project

Drupal Version Control API Project integration module
PHP
1
star
33

display-kiosk

Display a website in a stripped down kiosk
C++
1
star
34

field_copy

PHP
1
star
35

flexibledate

A CCK field for drupal that can contain both full dates and quarters.
PHP
1
star
36

jumpnevolve

Yet another jump'n'run game
Java
1
star
37

android-barcode-scanner

Use an android device as a wireless barcode scanner
C++
1
star
38

lightbox2_media

Allows using Lightbox2 for displaying images in Media fields.
PHP
1
star
39

field_label_plurals

A Drupal module that allows you to use different field labels for singular and plural, depending on the number of field values.
PHP
1
star
40

taxonomy_icon

A drupal module that allows the user to show taxonomy term references as icons.
PHP
1
star
41

fishnet-tuning

Experiments to find good parameters for reproducible Stockfish analysis
Python
1
star
42

github-showcases

A dataset of all repositories showcased on GitHub
Python
1
star
43

media

Fork of the Drupal Media module for #1349058
PHP
1
star
44

birthdays

The Drupal Birthdays module
PHP
1
star
45

pheres

Tools to experiment with the AgentSpeak programming language
Rust
1
star
46

cig-lectures

Seat reservations for CIG lectures at TU Clausthal
Python
1
star