Optional sanity check for actions.
[naja.git] / naja / gameboard.py
index a107b16315416a1deb6cce27e74e1abc9b9216bf..689c3fd15fcf324d9110763331a6a0eeb93023d2 100644 (file)
@@ -1,6 +1,14 @@
 from random import choice
 
-from naja.constants import BITS, DIRECTION_BITS, CONDITION_BITS
+from naja.constants import(
+    BITS, DIRECTION_BITS, CONDITION_BITS, PLAYER_DEFAULTS,
+    ACT, EXAMINE, ROTATION)
+from naja.options import options
+from naja.player import Player
+from naja import actions
+from naja.sound import sound
+from naja.utils import parse_bits
+import random
 
 
 class GameBoard(object):
@@ -8,28 +16,281 @@ class GameBoard(object):
     A representation of the game board.
     """
 
-    def __init__(self, player, health, wins, locations=None, state=None):
+    def __init__(self, state, player, board_locations):
+        self.max_health = state['max_health']
+        self.wins_required = state['wins_required']
+        self.health = state['health']
+        self.wins = state['wins']
+        self.locations = [item.copy() for item in state['locations']]
+        self.puzzle = state.get('puzzle', False)
         self.player = player
-        self.max_health = health
-        self.wins_required = wins
+        self.board_locations = board_locations
+        self.player_mode = state.get('player_mode', EXAMINE)
+        self.has_cheated = state.get('cheater', options.cheat_enabled)
+        self.clock_count = state.get('clock_count', 0)
+        self.replacement_params = state.get('replacement_params', None)
 
-        if locations is None:
-            locations = self.generate_locations()
-        self.locations = locations
+    @classmethod
+    def new_game(cls, deck, initial_bits=None, initial_pos=None,
+                 max_health=None, wins_required=None):
 
-        if state is None:
-            state = self.generate_state()
-        self.update_state(state)
+        defaults = {
+            'initial_bits': PLAYER_DEFAULTS.INITIAL_BITS,
+            'initial_pos': PLAYER_DEFAULTS.INITIAL_POS,
+            'max_health': PLAYER_DEFAULTS.MAX_HEALTH,
+            'wins_required': PLAYER_DEFAULTS.WINS_REQUIRED,
+        }
 
-    @classmethod
-    def generate_locations(cls):
-        raise NotImplementedError("TODO")
+        deck_defaults = deck.get('defaults', {})
+        for k, v in deck_defaults.iteritems():
+            if isinstance(v, list):
+                deck_defaults[k] = tuple(v)
+        defaults.update(deck_defaults)
 
-    def generate_state(self):
-        return {
-            'health': self.max_health,
+        if initial_bits is None:
+            initial_bits = defaults['initial_bits']
+        if initial_pos is None:
+            initial_pos = defaults['initial_pos']
+        if max_health is None:
+            max_health = defaults['max_health']
+        if wins_required is None:
+            wins_required = defaults['wins_required']
+
+        assert wins_required + max_health == 8
+
+        # Overriden by command line
+        if options.initial_bits:
+            initial_bits = options.initial_bits
+
+        state = {
+            'max_health': max_health,
+            'health': max_health,
+            'wins_required': wins_required,
             'wins': 0,
+            'locations': deck['cards'],
+            'puzzle': deck.get('puzzle', False),
+            'clock_count': 0,
+            'replacement_params': deck.get('replacement_params', None),
         }
+        player = Player(initial_bits, initial_pos)
+        board_locations = cls.import_board_locations(
+            cls.generate_board(deck))
+        board = cls(state, player, board_locations)
+        player.set_gameboard(board)
+        return board
+
+    @classmethod
+    def import_game(cls, definition):
+        state = definition.copy()
+        player = Player.import_player(state.pop('player'))
+        board_locations = cls.import_board_locations(
+            state.pop('board_locations'))
+        board = cls(state, player, board_locations)
+        player.set_gameboard(board)
+        return board
+
+    def export(self):
+        data = {
+            'max_health': self.max_health,
+            'health': self.health,
+            'wins_required': self.wins_required,
+            'wins': self.wins,
+            'locations': [item.copy() for item in self.locations],
+            'puzzle': self.puzzle,
+            'player': self.player.export(),
+            'board_locations': self.export_board_locations(),
+            'player_mode': self.player_mode,
+            'clock_count': self.clock_count,
+            'replacement_params': self.replacement_params,
+        }
+        if options.cheat_enabled:
+            self.has_cheated = True
+        if self.has_cheated:
+            data['cheater'] = True
+        return data
+
+    @classmethod
+    def import_locations(cls, locations_definition):
+        return [
+            LocationCard.import_location(definition)
+            for definition in locations_definition]
+
+    def export_board_locations(self):
+        return sorted(
+            (position, location.export())
+            for position, location in self.board_locations.iteritems())
+
+    @classmethod
+    def import_board_locations(cls, board_locations_definition):
+        return dict(
+            (tuple(position), LocationCard.import_location(definition))
+            for position, definition in board_locations_definition)
+
+    @classmethod
+    def generate_board(cls, deck):
+        if deck.get('puzzle', False):
+            return cls.generate_puzzle_board(deck)
+        else:
+            return cls.generate_random_board(deck)
+
+    @classmethod
+    def generate_puzzle_board(cls, deck):
+        assert len(deck['cards']) == 5 * 5
+        replacement_params = deck.get('replacement_params', None)
+        board_locations = [
+            [(i % 5, i // 5),
+             LocationCard.new_location(
+                 card.copy(), replacement_params, puzzle=True).export()]
+            for i, card in enumerate(deck['cards'])
+        ]
+        return board_locations
+
+    @classmethod
+    def generate_random_board(cls, deck):
+        board_locations = []
+        replacement_params = deck.get('replacement_params', None)
+        for x in range(5):
+            for y in range(5):
+                new_choice = cls.choose_card(deck['cards'], board_locations)
+                board_location = LocationCard.new_location(
+                    new_choice.copy(), replacement_params)
+                board_locations.append([(x, y), board_location.export()])
+        return board_locations
+
+    def lose_health(self):
+        self.health -= 1
+        if self.health <= 0:
+            self.end_game(win=False)
+
+    def gain_health(self):
+        if self.health < self.max_health:
+            self.health += 1
+
+    def acquire_win_token(self):
+        self.wins += 1
+        if self.wins >= self.wins_required:
+            self.end_game(win=True)
+
+    def card_used(self, position):
+        if not self.puzzle:
+            self.replace_card(position)
+
+    def replace_card(self, position):
+        new_choice = self.choose_card(self.locations,
+                                      self.board_locations.items(),
+                                      position)
+        location = LocationCard.new_location(new_choice.copy(),
+                                             self.replacement_params)
+        self.board_locations[position] = location
+
+    @classmethod
+    def choose_card(cls, cards, board_locations, position=None):
+        # Find which cards are at their maximum and exclude them from
+        # the choice list
+        counts = {}
+        choices = {card['card_name']: card for card in cards}
+        for pos, card in board_locations:
+            if pos == position:
+                # skip the card we're replacing if appropriate
+                continue
+            if isinstance(card, LocationCard):
+                key = card.card_name
+                max_num = card.max_number
+            else:
+                key = card['card_name']
+                max_num = card.get('max_number', 25)
+            counts.setdefault(key, 0)
+            counts[key] += 1
+            if counts[key] >= max_num:
+                if key in choices:
+                    del choices[key]
+        return choice(choices.values())
+
+    def shift_location_row(self, change, is_vertical):
+        px, py = self.player.position
+        shifted_locations = {}
+        mkpos = lambda i: (px, i) if is_vertical else (i, py)
+
+        for i in range(5):
+            if (px, py) == mkpos(i):
+                continue
+            new_i = (i + change) % 5
+            if (px, py) == mkpos(new_i):
+                new_i = (new_i + change) % 5
+            shifted_locations[mkpos(new_i)] = self.board_locations[mkpos(i)]
+
+        self.board_locations.update(shifted_locations)
+
+    def shift_locations(self, direction):
+        if BITS[direction] == BITS.NORTH:
+            self.shift_location_row(-1, is_vertical=True)
+        elif BITS[direction] == BITS.SOUTH:
+            self.shift_location_row(1, is_vertical=True)
+        elif BITS[direction] == BITS.EAST:
+            self.shift_location_row(1, is_vertical=False)
+        elif BITS[direction] == BITS.WEST:
+            self.shift_location_row(-1, is_vertical=False)
+
+    def rotate_locations(self, direction):
+        px, py = self.player.position
+        locations_to_rotate = []
+        rotated_locations = {}
+
+        if py > 0:
+            for i in range(max(0, px - 1), min(5, px + 2)):
+                locations_to_rotate.append((i, py - 1))
+
+        if px < 4:
+            locations_to_rotate.append((px + 1, py))
+
+        if py < 4:
+            for i in reversed(range(max(0, px - 1), min(5, px + 2))):
+                locations_to_rotate.append((i, py + 1))
+
+        if px > 0:
+            locations_to_rotate.append((px - 1, py))
+
+        if ROTATION[direction] == ROTATION.CLOCKWISE:
+            new_positions = locations_to_rotate[1:] + [locations_to_rotate[0]]
+        elif ROTATION[direction] == ROTATION.ANTICLOCKWISE:
+            new_positions = (
+                [locations_to_rotate[-1]] + locations_to_rotate[:-1])
+
+        for old, new in zip(locations_to_rotate, new_positions):
+            rotated_locations[new] = self.board_locations[old]
+
+        self.board_locations.update(rotated_locations)
+
+    def allow_chess_move(self, chesspiece):
+        self.player.allow_chess_move(chesspiece)
+
+    def change_mode(self, new_mode):
+        """Advance to the next mode"""
+        if new_mode == self.player_mode:
+            raise RuntimeError("Inconsistent state. Setting mode %s to itself"
+                               % self.player_mode)
+        elif new_mode in (ACT, EXAMINE):
+            self.player_mode = new_mode
+            if new_mode is EXAMINE:
+                self.board_update()
+        else:
+            raise RuntimeError("Illegal player mode %s" % self.player_mode)
+
+    def board_update(self):
+        self.clock_count += 1
+        for position, location in self.board_locations.iteritems():
+            location.timer_action(position, self)
+
+    def end_game(self, win):
+        # TODO: Find a way to not have UI stuff in game logic stuff.
+        from naja.events import SceneChangeEvent
+        from naja.scenes.lose import LoseScene
+        from naja.scenes.win import WinScene
+        sound.stop()
+        if win:
+            SceneChangeEvent.post(WinScene)
+        else:
+            SceneChangeEvent.post(LoseScene)
 
 
 class LocationCard(object):
@@ -37,14 +298,79 @@ class LocationCard(object):
     A particular set of options available on a location.
     """
 
-    def __init__(self, bitwise_operation, bitwise_operand, actions):
-        self.bitwise_operation = bitwise_operation
+    def __init__(self, card_name, bitwise_operand, location_actions,
+                 replacement_time=None, max_number=25):
+        self.card_name = card_name
         self.bitwise_operand = bitwise_operand
-        self.actions = actions
+        self.actions = location_actions
+        self.max_number = max_number
+        self.replacement_time = replacement_time
+        if options.debug:
+            for action in self.actions:
+                action.sanity_check(self)
 
-    @staticmethod
-    def generate_location():
-        raise NotImplementedError("TODO")
+    @classmethod
+    def import_location(cls, state):
+        location_actions = [
+            cls.build_action(definition) for definition in state['actions']]
+        return cls(state['card_name'], state['bitwise_operand'],
+                   location_actions, state['replacement_time'],
+                   state['max_number'])
+
+    @classmethod
+    def build_action(cls, definition):
+        action_class = getattr(actions, definition['action_class'])
+        required_bits = parse_bits(definition['required_bits'])
+        data = definition.get('data', {})
+        return action_class(required_bits, **data)
+
+    @classmethod
+    def new_location(cls, definition, replacement_params=None, puzzle=False):
+        if 'bits' in definition:
+            bits = parse_bits(definition['bits'])
+        else:
+            bits = cls.generate_bitwise_operand()
+
+        if 'replacement_time' in definition:
+            replacement_time = definition['replacement_time']
+        else:
+            replacement_time = cls.generate_replacement_time(
+                replacement_params)
+
+        max_number = definition.get('max_number', 25)
+        card_name = definition['card_name']
+        location = cls.import_location({
+            'bitwise_operand': bits,
+            'actions': definition['actions'],
+            'max_number': max_number,
+            'card_name': card_name,
+            'replacement_time': replacement_time,
+        })
+        if not puzzle:
+            location.check_actions()
+        return location
+
+    def export(self):
+        return {
+            'bitwise_operand': sorted(self.bitwise_operand),
+            'actions': [action.export() for action in self.actions],
+            'max_number': self.max_number,
+            'card_name': self.card_name,
+            'replacement_time': self.replacement_time,
+        }
+
+    def check_actions(self):
+        if not self.actions:
+            print "Warning: Location has no actions."
+            self.insert_default_default_action()
+        if self.actions[0].required_bits:
+            self.insert_default_default_action()
+
+    def insert_default_default_action(self):
+        self.actions.insert(0, self.build_action({
+            'action_class': 'DoNothing',
+            'required_bits': [],
+        }))
 
     @staticmethod
     def generate_bitwise_operand():
@@ -63,30 +389,18 @@ class LocationCard(object):
         return frozenset(bits)
 
     @staticmethod
-    def generate_location_actions():
-        raise NotImplementedError("TODO")
-
-    def apply_bitwise_operation(self, player):
-        operator = {
-            'SET': player.bits.set_bits,
-            'CLEAR': player.bits.clear_bits,
-            'TOGGLE': player.bits.toggle_bits,
-        }[self.bitwise_operation]
-        operator(self.bitwise_operand)
-
-
-class LocationAction(object):
-    """
-    An action that may be performed on a location.
-    """
-
-    REQUIRED_BITS = frozenset()
-
-    def __init__(self, **data):
-        self.data = data
-
-    def check_available(self, player):
-        return player.bits.check_bits(self.REQUIRED_BITS)
+    def generate_replacement_time(replacement_params):
+        if replacement_params is None:
+            return None
+        else:
+            if replacement_params['chance'] > random.random():
+                return random.randint(replacement_params['min'],
+                                      replacement_params['max'])
+            else:
+                return None
 
-    def perform_action(self, player, board):
-        raise NotImplementedError("TODO")
+    def timer_action(self, position, board):
+        if self.replacement_time is not None:
+            self.replacement_time -= 1
+            if self.replacement_time <= 0:
+                board.replace_card(position)