Download app.py from Bubaa001/Fast2: direct link, hf CLI and curl.
- Browser
- Download file 2.23 kB
-
https://huggingface.co/spaces/Bubaa001/Fast2/resolve/main/app.py
- Command line
-
hf download hf://spaces/Bubaa001/Fast2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Bubaa001/Fast2/resolve/main/app.py
2.23 kB
| 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 | |
| async def get(): | |
| with open("index.html", "r") as f: | |
| return HTMLResponse(f.read()) | |
| # WebSocket endpoint | |
| 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) |