All puzzles to have cards without default actions.
[naja.git] / naja / gameboard.py
1 from random import choice
2
3 from naja.constants import(
4     BITS, DIRECTION_BITS, CONDITION_BITS, PLAYER_DEFAULTS,
5     ACT, EXAMINE, ROTATION)
6 from naja.options import options
7 from naja.player import Player
8 from naja import actions
9 from naja.sound import sound
10 import random
11
12
13 class GameBoard(object):
14     """
15     A representation of the game board.
16     """
17
18     def __init__(self, state, player, board_locations):
19         self.max_health = state['max_health']
20         self.wins_required = state['wins_required']
21         self.health = state['health']
22         self.wins = state['wins']
23         self.locations = [item.copy() for item in state['locations']]
24         self.puzzle = state.get('puzzle', False)
25         self.player = player
26         self.board_locations = board_locations
27         self.player_mode = state.get('player_mode', EXAMINE)
28         self.has_cheated = state.get('cheater', options.cheat_enabled)
29         self.clock_count = state.get('clock_count', 0)
30         self.replacement_params = state.get('replacement_params', None)
31
32     @classmethod
33     def new_game(cls, deck, initial_bits=None, initial_pos=None,
34                  max_health=None, wins_required=None):
35
36         defaults = {
37             'initial_bits': PLAYER_DEFAULTS.INITIAL_BITS,
38             'initial_pos': PLAYER_DEFAULTS.INITIAL_POS,
39             'max_health': PLAYER_DEFAULTS.MAX_HEALTH,
40             'wins_required': PLAYER_DEFAULTS.WINS_REQUIRED,
41         }
42
43         puzzle = deck.get('puzzle', False)
44
45         if puzzle:
46             puzzle_defaults = deck.get('defaults', {})
47             for k, v in puzzle_defaults.iteritems():
48                 if isinstance(v, list):
49                     puzzle_defaults[k] = [int(x) for x in v]
50                 else:
51                     puzzle_defaults[k] = int(v)
52             defaults.update(puzzle_defaults)
53
54         if initial_bits is None:
55             initial_bits = defaults['initial_bits']
56         if initial_pos is None:
57             initial_pos = defaults['initial_pos']
58         if max_health is None:
59             max_health = defaults['max_health']
60         if wins_required is None:
61             wins_required = defaults['wins_required']
62
63         # Overriden by command line
64         if options.initial_bits:
65             initial_bits = options.initial_bits
66
67         state = {
68             'max_health': max_health,
69             'health': max_health,
70             'wins_required': wins_required,
71             'wins': 0,
72             'locations': deck['cards'],
73             'puzzle': puzzle,
74             'clock_count': 0,
75             'replacement_params': deck.get('replacement_params', None),
76         }
77         player = Player(initial_bits, initial_pos)
78         board_locations = cls.import_board_locations(
79             cls.generate_board(deck))
80         board = cls(state, player, board_locations)
81         player.set_gameboard(board)
82         return board
83
84     @classmethod
85     def import_game(cls, definition):
86         state = definition.copy()
87         player = Player.import_player(state.pop('player'))
88         board_locations = cls.import_board_locations(
89             state.pop('board_locations'))
90         return cls(state, player, board_locations)
91
92     def export(self):
93         data = {
94             'max_health': self.max_health,
95             'health': self.health,
96             'wins_required': self.wins_required,
97             'wins': self.wins,
98             'locations': [item.copy() for item in self.locations],
99             'puzzle': self.puzzle,
100             'player': self.player.export(),
101             'board_locations': self.export_board_locations(),
102             'player_mode': self.player_mode,
103             'clock_count': self.clock_count,
104             'replacement_params': self.replacement_params,
105         }
106         if options.cheat_enabled:
107             self.has_cheated = True
108         if self.has_cheated:
109             data['cheater'] = True
110         return data
111
112     @classmethod
113     def import_locations(cls, locations_definition):
114         return [
115             LocationCard.import_location(definition)
116             for definition in locations_definition]
117
118     def export_board_locations(self):
119         return sorted(
120             (position, location.export())
121             for position, location in self.board_locations.iteritems())
122
123     @classmethod
124     def import_board_locations(cls, board_locations_definition):
125         return dict(
126             (tuple(position), LocationCard.import_location(definition))
127             for position, definition in board_locations_definition)
128
129     @classmethod
130     def generate_board(cls, deck):
131         if deck.get('puzzle', False):
132             return cls.generate_puzzle_board(deck)
133         else:
134             return cls.generate_random_board(deck)
135
136     @classmethod
137     def generate_puzzle_board(cls, deck):
138         assert len(deck['cards']) == 5 * 5
139         replacement_params = deck.get('replacement_params', None)
140         board_locations = [
141             [(i % 5, i // 5),
142              LocationCard.new_location(
143                  card.copy(), replacement_params, puzzle=True).export()]
144             for i, card in enumerate(deck['cards'])
145         ]
146         return board_locations
147
148     @classmethod
149     def generate_random_board(cls, deck):
150         board_locations = []
151         replacement_params = deck.get('replacement_params', None)
152         for x in range(5):
153             for y in range(5):
154                 new_choice = cls.choose_card(deck['cards'], board_locations)
155                 board_location = LocationCard.new_location(
156                     new_choice.copy(), replacement_params)
157                 board_locations.append([(x, y), board_location.export()])
158         return board_locations
159
160     def lose_health(self):
161         self.health -= 1
162         if self.health <= 0:
163             self.end_game(win=False)
164
165     def gain_health(self):
166         if self.health < self.max_health:
167             self.health += 1
168
169     def acquire_win_token(self):
170         self.wins += 1
171         if self.wins >= self.wins_required:
172             self.end_game(win=True)
173
174     def card_used(self, position):
175         if not self.puzzle:
176             self.replace_card(position)
177
178     def replace_card(self, position):
179         new_choice = self.choose_card(self.locations,
180                                       self.board_locations.items(),
181                                       position)
182         location = LocationCard.new_location(new_choice.copy(),
183                                              self.replacement_params)
184         self.board_locations[position] = location
185
186     @classmethod
187     def choose_card(cls, cards, board_locations, position=None):
188         # Find which cards are at their maximum and exclude them from
189         # the choice list
190         counts = {}
191         choices = {card['card_name']: card for card in cards}
192         for pos, card in board_locations:
193             if pos == position:
194                 # skip the card we're replacing if appropriate
195                 continue
196             if isinstance(card, LocationCard):
197                 key = card.card_name
198                 max_num = card.max_number
199             else:
200                 key = card['card_name']
201                 max_num = card.get('max_number', 25)
202             counts.setdefault(key, 0)
203             counts[key] += 1
204             if counts[key] >= max_num:
205                 if key in choices:
206                     del choices[key]
207         return choice(choices.values())
208
209     def shift_location_row(self, change, is_vertical):
210         px, py = self.player.position
211         shifted_locations = {}
212         mkpos = lambda i: (px, i) if is_vertical else (i, py)
213
214         for i in range(5):
215             if (px, py) == mkpos(i):
216                 continue
217             new_i = (i + change) % 5
218             if (px, py) == mkpos(new_i):
219                 new_i = (new_i + change) % 5
220             shifted_locations[mkpos(new_i)] = self.board_locations[mkpos(i)]
221
222         self.board_locations.update(shifted_locations)
223
224     def shift_locations(self, direction):
225         if BITS[direction] == BITS.NORTH:
226             self.shift_location_row(-1, is_vertical=True)
227         elif BITS[direction] == BITS.SOUTH:
228             self.shift_location_row(1, is_vertical=True)
229         elif BITS[direction] == BITS.EAST:
230             self.shift_location_row(1, is_vertical=False)
231         elif BITS[direction] == BITS.WEST:
232             self.shift_location_row(-1, is_vertical=False)
233
234     def rotate_locations(self, direction):
235         px, py = self.player.position
236         locations_to_rotate = []
237         rotated_locations = {}
238
239         if py > 0:
240             for i in range(max(0, px - 1), min(5, px + 2)):
241                 locations_to_rotate.append((i, py - 1))
242
243         if px < 4:
244             locations_to_rotate.append((px + 1, py))
245
246         if py < 4:
247             for i in reversed(range(max(0, px - 1), min(5, px + 2))):
248                 locations_to_rotate.append((i, py + 1))
249
250         if px > 0:
251             locations_to_rotate.append((px - 1, py))
252
253         if ROTATION[direction] == ROTATION.CLOCKWISE:
254             new_positions = locations_to_rotate[1:] + [locations_to_rotate[0]]
255         elif ROTATION[direction] == ROTATION.ANTICLOCKWISE:
256             new_positions = (
257                 [locations_to_rotate[-1]] + locations_to_rotate[:-1])
258
259         for old, new in zip(locations_to_rotate, new_positions):
260             rotated_locations[new] = self.board_locations[old]
261
262         self.board_locations.update(rotated_locations)
263
264     def allow_chess_move(self, chesspiece):
265         self.player.allow_chess_move(chesspiece)
266
267     def change_mode(self, new_mode):
268         """Advance to the next mode"""
269         if new_mode == self.player_mode:
270             raise RuntimeError("Inconsistent state. Setting mode %s to itself"
271                                % self.player_mode)
272         elif new_mode in (ACT, EXAMINE):
273             self.player_mode = new_mode
274             if new_mode is EXAMINE:
275                 self.board_update()
276         else:
277             raise RuntimeError("Illegal player mode %s" % self.player_mode)
278
279     def board_update(self):
280         self.clock_count += 1
281         for position, location in self.board_locations.iteritems():
282             location.timer_action(position, self)
283
284     def end_game(self, win):
285         # TODO: Find a way to not have UI stuff in game logic stuff.
286         from naja.events import SceneChangeEvent
287         from naja.scenes.lose import LoseScene
288         from naja.scenes.win import WinScene
289         sound.stop()
290         if win:
291             SceneChangeEvent.post(WinScene)
292         else:
293             SceneChangeEvent.post(LoseScene)
294
295
296 class LocationCard(object):
297     """
298     A particular set of options available on a location.
299     """
300
301     def __init__(self, card_name, bitwise_operand, location_actions,
302                  replacement_time=None, max_number=25):
303         self.card_name = card_name
304         self.bitwise_operand = bitwise_operand
305         self.actions = location_actions
306         self.max_number = max_number
307         self.replacement_time = replacement_time
308
309     @classmethod
310     def import_location(cls, state):
311         location_actions = [
312             cls.build_action(definition) for definition in state['actions']]
313         return cls(state['card_name'], state['bitwise_operand'],
314                    location_actions, state['replacement_time'],
315                    state['max_number'])
316
317     @classmethod
318     def build_action(cls, definition):
319         action_class = getattr(actions, definition['action_class'])
320         required_bits = cls.parse_bits(definition['required_bits'])
321         data = definition.get('data', {})
322         return action_class(required_bits, **data)
323
324     @classmethod
325     def new_location(cls, definition, replacement_params=None, puzzle=False):
326         if 'bits' in definition:
327             bits = cls.parse_bits(definition['bits'])
328         else:
329             bits = cls.generate_bitwise_operand()
330
331         if 'replacement_time' in definition:
332             replacement_time = definition['replacement_time']
333         else:
334             replacement_time = cls.generate_replacement_time(
335                 replacement_params)
336
337         max_number = definition.get('max_number', 25)
338         card_name = definition['card_name']
339         location = cls.import_location({
340             'bitwise_operand': bits,
341             'actions': definition['actions'],
342             'max_number': max_number,
343             'card_name': card_name,
344             'replacement_time': replacement_time,
345         })
346         if not puzzle:
347             location.check_actions()
348         return location
349
350     @classmethod
351     def parse_bits(self, bit_list):
352         # Convert names to numbers if applicable.
353         return frozenset(BITS.get(bit, bit) for bit in bit_list)
354
355     def export(self):
356         return {
357             'bitwise_operand': sorted(self.bitwise_operand),
358             'actions': [action.export() for action in self.actions],
359             'max_number': self.max_number,
360             'card_name': self.card_name,
361             'replacement_time': self.replacement_time,
362         }
363
364     def check_actions(self):
365         if not self.actions:
366             print "Warning: Location has no actions."
367             self.insert_default_default_action()
368         if self.actions[0].required_bits:
369             self.insert_default_default_action()
370
371     def insert_default_default_action(self):
372         self.actions.insert(0, self.build_action({
373             'action_class': 'DoNothing',
374             'required_bits': [],
375         }))
376
377     @staticmethod
378     def generate_bitwise_operand():
379         """
380         Generate a set of two or three bits. At least one direction and one
381         condition bit will be included. There is a low probability of choosing
382         a third bit from the complete set.
383         """
384         bits = set()
385         bits.add(choice(DIRECTION_BITS.values()))
386         bits.add(choice(CONDITION_BITS.values()))
387         # One in three chance of adding a third bit, with a further one in four
388         # chance that it will match a bit already chosen.
389         if choice(range(3)) == 0:
390             bits.add(choice(BITS.values()))
391         return frozenset(bits)
392
393     @staticmethod
394     def generate_replacement_time(replacement_params):
395         if replacement_params is None:
396             return None
397         else:
398             if replacement_params['chance'] > random.random():
399                 return random.randint(replacement_params['min'],
400                                       replacement_params['max'])
401             else:
402                 return None
403
404     def timer_action(self, position, board):
405         if self.replacement_time is not None:
406             self.replacement_time -= 1
407             if self.replacement_time <= 0:
408                 board.replace_card(position)