summaryrefslogtreecommitdiff
path: root/swiftstory/game.py
blob: c0eb59281a8eab9aef0b961c7dfea98760e67760 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
""" Module that defines the main component of the game. """

from enum import Enum, auto
import random
from typing import List, Optional, Tuple

from swiftstory.exception import WrongAction, JoinError
from swiftstory.player import Player
from swiftstory.board import Board
from swiftstory.status import error, success


class GameState(Enum):
    """ Enumeration of the different game states. """
    WAITING_NEW_JUDGE = auto()
    WAITING_COLLECTION = auto()
    WAITING_DESIGNATION = auto()


class Game:
    """ Represent a game, including the board, players and state. """
    def __init__(self, white_desc: List[str], black_desc: List[str]) -> None:

        self.state = GameState.WAITING_NEW_JUDGE

        self.players: List[Player] = []

        self.judge: Optional[Player] = None

        self.board = Board()
        self.board.white_pick = list(enumerate(white_desc))
        self.board.black_pick = list(enumerate(black_desc))

        random.shuffle(self.board.white_pick)
        random.shuffle(self.board.black_pick)

    def try_join(self, player: Player) -> str:
        """ Attempt to join the game. Return an answer. """
        if len(self.players) >= 10:
            raise JoinError('too many players in this game')

        cards: List[Tuple[int, str]] = []

        try:
            for _ in range(10):
                cards.append(self.board.pick_white_card())
        except IndexError:
            raise JoinError('not enough white cards for player')

        for card in cards:
            player.receive_card(card)

        self.players.append(player)

        for p in self.players:
            if p is not player:
                p.register_notification({'op': 'player_joined_game'})

        cards = [(idx, desc) for idx, (_, desc) in player.cards.items()]

        if self.state is GameState.WAITING_NEW_JUDGE:
            state = 'waiting_judge'
        elif self.state is GameState.WAITING_COLLECTION:
            state = 'waiting_collection'
        else:
            state = 'waiting_designation'

        return success({'cards': cards, 'game_state': state})


    def try_become_judge(self, player: Player) -> str:
        """ Attempt to become the judge of the game. Return an answer. """
        if self.state is not GameState.WAITING_NEW_JUDGE:
            # TODO what if the judge has quit ?
            raise WrongAction('Someone is judge already')

        self.judge = player
        self.board.reveal_next_black_card()

        self.state = GameState.WAITING_COLLECTION

        for p in self.players:
            if p is not player:
                p.register_notification({'op': 'judge_designed'})

        return self.try_view_black_card(player)


    def try_play_card(self, player: Player, card_id: int) -> str:
        """ Attempt to play a card. Return an answer. """
        if self.state is not GameState.WAITING_COLLECTION:
            raise WrongAction('Who asked you to play now ?!')

        if self.judge is player:
            raise WrongAction('You\'re the judge, you silly')
        elif player.has_played:
            raise WrongAction('You already played, you dumb ass')

        try:
            card = player.pop_card(card_id)
        except IndexError:
            raise WrongAction('Invalid card id')

        player.has_played = True

        self.board.play_card(player, card)

        if self.judge is None:
            raise ValueError("There is no judge")
        self.judge.register_notification({'op': 'card_played'})

        return success({'card_id': card_id})


    def try_collect_cards(self, player: Player) -> str:
        """ Attempt to collect the cards play in the current round. Return an
        answer. """
        if self.state is not GameState.WAITING_COLLECTION:
            raise WrongAction("Do you think it's the moment for collection !?")

        if self.judge is not player:
            raise WrongAction('You\'re not the judge, you fool!')

        self.board.shuffle_played_cards()

        # we prevent the others to play
        self.state = GameState.WAITING_DESIGNATION

        for p in self.players:
            if p is not player:
                p.register_notification({'op': 'cards_collected'})

        return self.try_view_played_cards(player)


    def try_designate_card(self, player: Player, card_id: Optional[int]) -> str:
        """ Attempt to designate the best card. Return an answer. """
        if self.state is not GameState.WAITING_DESIGNATION:
            raise WrongAction('Not now, moron !')

        if self.judge is not player:
            raise WrongAction('Who do you think you are !?')

        def move_on() -> str:
            self.judge = None

            for p in self.players:
                if p is not player:
                    p.register_notification({'op': 'judge_needed'})

            self.state = GameState.WAITING_NEW_JUDGE
            return success(None)

        if not self.board.played_cards:
            return move_on()

        if card_id is None:
            raise WrongAction('There are cards on the board, pick one !')

        # TODO check exception
        try:
            card, winner = self.board.played_cards[card_id]
        except IndexError:
            return error('Invalid card')

        winner.inc_score()

        # put the cards back in the deck
        self.board.recycle_played_cards()

        # reset the state of the players
        for p in self.players:
            if p.has_played:
                idx = p.receive_card(self.board.pick_white_card())

                p.register_notification({
                    'op': 'received_card',
                    'content': {
                        'card': {
                            'id': idx,
                            'desc': p.cards[idx][1],
                            },
                        },
                    })
                p.has_played = False

        return move_on()

    def try_view_player_cards(self, player: Player) -> str:
        """ Attempt to view the cards of the given player. Return an answer. """
        return success([(idx, desc) for idx, (_, desc) in player.cards.items()])

    def try_view_played_cards(self, player: Player) -> str:
        """ Attempt to view the cards that have been played. Return an answer.
        """
        if self.state is not GameState.WAITING_DESIGNATION:
            raise WrongAction('Not now, moron !')

        return success([desc for (_, desc), _ in self.board.played_cards])

    def try_view_black_card(self, player: Player) -> str:
        """ Attempt to view the black card. Return an answer. """
        card = self.board.current_black_card

        if card is not None:
            return success(card[1])

        raise WrongAction('The black card has not been revealed yet')

    def disconnect(self, player: Player) -> None:
        """ Deatch a player from the game. """
        if self.judge is player:
            self.judge = None

            for p in self.players:
                p.register_notification({'op': 'judge_needed'})

            for card, p in self.board.played_cards:
                p.receive_card(card)

                p.register_notification({
                    'op': 'received_card',
                    'content': {
                        'card': {
                            'id': card[0],
                            'desc': card[1],
                            },
                        },
                    })
                p.has_played = False

            self.board.played_cards = []
            self.state = GameState.WAITING_NEW_JUDGE