Receive and process moves from a player.
(websocket, game, player, connected)
| 49 | |
| 50 | |
| 51 | async def play(websocket, game, player, connected): |
| 52 | """ |
| 53 | Receive and process moves from a player. |
| 54 | |
| 55 | """ |
| 56 | async for message in websocket: |
| 57 | # Parse a "play" event from the UI. |
| 58 | event = json.loads(message) |
| 59 | assert event["type"] == "play" |
| 60 | column = event["column"] |
| 61 | |
| 62 | try: |
| 63 | # Play the move. |
| 64 | row = game.play(player, column) |
| 65 | except ValueError as exc: |
| 66 | # Send an "error" event if the move was illegal. |
| 67 | await error(websocket, str(exc)) |
| 68 | continue |
| 69 | |
| 70 | # Send a "play" event to update the UI. |
| 71 | event = { |
| 72 | "type": "play", |
| 73 | "player": player, |
| 74 | "column": column, |
| 75 | "row": row, |
| 76 | } |
| 77 | broadcast(connected, json.dumps(event)) |
| 78 | |
| 79 | # If move is winning, send a "win" event. |
| 80 | if game.winner is not None: |
| 81 | event = { |
| 82 | "type": "win", |
| 83 | "player": game.winner, |
| 84 | } |
| 85 | broadcast(connected, json.dumps(event)) |
| 86 | |
| 87 | |
| 88 | async def start(websocket): |