equivalent of enum?

Skip Montanaro skip at mojam.com
Thu Sep 9 18:39:20 EDT 1999


    Remco> The board has squares, that can hold a piece. I want those to be
    Remco> represented by integers (whiterook is 1, whiteknight is 2,
    Remco> etc). But I want to refer to them by name in the code, not use
    Remco> the magic number 2 everywhere, and I want to index arrays with
    Remco> them.

If you expect to have properties associated with particular pieces
(position, strength, etc), you might want to consider representing them by
instances of a specific ChessPiece class instead:

    class ChessPiece:
	  def __init__(self, strength, x, y, color):
	      self.strength = strength
	      self.x = x
	      self.y = y
	      self.color = color
	      ...

	  def move(self, x, y):
	      if self.validate_move(x, y):
		 self.x = x
		 self.y = y

	  ...

    class Rook(ChessPiece):
	  def validate_move(self, x, y, board):
	      """can we make a rook move to (x,y) in this board configuration?"""

    class Knight(ChessPiece):
	  def validate_move(self, x, y, board):
	      """can we make a knight move to (x,y) in this board configuration?"""
	      ...

    ...

    whiterook = Rook(5, "h", "8", "white")
    whitenight = Knight(3, "h", "7", "white")
    ...

That way you can refer to them by name and as you flesh out the
functionality, provide methods that do lots of chessy (not cheesy!) stuff
when asked:

In more direct answer to your question, there is no enum type in Python.
It's simple enough to declare objects that you treat as constants, however:

    whiterook = 1
    whiteknight = 2
    ...

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/~skip/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list