#!/usr/bin/env python3 import argparse import asyncio import contextlib import json import websockets import swiftstory.GameManager from swiftstory.Client import Client from swiftstory.Status import error game_manager = swiftstory.GameManager.GameManager() def message_received_handler(client, message): try: json_msg = json.loads(message) except JSONDecodeError: return error('badly formatted json') op = json_msg['op'] if op == 'join_game': try: game_name = json_msg['game_name'] except KeyError: return error('field `game_name\' is required') 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': card_id = None try: card_id = int(json_msg['card_id']) except (KeyError, TypeError): pass finally: return client.designate_card(card_id) elif op == '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: return error('invalid command') async def swiftstory(websocket, path): client = Client(websocket, game_manager) with contextlib.suppress(websockets.exceptions.ConnectionClosed): async for message in client.socket: await client.socket.send(message_received_handler(client, message)) client.disconnect() def main(): parser = argparse.ArgumentParser() parser.add_argument('--listen', type=str, default='0.0.0.0') parser.add_argument('--port', type=int, default=1236) args = vars(parser.parse_args()) start_server = websockets.serve(swiftstory, args['listen'], args['port']) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() if __name__ == '__main__': main()