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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

There's no need to use tuple(range(3)) in Python 3 - tuple assignment to a generator works fine (I just tested it).
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.

Comments

0
class State: Blocked=1 Wall=2 Floor=3 some = State.Blocked 

1 Comment

The second version of the third answer is way better IMO. It ends up with the same result as this one but is much less error prone.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.