Add win token action.
[naja.git] / naja / actions.py
1 from naja.constants import BITS
2
3
4 class LocationAction(object):
5     """
6     An action that may be performed on a location.
7     """
8
9     TEXT = None
10     USES_MSB = False
11
12     def __init__(self, required_bits, **data):
13         bits = set()
14         for bit in required_bits:
15             # Convert names to numbers if applicable.
16             bits.add(BITS.get(bit, bit))
17         self.required_bits = frozenset(bits)
18         self.data = data
19
20     def check_available(self, player):
21         return player.bits.check_bits(self.required_bits)
22
23     def perform_action(self, board, location):
24         raise NotImplementedError("TODO")
25
26     def check_and_clear_MSB(self, player):
27         if player.bits.check_bit(BITS.MSB):
28             player.bits.clear_bit(BITS.MSB)
29             return True
30         else:
31             return False
32
33     def export(self):
34         return {'required_bits': list(self.required_bits),
35                 'data': self.data,
36                 'action_class': self.__class__.__name__}
37
38
39 class DoNothing(LocationAction):
40     TEXT = "No effect."
41
42     def perform_action(self, board, location):
43         pass
44
45
46 class LoseHealthOrMSB(LocationAction):
47     TEXT = "Lose health or MSB."
48     USES_MSB = True
49
50     def perform_action(self, board, location):
51         if not self.check_and_clear_MSB(board.player):
52             board.lose_health()
53
54
55 class SetBits(LocationAction):
56     TEXT = "Set bits specified by this location."
57
58     def perform_action(self, board, location):
59         board.player.bits.set_bits(location.bitwise_operand)
60
61
62 class ToggleBits(LocationAction):
63     TEXT = "Toggle bits specified by this location."
64
65     def perform_action(self, board, location):
66         board.player.bits.toggle_bits(location.bitwise_operand)
67
68
69 class LoseHealthOrMSBAndSetBits(LocationAction):
70     TEXT = "Lose health or MSB, then set bits specified by this location."
71     USES_MSB = True
72
73     def perform_action(self, board, location):
74         if not self.check_and_clear_MSB(board.player):
75             board.lose_health()
76         board.player.bits.set_bits(location.bitwise_operand)
77
78
79 class AcquireWinToken(LocationAction):
80     TEXT = "Acquire a win token, then clear all high bits."
81     USES_MSB = True
82
83     def perform_action(self, board, location):
84         if self.check_and_clear_MSB(board.player):
85             board.acquire_win_token()
86             board.player.bits.clear_bits(set([
87                 BITS.CYAN, BITS.MAGENTA, BITS.YELLOW,
88             ]))