Core

Colors

Constants for the side to move or the color of a piece.

chess.WHITE = True
chess.BLACK = False

You can get the opposite color using not color.

Piece types

chess.PAWN = 1
chess.KNIGHT = 2
chess.BISHOP = 3
chess.ROOK = 4
chess.QUEEN = 5
chess.KING = 6

Squares

chess.A1 = 0
chess.B1 = 1

and so on to

chess.G8 = 62
chess.H8 = 63
chess.SQUARES = [chess.A1, chess.B1, ..., chess.G8, chess.H8]
chess.SQUARE_NAMES = ['a1', 'b1', ..., 'g8', 'h8']
chess.FILE_NAMES = ['a', 'b', ..., 'g', 'h']
chess.RANK_NAMES = ['1', '2', ..., '7', '8']
chess.square(file_index, rank_index)

Gets a square number by file and rank index.

chess.square_file(square)

Gets the file index of the square where 0 is the a file.

chess.square_rank(square)

Gets the rank index of the square where 0 is the first rank.

chess.square_distance(a, b)

Gets the distance (i.e., the number of king steps) from square a to b.

chess.square_mirror(square)

Mirrors the square vertically.

Pieces

class chess.Piece(piece_type, color)

A piece with type and color.

piece_type

The piece type.

color

The piece color.

symbol()

Gets the symbol P, N, B, R, Q or K for white pieces or the lower-case variants for the black pieces.

unicode_symbol(invert_color=False)

Gets the Unicode character for the piece.

classmethod from_symbol(symbol)

Creates a Piece instance from a piece symbol.

Raises:ValueError if the symbol is invalid.

Moves

class chess.Move(from_square, to_square, promotion=None, drop=None)

Represents a move from a square to a square and possibly the promotion piece type.

Drops and null moves are supported.

from_square

The source square.

to_square

The target square.

promotion

The promotion piece type or Ǹone.

drop

The drop piece type or None.

uci()

Gets an UCI string for the move.

For example, a move from a7 to a8 would be a7a8 or a7a8q (if the latter is a promotion to a queen).

The UCI representation of a null move is 0000.

classmethod from_uci(uci)

Parses an UCI string.

Raises:ValueError if the UCI string is invalid.
classmethod null()

Gets a null move.

A null move just passes the turn to the other side (and possibly forfeits en passant capturing). Null moves evaluate to False in boolean contexts.

>>> import chess
>>>
>>> bool(chess.Move.null())
False

Board

chess.STARTING_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

The FEN for the standard chess starting position.

chess.STARTING_BOARD_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR'

The board part of the FEN for the standard chess starting position.

class chess.Board(fen='rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1', chess960=False)

A BaseBoard and additional information representing a chess position.

Provides move generation, validation, parsing, attack generation, game end detection, move counters and the capability to make and unmake moves.

The board is initialized to the standard chess starting position, unless otherwise specified in the optional fen argument. If fen is None, an empty board is created.

Optionally supports chess960. In Chess960 castling moves are encoded by a king move to the corresponding rook square. Use chess.Board.from_chess960_pos() to create a board with one of the Chess960 starting positions.

It’s safe to set turn, castling_rights, ep_square, halfmove_clock and fullmove_number directly.

turn

The side to move.

castling_rights

Bitmask of the rooks with castling rights.

To test for specific squares:

>>> import chess
>>>
>>> board = chess.Board()
>>> bool(board.castling_rights & chess.BB_H1) # White can castle with the h1 rook
True

To add a specific square:

>>> board.castling_rights |= chess.BB_A1

Use set_castling_fen() to set multiple castling rights. Also see has_castling_rights(), has_kingside_castling_rights(), has_queenside_castling_rights(), has_chess960_castling_rights(), clean_castling_rights().

ep_square

The potential en passant square on the third or sixth rank or None.

Use has_legal_en_passant() to test if en passant capturing would actually be possible on the next move.

fullmove_number

Counts move pairs. Starts at 1 and is incremented after every move of the black side.

halfmove_clock

The number of half-moves since the last capture or pawn move.

promoted

A bitmask of pieces that have been promoted.

chess960

Whether the board is in Chess960 mode. In Chess960 castling moves are represented as king moves to the corresponding rook square.

legal_moves = LegalMoveGenerator(self)

A dynamic list of legal moves.

>>> import chess
>>>
>>> board = chess.Board()
>>> board.legal_moves.count()
20
>>> bool(board.legal_moves)
True
>>> move = chess.Move.from_uci("g1f3")
>>> move in board.legal_moves
True

Wraps generate_legal_moves() and is_legal().

A dynamic list of pseudo legal moves, much like the legal move list.

Pseudo legal moves might leave or put the king in check, but are otherwise valid. Null moves are not pseudo legal. Castling moves are only included if they are completely legal.

Wraps generate_pseudo_legal_moves() and is_pseudo_legal().

move_stack

The move stack. Use Board.push(), Board.pop(), Board.peek() and Board.clear_stack() for manipulation.

reset()

Restores the starting position.

clear()

Clears the board.

Resets move stacks and move counters. The side to move is white. There are no rooks or kings, so castling rights are removed.

In order to be in a valid status() at least kings need to be put on the board.

clear_board()

Clears the board.

clear_stack()

Clears the move stack.

remove_piece_at(square)

Removes the piece from the given square. Returns the Piece or None if the square was already empty.

set_piece_at(square, piece, promoted=False)

Sets a piece at the given square.

An existing piece is replaced. Setting piece to None is equivalent to remove_piece_at().

is_check()

Returns if the current side to move is in check.

is_into_check(move)

Checks if the given move would leave the king in check or put it into check. The move must be at least pseudo legal.

was_into_check()

Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move.

is_variant_end()

Checks if the game is over due to a special variant end condition.

Note, for example, that stalemate is not considered a variant-specific end condition (this method will return False), yet it can have a special result in suicide chess (any of is_variant_loss(), is_variant_win(), is_variant_draw() might return True).

is_variant_loss()

Checks if a special variant-specific loss condition is fulfilled.

is_variant_win()

Checks if a special variant-specific win condition is fulfilled.

is_variant_draw()

Checks if a special variant-specific drawing condition is fulfilled.

is_game_over(claim_draw=False)

Checks if the game is over due to checkmate, stalemate, insufficient material, the seventyfive-move rule, fivefold repetition or a variant end condition.

The game is not considered to be over by threefold repetition or the fifty-move rule, unless claim_draw is given.

result(claim_draw=False)

Gets the game result.

1-0, 0-1 or 1/2-1/2 if the game is over. Otherwise, the result is undetermined: *.

is_checkmate()

Checks if the current position is a checkmate.

is_stalemate()

Checks if the current position is a stalemate.

is_insufficient_material()

Checks for a draw due to insufficient mating material.

is_seventyfive_moves()

Since the 1st of July 2014, a game is automatically drawn (without a claim by one of the players) if the half-move clock since a capture or pawn move is equal to or grather than 150. Other means to end a game take precedence.

is_fivefold_repetition()

Since the 1st of July 2014 a game is automatically drawn (without a claim by one of the players) if a position occurs for the fifth time on consecutive alternating moves.

can_claim_draw()

Checks if the side to move can claim a draw by the fifty-move rule or by threefold repetition.

can_claim_fifty_moves()

Draw by the fifty-move rule can be claimed once the clock of halfmoves since the last capture or pawn move becomes equal or greater to 100 and the side to move still has a legal move they can make.

can_claim_threefold_repetition()

Draw by threefold repetition can be claimed if the position on the board occured for the third time or if such a repetition is reached with one of the possible legal moves.

push(move)

Updates the position with the given move and puts it onto the move stack.

>>> import chess
>>>
>>> board = chess.Board()
>>>
>>> Nf3 = chess.Move.from_uci("g1f3")
>>> board.push(Nf3)  # Make the move
>>> board.pop()  # Unmake the last move
Move.from_uci('g1f3')

Null moves just increment the move counters, switch turns and forfeit en passant capturing.

Warning:Moves are not checked for legality.
pop()

Restores the previous position and returns the last move from the stack.

Raises:IndexError if the stack is empty.
peek()

Gets the last move from the move stack.

Raises:IndexError if the move stack is empty.

Checks if there is a pseudo-legal en passant capture.

Checks if there is a legal en passant capture.

fen(shredder=False, en_passant='legal', promoted=None)

Gets a FEN representation of the position.

A FEN string (e.g., rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1) consists of the position part board_fen(), the turn, the castling part (castling_rights), the en passant square (ep_square), the halfmove_clock and the fullmove_number.

Parameters:
  • shredder – Use castling_shredder_fen() and encode castling rights by the file of the rook (like HAha) instead of the default castling_xfen() (like KQkq).
  • en_passant – By default, only fully legal en passant squares are included (has_legal_en_passant()). Pass fen to strictly follow the FEN specification (always include the en passant square after a double pawn move) or xfen to follow the X-FEN specification (has_pseudo_legal_en_passant()).
  • promoted – Mark promoted pieces like Q~. By default, this is only enabled in chess variants where this is relevant.
set_fen(fen)

Parses a FEN and sets the position from it.

Raises:ValueError if the FEN string is invalid.
set_castling_fen(castling_fen)

Sets castling rights from a string in FEN notation like Qqk.

Raises:ValueError if the castling FEN is syntactically invalid.
set_board_fen(fen)

Parses a FEN and sets the board from it.

Raises:ValueError if the FEN string is invalid.
set_piece_map(pieces)

Sets up the board from a dictionary of pieces by square index.

set_chess960_pos(sharnagl)

Sets up a Chess960 starting position given its index between 0 and 959. Also see from_chess960_pos().

chess960_pos(ignore_turn=False, ignore_castling=False, ignore_counters=True)

Gets the Chess960 starting position index between 0 and 956 or None if the current position is not a Chess960 starting position.

By default white to move (ignore_turn) and full castling rights (ignore_castling) are required, but move counters (ignore_counters) are ignored.

epd(shredder=False, en_passant='legal', promoted=None, **operations)

Gets an EPD representation of the current position.

See fen() for FEN formatting options (shredder, ep_square and promoted).

EPD operations can be given as keyword arguments. Supported operands are strings, integers, floats, moves, lists of moves and None. All other operands are converted to strings.

A list of moves for pv will be interpreted as a variation. All other move lists are interpreted as a set of moves in the current position.

hmvc and fmvc are not included by default. You can use:

>>> import chess
>>>
>>> board = chess.Board()
>>> board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number)
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - hmvc 0; fmvc 1;'
set_epd(epd)

Parses the given EPD string and uses it to set the position.

If present, hmvc and fmvn are used to set the half-move clock and the full-move number. Otherwise, 0 and 1 are used.

Returns a dictionary of parsed operations. Values can be strings, integers, floats, move objects, or lists of moves.

Raises:ValueError if the EPD string is invalid.
san(move)

Gets the standard algebraic notation of the given move in the context of the current position.

lan(move)

Gets the long algebraic notation of the given move in the context of the current position.

variation_san(variation)

Given a sequence of moves, returns a string representing the sequence in standard algebraic notation (e.g., 1. e4 e5 2. Nf3 Nc6 or 37...Bg6 38. fxg6).

The board will not be modified as a result of calling this.

Raises:ValueError if any moves in the sequence are illegal.
parse_san(san)

Uses the current position as the context to parse a move in standard algebraic notation and returns the corresponding move object.

The returned move is guaranteed to be either legal or a null move.

Raises:ValueError if the SAN is invalid or ambiguous.
push_san(san)

Parses a move in standard algebraic notation, makes the move and puts it on the the move stack.

Returns the move.

Raises:ValueError if neither legal nor a null move.
uci(move, chess960=None)

Gets the UCI notation of the move.

chess960 defaults to the mode of the board. Pass True to force Chess960 mode.

parse_uci(uci)

Parses the given move in UCI notation.

Supports both Chess960 and standard UCI notation.

The returned move is guaranteed to be either legal or a null move.

Raises:ValueError if the move is invalid or illegal in the current position (but not a null move).
push_uci(uci)

Parses a move in UCI notation and puts it on the move stack.

Returns the move.

Raises:ValueError if the move is invalid or illegal in the current position (but not a null move).
is_en_passant(move)

Checks if the given pseudo-legal move is an en passant capture.

is_capture(move)

Checks if the given pseudo-legal move is a capture.

is_zeroing(move)

Checks if the given pseudo-legal move is a capture or pawn move.

is_irreversible(move)

Checks if the given pseudo-legal move is irreversible.

In standard chess, pawn moves, captures and moves that destroy castling rights are irreversible.

is_castling(move)

Checks if the given pseudo-legal move is a castling move.

is_kingside_castling(move)

Checks if the given pseudo-legal move is a kingside castling move.

is_queenside_castling(move)

Checks if the given pseudo-legal move is a queenside castling move.

clean_castling_rights()

Returns valid castling rights filtered from castling_rights.

has_castling_rights(color)

Checks if the given side has castling rights.

has_kingside_castling_rights(color)

Checks if the given side has kingside (that is h-side in Chess960) castling rights.

has_queenside_castling_rights(color)

Checks if the given side has queenside (that is a-side in Chess960) castling rights.

has_chess960_castling_rights()

Checks if there are castling rights that are only possible in Chess960.

status()

Gets a bitmask of possible problems with the position.

Move making, generation and validation are only guaranteed to work on a completely valid board.

STATUS_VALID for a completely valid board.

Otherwise, bitwise combinations of: STATUS_NO_WHITE_KING, STATUS_NO_BLACK_KING, STATUS_TOO_MANY_KINGS, STATUS_TOO_MANY_WHITE_PAWNS, STATUS_TOO_MANY_BLACK_PAWNS, STATUS_PAWNS_ON_BACKRANK, STATUS_TOO_MANY_WHITE_PIECES, STATUS_TOO_MANY_BLACK_PIECES, STATUS_BAD_CASTLING_RIGHTS, STATUS_INVALID_EP_SQUARE, STATUS_OPPOSITE_CHECK, STATUS_EMPTY, STATUS_RACE_CHECK, STATUS_RACE_OVER, STATUS_RACE_MATERIAL.

is_valid()

Checks if the board is valid.

Move making, generation and validation are only guaranteed to work on a completely valid board.

See status() for details.

mirror()

Returns a mirrored copy of the board.

The board is mirrored vertically and piece colors are swapped, so that the position is equivalent modulo color.

copy(stack=True)

Creates a copy of the board.

classmethod empty(chess960=False)

Creates a new empty board. Also see clear().

classmethod from_epd(epd, chess960=False)

Creates a new board from an EPD string. See set_epd().

Returns the board and the dictionary of parsed operations as a tuple.

classmethod from_chess960_pos(sharnagl)

Creates a new board, initialized with a Chess960 starting position.

>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))
class chess.BaseBoard(board_fen='rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')

A board representing the position of chess pieces. See Board for a full board with move generation.

The board is initialized with the standard chess starting position, unless otherwise specified in the optional board_fen argument. If board_fen is None, an empty board is created.

clear_board()

Clears the board.

pieces(piece_type, color)

Gets pieces of the given type and color.

Returns a set of squares.

piece_at(square)

Gets the piece at the given square.

piece_type_at(square)

Gets the piece type at the given square.

king(color)

Finds the king square of the given side. Returns None if there is no king of that color.

In variants with king promotions, only non-promoted kings are considered.

attacks(square)

Gets a set of attacked squares from a given square.

There will be no attacks if the square is empty. Pinned pieces are still attacking other squares.

Returns a set of squares.

is_attacked_by(color, square)

Checks if the given side attacks the given square.

Pinned pieces still count as attackers. Pawns that can be captured en passant are not considered attacked.

attackers(color, square)

Gets a set of attackers of the given color for the given square.

Pinned pieces still count as attackers.

Returns a set of squares.

pin(color, square)

Detects an absolute pin (and its direction) of the given square to the king of the given color.

>>> import chess
>>>
>>> board = chess.Board("rnb1k2r/ppp2ppp/5n2/3q4/1b1P4/2N5/PP3PPP/R1BQKBNR w KQkq - 3 7")
>>> board.is_pinned(chess.WHITE, chess.C3)
True
>>> direction = board.pin(chess.WHITE, chess.C3)
>>> direction
SquareSet(0x0000000102040810)
>>> print(direction)
. . . . . . . .
. . . . . . . .
. . . . . . . .
1 . . . . . . .
. 1 . . . . . .
. . 1 . . . . .
. . . 1 . . . .
. . . . 1 . . .

Returns a set of squares that mask the rank, file or diagonal of the pin. If there is no pin, then a mask of the entire board is returned.

is_pinned(color, square)

Detects if the given square is pinned to the king of the given color.

remove_piece_at(square)

Removes the piece from the given square. Returns the Piece or None if the square was already empty.

set_piece_at(square, piece, promoted=False)

Sets a piece at the given square.

An existing piece is replaced. Setting piece to None is equivalent to remove_piece_at().

board_fen(promoted=False)

Gets the board FEN.

set_board_fen(fen)

Parses a FEN and sets the board from it.

Raises:ValueError if the FEN string is invalid.
piece_map()

Gets a dictionary of pieces by square index.

set_piece_map(pieces)

Sets up the board from a dictionary of pieces by square index.

set_chess960_pos(sharnagl)

Sets up a Chess960 starting position given its index between 0 and 959. Also see from_chess960_pos().

chess960_pos()

Gets the Chess960 starting position index between 0 and 959 or None.

mirror()

Returns a mirrored copy of the board.

The board is mirrored vertically and piece colors are swapped, so that the position is equivalent modulo color.

copy()

Creates a copy of the board.

classmethod empty()

Creates a new empty board. Also see clear_board().

classmethod from_chess960_pos(sharnagl)

Creates a new board, initialized with a Chess960 starting position.

>>> import chess
>>> import random
>>>
>>> board = chess.Board.from_chess960_pos(random.randint(0, 959))

Square sets

class chess.SquareSet(mask=0)

A set of squares.

>>> import chess
>>>
>>> squares = chess.SquareSet(chess.BB_A8 | chess.BB_RANK_1)
>>> squares
SquareSet(0x01000000000000ff)
>>> print(squares)
1 . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
1 1 1 1 1 1 1 1
>>> len(squares)
9
>>> bool(squares)
True
>>> chess.B1 in squares
True
>>> for square in squares:
...     # 0 -- chess.A1
...     # 1 -- chess.B1
...     # 2 -- chess.C1
...     # 3 -- chess.D1
...     # 4 -- chess.E1
...     # 5 -- chess.F1
...     # 6 -- chess.G1
...     # 7 -- chess.H1
...     # 56 -- chess.A8
...     print(square)
...
0
1
2
3
4
5
6
7
56
>>> list(squares)
[0, 1, 2, 3, 4, 5, 6, 7, 56]

Square sets are internally represented by 64-bit integer masks of the included squares. Bitwise operations can be used to compute unions, intersections and shifts.

>>> int(squares)
72057594037928191

Also supports common set operations like issubset(), issuperset(), union(), intersection(), difference(), symmetric_difference() and copy() as well as update(), intersection_update(), difference_update(), symmetric_difference_update() and clear().

add(square)

Adds a square to the set.

remove(square)

Removes a square from the set.

Raises:KeyError if the given square was not in the set.
discard(square)

Discards a square from the set.

pop()

Removes a square from the set and returns it.

Raises:KeyError on an empty set.
classmethod from_square(square)

Creates a SquareSet from a single square.

>>> import chess
>>>
>>> chess.SquareSet.from_square(chess.A1) == chess.BB_A1
True

Common integer masks are:

chess.BB_VOID = 0
chess.BB_ALL = 0xFFFFFFFFFFFFFFFF

Single squares:

chess.BB_SQUARES = [chess.BB_A1, chess.BB_B1, ..., chess.BB_G8, chess.BB_H8]

Ranks and files:

chess.BB_RANKS = [chess.BB_RANK_1, ..., chess.BB_RANK_8]
chess.BB_FILES = [chess.BB_FILE_A, ..., chess.BB_FILE_H]

Other masks:

chess.BB_LIGHT_SQUARES = 0x55AA55AA55AA55AA
chess.BB_DARK_SQUARES = 0xAA55AA55AA55AA55
chess.BB_BACKRANKS = chess.BB_RANK_1 | chess.BB_RANK_8
chess.BB_CORNERS = chess.BB_A1 | chess.BB_H1 | chess.BB_A8 | chess.BB_H8