1 from naja.constants import BITS
4 class PlayerBits(object):
9 def __init__(self, bits):
17 def bits(self, value):
18 assert 0 <= value <= 0xff
21 # Operate on individual bits
23 def check_bit(self, bit):
24 return bool(self.bits & (1 << bit))
26 def set_bit(self, bit):
27 self.bits |= (1 << bit)
29 def clear_bit(self, bit):
30 self.bits &= (0xff ^ (1 << bit))
32 def toggle_bit(self, bit):
33 self.bits ^= (1 << bit)
35 # Operate on sets of bits
37 def check_bits(self, bits):
38 return all(self.check_bit(bit) for bit in bits)
40 def set_bits(self, bits):
44 def clear_bits(self, bits):
48 def toggle_bits(self, bits):
55 A representation of the player.
58 def __init__(self, bits, position):
59 self.bits = PlayerBits(bits)
60 self.position = position
63 def import_player(cls, definition):
64 return cls(definition['bits'], tuple(definition['position']))
68 'bits': self.bits.bits,
69 'position': list(self.position),
72 def get_adjacent_position(self, direction):
74 if direction == BITS.NORTH and y > 0:
76 elif direction == BITS.SOUTH and y < 4:
78 elif direction == BITS.EAST and x < 4:
80 elif direction == BITS.WEST and x > 0:
86 def move(self, direction):
87 if not self.bits.check_bit(direction):
89 new_position = self.get_adjacent_position(direction)
90 if new_position is not None:
91 self.position = new_position
95 def legal_moves(self):
96 positions = [self.position]
97 for direction in [BITS.NORTH, BITS.SOUTH, BITS.EAST, BITS.WEST]:
98 position = self.get_adjacent_position(direction)
99 if position is not None and self.bits.check_bit(direction):
100 positions.append(position)