-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
73 lines (62 loc) · 2.62 KB
/
app.py
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
import asyncio
import json
from typing import cast
from uuid import uuid4
import nest_asyncio
from websockets.server import WebSocketServerProtocol, serve
from paper_tactics.adapters.in_memory_game_repository import InMemoryGameRepository
from paper_tactics.adapters.in_memory_match_request_queue import (
InMemoryMatchRequestQueue,
)
from paper_tactics.adapters.stdout_logger import StdoutLogger
from paper_tactics.adapters.websockets_player_notifier import WebsocketsPlayerNotifier
from paper_tactics.entities.cell import Cell
from paper_tactics.entities.game_preferences import GamePreferences
from paper_tactics.entities.match_request import MatchRequest
from paper_tactics.use_cases.concede import concede
from paper_tactics.use_cases.create_game import create_game
from paper_tactics.use_cases.make_turn import make_turn
nest_asyncio.apply()
game_repository = InMemoryGameRepository()
match_request_queue = InMemoryMatchRequestQueue()
player_notifier = WebsocketsPlayerNotifier()
logger = StdoutLogger()
async def handler(websocket: WebSocketServerProtocol) -> None:
async for message in websocket:
try:
event = json.loads(message)
except json.JSONDecodeError as e:
logger.log_exception(e)
return
if event.get("action") == "create-game":
preferences = GamePreferences(**event.get("preferences", {}))
request = MatchRequest(uuid4().hex, event.get("view_data", {}), preferences)
player_notifier.websockets[request.id] = websocket
create_game(
game_repository, match_request_queue, player_notifier, logger, request
)
elif event.get("action") == "make-turn":
try:
player_id = player_notifier.websockets.inverse[websocket]
game_id = event["gameId"]
cell = cast(Cell, tuple(event["cell"]))
assert len(cell) == 2
except Exception as e:
logger.log_exception(e)
return
make_turn(
game_repository, player_notifier, logger, game_id, player_id, cell
)
elif event.get("action") == "concede":
try:
player_id = player_notifier.websockets.inverse[websocket]
game_id = event["gameId"]
except Exception as e:
logger.log_exception(e)
return
concede(game_repository, player_notifier, logger, game_id, player_id)
async def main() -> None:
async with serve(handler, "", 8001):
await asyncio.Future()
if __name__ == "__main__":
asyncio.run(main())