Handle a connection from the first player: start a new game.
(websocket)
| 86 | |
| 87 | |
| 88 | async def start(websocket): |
| 89 | """ |
| 90 | Handle a connection from the first player: start a new game. |
| 91 | |
| 92 | """ |
| 93 | # Initialize a Connect Four game, the set of WebSocket connections |
| 94 | # receiving moves from this game, and secret access tokens. |
| 95 | game = Connect4() |
| 96 | connected = {websocket} |
| 97 | |
| 98 | join_key = secrets.token_urlsafe(12) |
| 99 | JOIN[join_key] = game, connected |
| 100 | |
| 101 | watch_key = secrets.token_urlsafe(12) |
| 102 | WATCH[watch_key] = game, connected |
| 103 | |
| 104 | try: |
| 105 | # Send the secret access tokens to the browser of the first player, |
| 106 | # where they'll be used for building "join" and "watch" links. |
| 107 | event = { |
| 108 | "type": "init", |
| 109 | "join": join_key, |
| 110 | "watch": watch_key, |
| 111 | } |
| 112 | await websocket.send(json.dumps(event)) |
| 113 | # Receive and process moves from the first player. |
| 114 | await play(websocket, game, PLAYER1, connected) |
| 115 | finally: |
| 116 | del JOIN[join_key] |
| 117 | del WATCH[watch_key] |
| 118 | |
| 119 | |
| 120 | async def join(websocket, join_key): |