dispense with movement mode
[naja.git] / naja / player.py
index fcfc3301de4ab22bdfed7982b210d4acc73a29e3..f502b640ffd94ddd999022931425e77248794141 100644 (file)
@@ -1,3 +1,4 @@
+from naja.constants import BITS
 
 
 class PlayerBits(object):
@@ -57,3 +58,50 @@ class Player(object):
     def __init__(self, bits, position):
         self.bits = PlayerBits(bits)
         self.position = position
+
+    @classmethod
+    def import_player(cls, definition):
+        return cls(definition['bits'], tuple(definition['position']))
+
+    def export(self):
+        return {
+            'bits': self.bits.bits,
+            'position': list(self.position),
+        }
+
+    def get_adjacent_position(self, direction):
+        x, y = self.position
+        if direction == BITS.NORTH and y > 0:
+            return (x, y - 1)
+        elif direction == BITS.SOUTH and y < 4:
+            return (x, y + 1)
+        elif direction == BITS.EAST and x < 4:
+            return (x + 1, y)
+        elif direction == BITS.WEST and x > 0:
+            return (x - 1, y)
+        else:
+            # Not a legal space.
+            return None
+
+    def move(self, direction):
+        if not self.bits.check_bit(direction):
+            return False
+        new_position = self.get_adjacent_position(direction)
+        if new_position is not None:
+            self.position = new_position
+            return True
+        return False
+
+    def set_position(self, new_position):
+        if new_position in self.legal_moves():
+            self.position = new_position
+            return True
+        return False
+
+    def legal_moves(self):
+        positions = [self.position]
+        for direction in [BITS.NORTH, BITS.SOUTH, BITS.EAST, BITS.WEST]:
+            position = self.get_adjacent_position(direction)
+            if position is not None and self.bits.check_bit(direction):
+                positions.append(position)
+        return positions