diff options
Diffstat (limited to 'swiftstory')
-rw-r--r-- | swiftstory/SwiftStory.py | 50 |
1 files changed, 26 insertions, 24 deletions
diff --git a/swiftstory/SwiftStory.py b/swiftstory/SwiftStory.py index dc55e2a..b7dbb6d 100644 --- a/swiftstory/SwiftStory.py +++ b/swiftstory/SwiftStory.py @@ -14,18 +14,9 @@ from swiftstory.Status import error game_manager = swiftstory.GameManager.GameManager() -def message_received_handler(client, message): - try: - json_msg = json.loads(message) - except json.JSONDecodeError: - return error('badly formatted json') - try: - op = json_msg['op'] - except (KeyError, TypeError): - op = None - - if op == 'join_game': +def message_received_handler(client, message): + def join_game(): try: game_name = json_msg['game_name'] except KeyError: @@ -33,15 +24,8 @@ def message_received_handler(client, message): else: lang = json_msg.get('lang') return client.join_game(game_name, lang) - elif op == 'view_player_cards': - return client.view_player_cards() - elif op == 'view_black_card': - return client.view_black_card() - elif op == 'view_played_cards': - return client.view_played_cards() - elif op == 'pick_black_card': - return client.pick_black_card() - elif op == 'designate_card': + + def designate_card(): card_id = None try: card_id = int(json_msg['card_id']) @@ -49,16 +33,34 @@ def message_received_handler(client, message): pass finally: return client.designate_card(card_id) - elif op == 'play_white_card': + + def play_white_card(): try: card_id = int(json_msg['card_id']) except KeyError: return error('field `card_id\' is required') else: return client.play_white_card(card_id) - elif op == 'collect_cards': - return client.collect_cards() - else: + + opcodes_map = { + "join_game": join_game, + "view_player_cards": lambda: client.view_player_cards(), + "view_black_card": lambda: client.view_black_card(), + "view_played_cards": lambda: client.view_played_cards(), + "pick_black_card": lambda: client.pick_black_card(), + "collect_cards": lambda: client.collect_cards(), + "designate_card": designate_card, + "play_white_card": play_white_card, + } + + try: + json_msg = json.loads(message) + except json.JSONDecodeError: + return error('badly formatted json') + + try: + return opcodes_map[json_msg["op"]]() + except (KeyError, TypeError): return error('invalid command') |