0% found this document useful (0 votes)
28 views2 pages

WebSocket Snakes and Ladders Game in Python

The document contains a Python WebSocket server implementation for a Snakes and Ladders game. It manages player connections, handles dice rolls, updates player positions based on the game rules, and broadcasts game state changes to all players. The server also checks for a win condition and resets the game when a player reaches the end.

Uploaded by

rj.kamez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views2 pages

WebSocket Snakes and Ladders Game in Python

The document contains a Python WebSocket server implementation for a Snakes and Ladders game. It manages player connections, handles dice rolls, updates player positions based on the game rules, and broadcasts game state changes to all players. The server also checks for a win condition and resets the game when a player reaches the end.

Uploaded by

rj.kamez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

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]
```

You might also like