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