en_pyssant package

Module contents

En Pyssant is a chess implementation and engine.

class Type[source]

Bases: enum.Enum

Type of piece.

BISHOP = 'b'
KING = 'k'
KNIGHT = 'n'
PAWN = 'p'
QUEEN = 'q'
ROOK = 'r'
class Side[source]

Bases: enum.Enum

Colours corresponding to sides.

BLACK = 0
WHITE = 1
class Piece[source]

Bases: en_pyssant._core.Piece

A chess piece. This object is immutable.

>>> white_rook = Piece(Type.ROOK, Side.WHITE)
>>> white_rook.side = Side.BLACK
Traceback (most recent call last):
    ...
AttributeError: can't set attribute
Parameters:
  • type – Type of piece.
  • side – Side to which the piece belongs.
classmethod from_str(char)[source]

Create a piece from char. char must be a single letter as found in Type. Lower case means that the piece is black, and upper case means that the piece is white.

Parameters:char (str) – String representation of piece.
Return type:Piece
Returns:A piece.
class Direction[source]

Bases: enum.Enum

General four directions.

DOWN = (0, -1)
LEFT = (-1, 0)
RIGHT = (1, 0)
UP = (0, 1)
class Square[source]

Bases: str

A wrapper class around str that handles only chess squares.

>>> Square('a1')
'a1'
>>> Square('')
Traceback (most recent call last):
    ...
ValueError: '' is not a valid square
>>> Square('a9')
Traceback (most recent call last):
    ...
ValueError: 'a9' is not a valid square
down()[source]
Return type:Square
Returns:One square down.
Raises:IndexError – Cannot go down.
goto(direction)[source]
Parameters:direction (Union[Direction, Tuple[int, int]]) – Direction to go to.
Return type:Square
Returns:One square in the given direction.
Raises:IndexError – Destination out of bounds.
in_bounds(path)[source]

Traverse with path. Return the destination if it is inside the bounds of a chess board. Else, return False.

Note

A sequence of (int, int) tuples is more performant than a sequence of Direction objects. To get such a tuple, just do direction.value.

Parameters:path (Sequence[Union[Direction, Tuple[int, int]]]) – Path to traverse to destination. Must be hashable.
Return type:Union[Square, bool]
Returns:Destination square or False
left()[source]
Return type:Square
Returns:One square to the left.
Raises:IndexError – Cannot go left.
right()[source]
Return type:Square
Returns:One square to the right.
Raises:IndexError – Cannot go right.
traverse(path)[source]
Parameters:path (Sequence[Union[Direction, Tuple[int, int]]]) – Sequence of directions to follow. Must be hashable.
Return type:Square
Returns:The square at the end of the path.
Raises:IndexError – Path goes out of bounds.
up()[source]
Return type:Square
Returns:One square up.
Raises:IndexError – Cannot go up.
colour

Colour of the square.

Return type:Side
file

The file (or column) of the square.

Return type:str
rank

The rank (or row) of the square.

Return type:int
class MoveFlag[source]

Bases: enum.Enum

Flags associated with a move.

EN_PASSANT_CAPTURE = 2
KINGSIDE_CASTLING = 5
NON_CAPTURE = 0
PAWN_PUSH = 3
PROMOTION = 6
QUEENSIDE_CASTLING = 4
STANDARD_CAPTURE = 1
class Move[source]

Bases: en_pyssant._core.Move

A move on the chess board.

Under normal circumstances, you only need to provide origin, destination and possibly promotion when using a Move object to interface with the rest of the API. The rest is metadata, as it were.

Parameters:
  • origin – Square from which the piece has moved.
  • destination – Square to which the piece has moved.
  • piece – The piece that has moved.
  • captured – If a capture move: Piece that has been captured.
  • promotion – The piece type that the pawn has been promoted to.
  • flags – Flags associated with move.
expand(position, ruleset)[source]

Given a move that contains only origin and destination, return a new, fully descriptive move that contains all fields.

Promotion moves that do not already specify which piece to promoto to will default to queen promotions.

Parameters:
  • position (Position) – Chess position before the move is performed.
  • ruleset – Game ruleset.
Return type:

Move

Returns:

A fully expanded move.

Raises:

ValueError – Move is invalid.

classmethod from_san(san, position, ruleset, strict=False)[source]

Return a Move object from a Standard Algebraic Notation string.

Parameters:
  • san (str) – Standard Algebraic Notation.
  • position (Position) – Chess position _before_ the move is performed.
  • ruleset – Game ruleset.
  • strict (bool) – Only accept the strictest possible notation as valid.
Return type:

Move

Returns:

A move.

Raises:

ValueErrorsan is invalid.

san(position, ruleset)[source]

Return the Standard Algebraic Notation of a move.

Parameters:
  • position (Position) – Chess position _before_ the move is performed.
  • ruleset – Game ruleset.
Return type:

str

Returns:

Standard Algebraic Notation.

class HistoryRecord[source]

Bases: en_pyssant._core.HistoryRecord

A history record. This object is immutable.

You may put these in a list to keep track of a game’s history.

Parameters:
  • position (Position) – Position before move is executed.
  • move – Move chosen by the player.
class Gameover[source]

Bases: enum.Enum

How a game has ended. There is no value for ‘game has not ended’.

CHECKMATE = 1
FIFTY_MOVE = 3
INSUFFICIENT_MATERIAL = 4
STALEMATE = 2
THREEFOLD_REPETITION = 5
class CastlingSide[source]

Bases: en_pyssant._position.CastlingSide

Tuple of kingside and queenside castling availability.

>>> castling_side = CastlingSide(True, True)
>>> castling_side.kingside
True
Parameters:
  • kingside – Whether kingside castling is available.
  • queenside – Whether queenside castling is available.
class Castling[source]

Bases: en_pyssant._position.Castling

Tuple of white and black CastlingSide.

>>> castling = Castling(CastlingSide(True, True), CastlingSide(True, True))
>>> castling.white.kingside
True
>>> castling[Side.WHITE].kingside
True
>>> castling[0].kingside
True
Parameters:
  • white – Kingside and queenside castling on the white side.
  • black – Kingside and queenside castling on the black side.
class Board[source]

Bases: object

An abstract base class for a chess board implementation. A chess board is immutable and need implement only get(), put() and __init__(). __init__() must take no positional arguments and - without any arguments - create an initial chess board.

All other methods are already implemented.

all_pieces()[source]

Yield all squares and their respective pieces, from a1 to h8. Increment files before ranks.

Comparable to enumerate(), except for squares and pieces.

Return type:Iterator[Tuple[Square, Optional[Piece]]]
Returns:All squares and their respective pieces.
classmethod from_fen(fen)[source]

Generate a Board from the board portion of a Forsyth-Edwards Notation string.

Parameters:fen (str) – First part of Forsyth-Edwards Notation
Return type:Board
Returns:A board.
Raises:ValueError – Input is invalid.
get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
pretty()[source]
>>> print(DictBoard().pretty())
  A B C D E F G H
8 r n b q k b n r
7 p p p p p p p p
6 . . . . . . . .
5 . . . . . . . .
4 . . . . . . . .
3 . . . . . . . .
2 P P P P P P P P
1 R N B Q K B N R
Return type:str
Returns:A pretty representation of the board.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

Board

Returns:

A new board.

class BitBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A bitboard representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

BitBoard

Returns:

A new board.

class BytesBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A simple bytes-based board representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

BytesBoard

Returns:

A new board.

class DictBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A simple dictionary-based board representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

DictBoard

Returns:

A new board.

class ListBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A simple list-based board representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

DictBoard

Returns:

A new board.

class StringBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A simple string-based board representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

StringBoard

Returns:

A new board.

class TupleBoard(**kwargs)[source]

Bases: en_pyssant._board.Board

A tuple-based board representation.

get(square)[source]

Return piece at square. Return None if no piece exists at square.

Parameters:square (str) – Square in algebraic notation.
Return type:Optional[Piece]
Returns:Piece at square.
put(square, piece)[source]

Put piece on square. Override any existing pieces. Return a new board.

Parameters:
  • square (str) – Square in algebraic notation.
  • piece (Optional[Piece]) – Piece to be placed on square.
Return type:

DictBoard

Returns:

A new board.

class Position[source]

Bases: en_pyssant._position.Position

Tuple that represents a snapshot of the state of a chess game. The structure explicitly matches Forsyth-Edwards Notation as well as possible.

Important

A chess position is a state, not a location.

>>> Position(
...     DictBoard(),
...     Side.WHITE,
...     Castling(CastlingSide(True, True), CastlingSide(True, True)),
...     None,
...     0,
...     1)
...
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
>>> Position()  # No arguments
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
Parameters:
  • board – Board representation.
  • side_to_play – Side to play.
  • castling – Castling rights of black and white.
  • en_passant_target – Square ‘behind’ a pawn that has moved two squares in the previous turn.
  • half_move_clock – Number of halfmoves since last capture or pawn advance.
  • move_count – Amount of moves since start. Increments after black’s move.
classmethod from_fen(fen, board_cls=<class 'en_pyssant._board.DictBoard'>)[source]

Generate a Position from a Forsyth-Edwards Notation string.

>>> fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
>>> Position.from_fen(fen)
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
Parameters:
  • fen (str) – Forsyth-Edwards Notation.
  • board_cls (Type[Board]) – Type that will be used for board.
Return type:

Position

Returns:

A position.

Raises:

ValueError – Input is invalid

pretty()[source]
>>> print(Position().pretty())
  A B C D E F G H
8 r n b q k b n r
7 p p p p p p p p
6 . . . . . . . .
5 . . . . . . . .
4 . . . . . . . .
3 . . . . . . . .
2 P P P P P P P P
1 R N B Q K B N R

FEN: rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1
Return type:str
Returns:A pretty representation of the position.
class Game(position=None, history=None, ruleset=None, event=None, site=None, date=None, round=None, white=None, black=None)[source]

Bases: object

Central game object that is used to play the game.

All undocumented methods are documented in rules. Except where rules accepts position and history parameters, those parameters are implicit in this class. The instance variables are passed and altered.

Variables:
Parameters:
  • position (Optional[Position]) – Chess position.
  • history (Optional[Sequence[HistoryRecord]]) – History of plays.
  • ruleset – Game ruleset.
  • event (Optional[str]) – The name of the tournament or match event.
  • site (Optional[str]) – The location of the event.
  • date (Optional[str]) – The starting date of the game.
  • round (Optional[str]) – The playing round ordinal of the game.
  • white (Optional[str]) – The player of the white pieces.
  • black (Optional[str]) – The player of the black pieces.
attacked(side, square)[source]
Return type:bool
do_move(move, force=False)[source]

Important

position and history are updated when calling this method.

Return type:Position
do_move_with_history(move, force=False)[source]

Important

position and history are updated when calling this method.

Return type:Tuple[Position, HistoryRecord]
classmethod from_pgn(pgn, board_cls=<class 'en_pyssant._board.DictBoard'>, ruleset=None)[source]

Generate a Game from a Portable Game Notation string.

An example PGN is:

[Event "F/S Return Match"]
[Site "Belgrade, Serbia JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
[Result "1/2-1/2"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5
7. Bb3 d6 8. c3 O-O 9. h3 Nb8 10. d4 Nbd7 11. c4 c6 12. cxb5 axb5
13. Nc3 Bb7 14. Bg5 b4 15.  Nb1 h6 16. Bh4 c5 17. dxe5 Nxe4
18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21.  Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3
Qg5 28. Qxg5 hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5
33.  f3 Bc8 34. Kf2 Bf5 35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3
Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6 Nf2 42. g4 Bd3 43. Re6 1/2-1/2
Parameters:
  • pgn (str) – Portable Game Notation.
  • board_cls (Type[Board]) – Type that will be used for the board representation.
  • ruleset – Game ruleset.
Return type:

Game

Returns:

A game.

Raises:

ValueError – Input is invalid.

is_check(side=None)[source]
Return type:bool
is_checkmate()[source]
Return type:bool
is_draw()[source]
Return type:bool
is_fifty_move()[source]
Return type:bool
is_gameover()[source]
Return type:bool
is_insufficient_material()[source]
Return type:bool
is_stale()[source]
Return type:bool
is_stalemate()[source]
Return type:bool
is_threefold_repetition()[source]
Return type:bool
loser()[source]
Return type:Side
moves()[source]
Return type:Iterator[Move]
pgn()[source]

Generate and return the Portable Game Notation.

The movetext is wrapped at 80 characters.

Return type:str
Returns:Portable Game Notation of current game state.
winner()[source]
Return type:Side