3

I am writing a rogue-like game in Python and am defining my Tile class. A tile can either be blocked, wall or floor. I would like to be able to write something along the lines of

self.state = Blocked

similar to how you would use a boolean (but with three values).

Is there a nice way for me to define a data type to enable me to do this?

Thanks

TartanLlama
  • 63,752
  • 13
  • 157
  • 193

3 Answers3

4

For three constants, I would use the unpacking version of the enum 'pattern':

Blocked, Wall, Floor = range(3)

If it gets more complex than that though, I would have a look at other enum types in python.

Community
  • 1
  • 1
aaronasterling
  • 68,820
  • 20
  • 127
  • 125
  • 2
    There's no need to use tuple(range(3)) in Python 3 - tuple assignment to a generator works fine (I just tested it). – Chris Morgan Nov 19 '10 at 12:55
1

Make use of bit flags. You can search google for more information, in the simplest terms you can store Boolean values in binary form, since True/False is one bit you can make a 4 bits or 1 byte to store 4 different Booleans.

So let say it like this:

python syntax:
a = 0x0 #[ this is python representation of bit flag or binary number <class 'int'> or in python27 <type 'int'> ]

binary representation:
0x0 = 000 [ zero is zero it does not matter how long the binary variable is]
0x1 = 001 [ 1 ]
0x2 = 010 [ 2 ]
0x4 = 100 [ 4 ]
so here we have 3 or more different Boolean places that we can check, since 000000000001 == 001 == 01 == 0x1

but in bit flags
0x3 = 011 [3 = 2+1]
0x5 = 101 [5 = 4+1]
0x6 = 110 [6 = 4+2]
0x7 = 111 [7 = 4+2+1]

IN THE MOST SIMPLEST TERMS I will give you one comparison syntax & which means AND, that means that place of '1' in bit flag must be the same. So in practical terms 0x1&0x2==0x2 will be False because 001&010 does not have '1' in the same place

so if you want to check for two types in bit flag just add them together and check, with syntax above.
example: 0x3&(0x1+0x2)==(0x1+0x2)

I hope this helps. Happy googling.

Danilo
  • 1,017
  • 13
  • 32
0
class State:
   Blocked=1
   Wall=2
   Floor=3

some = State.Blocked
ceth
  • 44,198
  • 62
  • 180
  • 289
  • The second version of the [third answer](http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python/1695250#1695250) is __way__ better IMO. It ends up with the same result as this one but is much less error prone. – aaronasterling Nov 19 '10 at 13:04