I am trying to build a simple chess board in Python 3 and I am a bit lost representing the pieces properly. I thought it would be a reasonable idea to defined values for every colour and piece like that:
from enum import Enum
class Piece(Enum):
"This class represents a piece and its colour"
Empty = 0
King = 1
Pawn = 2
Knight = 4
Bishop = 8
Rook = 16
Queen = 32
White = 64
Black = 128
Now I would like to represent a piece by concatenating the colour and the piece like that here:
squares = []
square[0] = Piece.White | Piece.Rook
Unfortunately, my IDE tells me that piece wouldn't have a member of type "Rook".
Is my way of using enums totally wrong? I am used to doing such stuff in other programming languages, but I am new to enums in Python. Is there any clever idea on how to fix that?
You're looking for a Flag
enum. See the documentation for example usage, but your code as written should be fine if you just change Enum
to Flag
.