File size: 2,229 Bytes
7bfbe49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
import uvicorn
import json
import asyncio

app = FastAPI()

# WebSocket connections manager
class ConnectionManager:
    def __init__(self):
        self.active_connections = {}

    async def connect(self, websocket: WebSocket, player_id: str):
        await websocket.accept()
        self.active_connections[player_id] = websocket

    def disconnect(self, player_id: str):
        if player_id in self.active_connections:
            del self.active_connections[player_id]

    async def broadcast(self, message: dict):
        for connection in self.active_connections.values():
            try:
                await connection.send_json(message)
            except:
                self.disconnect(connection)

manager = ConnectionManager()

# Game state
game_state = {
    "players": {},
    "fruits": [],
    "obstacles": []
}

# Serve HTML
@app.get("/")
async def get():
    with open("index.html", "r") as f:
        return HTMLResponse(f.read())

# WebSocket endpoint
@app.websocket("/ws/{player_id}")
async def websocket_endpoint(websocket: WebSocket, player_id: str):
    await manager.connect(websocket, player_id)
    
    # Initialize player
    game_state["players"][player_id] = {
        "x": 0,
        "y": 0,
        "direction": "right",
        "length": 3,
        "score": 0
    }

    try:
        while True:
            data = await websocket.receive_text()
            message = json.loads(data)
            
            # Update player direction
            if message["type"] == "direction":
                game_state["players"][player_id]["direction"] = message["direction"]
            
            # Broadcast game state to all players
            await manager.broadcast({
                "type": "game_state",
                "state": game_state
            })
            
    except WebSocketDisconnect:
        manager.disconnect(player_id)
        del game_state["players"][player_id]
        await manager.broadcast({
            "type": "player_disconnected",
            "player_id": player_id
        })

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)