Skip to content Skip to sidebar Skip to footer

Python User-defined Data Type

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 s

Solution 1:

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.

Solution 2:

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.

Solution 3:

classState:
   Blocked=1
   Wall=2
   Floor=3

some = State.Blocked

Post a Comment for "Python User-defined Data Type"