Files
fairhopper/hopper/ws_client.py
2023-03-25 15:27:15 +01:00

32 lines
894 B
Python

import json
from contextlib import asynccontextmanager
import websockets
from hopper.api.dependencies import get_game_engine
from hopper.models.ws_dto import GameStateDto
from settings import settings
@asynccontextmanager
async def create_ws_client() -> websockets.WebSocketServerProtocol:
ws_uri = f"ws://{settings.ws_server.HOST}:{settings.ws_server.PORT}"
async with websockets.connect(uri=ws_uri) as websocket:
yield websocket
async def send_game_state() -> None:
async with create_ws_client() as websocket:
engine = get_game_engine()
game_state = GameStateDto(
board=engine.board,
destination=engine.board.destination,
players=engine.players,
layers=engine.board.layers,
)
print(json.dumps(game_state.dict(), indent=4))
await websocket.send(json.dumps(game_state.dict()))