Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Pieces immutable and return them from cache #921

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion chess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ def between(a: Square, b: Square) -> Bitboard:
FEN_CASTLING_REGEX = re.compile(r"^(?:-|[KQABCDEFGH]{0,2}[kqabcdefgh]{0,2})\Z")


@dataclasses.dataclass
@dataclasses.dataclass(frozen=True)
class Piece:
"""A piece with type and color."""

Expand All @@ -457,6 +457,25 @@ class Piece:
color: Color
"""The piece color."""

WHITE_PIECE_OBJECTS: List[Piece] = None # initialized next
BLACK_PIECE_OBJECTS: List[Piece] = None # initialized next

@classmethod
def from_cache(cls, piece_type: PieceType, color: Color) -> 'Piece':
"""
Fetches a :class:`~chess.Piece` instance from a piece type and color.

:raises: :exc:`ValueError` if the piece type or color is invalid.
"""

if piece_type < 1 or piece_type > 6:
raise ValueError("invalid piece type")
if color == WHITE:
return cls.WHITE_PIECE_OBJECTS[piece_type]
elif color == BLACK:
return cls.BLACK_PIECE_OBJECTS[piece_type]
raise NotImplementedError('invalid color')

def symbol(self) -> str:
"""
Gets the symbol ``P``, ``N``, ``B``, ``R``, ``Q`` or ``K`` for white
Expand Down Expand Up @@ -494,6 +513,19 @@ def from_symbol(cls, symbol: str) -> Piece:
"""
return cls(PIECE_SYMBOLS.index(symbol.lower()), symbol.isupper())

@classmethod
def initialize_cache(cls):
# There is no piece 0, so just fill that slot in so we don't need to do arithmetic later on.
cls.WHITE_PIECE_OBJECTS = [None, *(Piece(piece_type, WHITE) for piece_type in PIECE_TYPES)]
cls.BLACK_PIECE_OBJECTS = [None, *(Piece(piece_type, BLACK) for piece_type in PIECE_TYPES)]
# Sneak in a trampoline to `cls.from_cache()` method.
cls.__new__ = piece_from_cache

def piece_from_cache(cls, piece_type: PieceType, color: Color) -> 'Piece':
return cls.from_cache(piece_type, color)

Piece.initialize_cache()


@dataclasses.dataclass(unsafe_hash=True)
class Move:
Expand Down