### Build and install libgtb shared library Source: https://github.com/niklasf/python-chess/blob/master/docs/gaviota.md Commands to clone, compile, and install the Gaviota-Tablebases shared library for faster probing. ```shell git clone https://github.com/michiguel/Gaviota-Tablebases.git cd Gaviota-Tablebases make sudo make install ``` -------------------------------- ### Install python-chess Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Use pip to install the python-chess library. Requires Python 3.8 or newer. ```default pip install chess ``` -------------------------------- ### Basic Chess Board Operations Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Demonstrates initializing a chess board, checking legal moves, and making moves using Standard Algebraic Notation (SAN). Includes an example of reaching a checkmate state. ```python >>> import chess >>> board = chess.Board() >>> board.legal_moves >>> 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') ``` -------------------------------- ### Communicate with UCI/XBoard Engines Source: https://github.com/niklasf/python-chess/blob/master/README.rst Use chess.engine.SimpleEngine.popen_uci() to start an engine. The play() method returns a PlayResult object with the best move and other information. Remember to quit the engine. ```python >>> 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 >>> engine.quit() ``` -------------------------------- ### Initialize a Chess960 board Source: https://github.com/niklasf/python-chess/blob/master/docs/variant.md Create a standard board with Chess960 rules enabled. ```pycon >>> chess.Board(chess960=True) Board('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1', chess960=True) ``` -------------------------------- ### Access variant metadata Source: https://github.com/niklasf/python-chess/blob/master/docs/variant.md Retrieve variant-specific information such as UCI identifiers and starting FEN strings. ```pycon >>> # General information about the variants. >>> type(board).uci_variant 'giveaway' >>> type(board).xboard_variant 'giveaway' >>> type(board).starting_fen 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1' ``` -------------------------------- ### Initialize a variant board Source: https://github.com/niklasf/python-chess/blob/master/docs/variant.md Create a new board instance for a specific chess variant. ```pycon >>> import chess.variant >>> >>> board = chess.variant.GiveawayBoard() ``` -------------------------------- ### Parse and Create SAN Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Convert moves to Standard Algebraic Notation and vice versa. ```python >>> 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' ``` -------------------------------- ### Connect to a remote chess engine using AsyncSSH Source: https://github.com/niklasf/python-chess/blob/master/docs/engine.md Establishes a connection to a remote host and initializes a UCI engine process. Requires the asyncssh library and a valid engine path on the remote machine. ```python import asyncio import asyncssh import chess import chess.engine async def main() -> None: async with asyncssh.connect("localhost") as conn: channel, engine = await conn.create_subprocess(chess.engine.UciProtocol, "/usr/bin/stockfish") await engine.initialize() # Play, analyse, ... await engine.ping() asyncio.run(main()) ``` -------------------------------- ### Render Board in Notebook Source: https://github.com/niklasf/python-chess/blob/master/README.rst Displays the current board state in an IPython or Jupyter environment. ```python >>> board # doctest: +SKIP ``` -------------------------------- ### Play chess engine games Source: https://github.com/niklasf/python-chess/blob/master/docs/engine.md Demonstrates how to have a chess engine play against itself using either a synchronous or asynchronous interface. ```python import chess import chess.engine engine = chess.engine.SimpleEngine.popen_uci(r"C:\Users\xxxxx\Downloads\stockfish_14_win_x64\stockfish_14_win_x64_avx2.exe") board = chess.Board() while not board.is_game_over(): result = engine.play(board, chess.engine.Limit(time=0.1)) board.push(result.move) engine.quit() ``` ```python import asyncio import chess import chess.engine async def main() -> None: transport, engine = await chess.engine.popen_uci(r"C:\Users\xxxxx\Downloads\stockfish_14_win_x64\stockfish_14_win_x64_avx2.exe") board = chess.Board() while not board.is_game_over(): result = await engine.play(board, chess.engine.Limit(time=0.1)) board.push(result.move) await engine.quit() asyncio.run(main()) ``` -------------------------------- ### Play a move with a UCI engine in Python Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Initializes a UCI engine process, sets a specific board position, and requests a move within a time limit. ```python >>> 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) >>> engine.quit() ``` -------------------------------- ### Read Polyglot Opening Books Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Query opening books for recommended moves. ```python >>> 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() ``` -------------------------------- ### Make and Unmake Moves Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Use push to execute a move and pop to revert the last move. ```python >>> Nf3 = chess.Move.from_uci("g1f3") >>> board.push(Nf3) # Make the move >>> board.pop() # Unmake the last move Move.from_uci('g1f3') ``` -------------------------------- ### Print ASCII Board Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Visualize the current board state using ASCII characters. ```python >>> 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 ``` -------------------------------- ### Parse and Create EPD Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Work with Extended Position Description strings. ```python >>> 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 ``` -------------------------------- ### Read and Write PGNs Source: https://github.com/niklasf/python-chess/blob/master/README.rst Use chess.pgn.read_game() to read a PGN file. Game objects have headers, comments, NAGs, and a mainline. Access headers via dictionary-like access. ```python >>> 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 >>> first_game.headers["Result"] '0-1' ``` -------------------------------- ### Read and Write PGN Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Process Portable Game Notation files including headers and variations. ```python >>> 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() >>> first_game.headers["Result"] '0-1' ``` -------------------------------- ### Enable engine logging Source: https://github.com/niklasf/python-chess/blob/master/docs/engine.md Configures the standard logging module to capture engine communication for debugging. ```python import logging # Enable debug logging. logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Configure engine options Source: https://github.com/niklasf/python-chess/blob/master/docs/engine.md Retrieves and modifies engine-specific configuration parameters. ```python import chess.engine engine = chess.engine.SimpleEngine.popen_uci("/usr/bin/stockfish") # Check available options. engine.options["Hash"] # Option(name='Hash', type='spin', default=16, min=1, max=131072, var=[]) # Set an option. engine.configure({"Hash": 32}) # [...] ``` ```python import asyncio import chess.engine async def main() -> None: transport, engine = await chess.engine.popen_uci("/usr/bin/stockfish") # Check available options. print(engine.options["Hash"]) # Option(name='Hash', type='spin', default=16, min=1, max=131072, var=[]) # Set an option. await engine.configure({"Hash": 32}) # [...] asyncio.run(main()) ``` -------------------------------- ### Write Game to PGN Format Source: https://github.com/niklasf/python-chess/blob/master/docs/pgn.md Exports a game object to PGN format, including headers, comments, and variations. Ensure games in files are separated by blank lines. ```python >>> import chess >>> import chess.pgn >>> >>> game = chess.pgn.Game() >>> game.headers["Event"] = "Example" >>> node = game.add_variation(chess.Move.from_uci("e2e4")) >>> node = node.add_variation(chess.Move.from_uci("e7e5")) >>> node.comment = "Comment" >>> >>> print(game) [Event "Example"] [Site "?"] [Date "????.??.??"] [Round "?"] [White "?"] [Black "?"] [Result "*"] 1. e4 e5 { Comment } * ``` ```python >>> print(game, file=open("/dev/null", "w"), end="\n\n") ``` -------------------------------- ### Parse and Create FEN Source: https://github.com/niklasf/python-chess/blob/master/docs/index.md Handle FEN and Shredder FEN strings for board state serialization. ```python >>> 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') ``` -------------------------------- ### Open Syzygy tablebases for variants Source: https://github.com/niklasf/python-chess/blob/master/docs/variant.md Load Syzygy tablebases specifically for supported variants like Atomic chess. ```pycon >>> import chess.syzygy >>> import chess.variant >>> >>> tables = chess.syzygy.open_tablebase("data/syzygy", VariantBoard=chess.variant.AtomicBoard) ``` -------------------------------- ### Play variant games with UCI engines Source: https://github.com/niklasf/python-chess/blob/master/docs/variant.md Use a UCI engine to play moves on a variant board. ```pycon >>> import chess.engine >>> >>> engine = chess.engine.SimpleEngine.popen_uci("stockfish-mv") >>> >>> board = chess.variant.RacingKingsBoard() >>> result = engine.play(board, chess.engine.Limit(time=1.0)) ```