34 lines
1.0 KiB
Python
34 lines
1.0 KiB
Python
import json
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
import websockets
|
|
|
|
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 ws_send_game_state() -> None:
|
|
# avoid circular imports
|
|
from hopper.api.dependencies import get_game_engine
|
|
|
|
try:
|
|
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.get_board_layout().layers,
|
|
)
|
|
await websocket.send(json.dumps(game_state.dict()))
|
|
except OSError as ex:
|
|
logging.error(f"Error sending WS state: {ex}") |