Python Server (`server.
py`):
import asyncio
import websockets
import random
import json
# Snakes and ladders mapping
snakes_ladders = {16:6, 48:30, 64:60, 79:19, 93:68, 95:24, 97:76,
1:38, 4:14, 9:31, 21:42, 28:84, 36:44, 51:67, 71:91, 80:100}
players = {} # websocket -> position
turn_order = []
current_turn = 0
async def handler(ws):
global current_turn
# Add new player
players[ws] = 0
turn_order.append(ws)
await [Link]([Link]({"type":"welcome","pos":0}))
```
try:
async for message in ws:
data = [Link](message)
if data["type"] == "roll":
if ws != turn_order[current_turn]:
await [Link]([Link]({"type":"error","msg":"Not your turn!"}))
continue
dice = [Link](1,6)
pos = players[ws] + dice
if pos > 100:
pos = players[ws] # cannot go beyond 100
pos = snakes_ladders.get(pos,pos)
players[ws] = pos
# Broadcast update
for p in players:
await [Link]([Link]({
"type":"update",
"player":list([Link]()).index(ws),
"pos":pos,
"dice":dice
}))
# Check win
if pos == 100:
for p in players:
await
[Link]([Link]({"type":"win","player":list([Link]()).index(ws)}))
[Link]()
turn_order.clear()
return
# Next turn
current_turn = (current_turn + 1) % len(turn_order)
finally:
if ws in players:
del players[ws]
```