93 lines
3.0 KiB
Python
93 lines
3.0 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from .story_engine import StoryEngine
|
|
from services.persistence import SQLitePersistence
|
|
|
|
|
|
class StateManager:
|
|
def __init__(self, persistence: SQLitePersistence, story_engine: StoryEngine):
|
|
self.persistence = persistence
|
|
self.story_engine = story_engine
|
|
|
|
def create_new_room(
|
|
self,
|
|
room_id: str,
|
|
host_player_id: str,
|
|
host_name: str,
|
|
*,
|
|
host_user_id: str | None = None,
|
|
game_card: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
state = self.story_engine.initial_state(
|
|
room_id,
|
|
[host_player_id],
|
|
game_card=game_card,
|
|
).to_dict()
|
|
game_card_id = (game_card or {}).get("card_id", "fogharbor")
|
|
self.persistence.create_room(room_id, host_player_id, state, game_card_id=game_card_id)
|
|
self.persistence.add_or_update_player(
|
|
room_id,
|
|
host_player_id,
|
|
host_name,
|
|
is_host=True,
|
|
is_ready=False,
|
|
is_online=True,
|
|
user_id=host_user_id,
|
|
)
|
|
return state
|
|
|
|
def add_player(
|
|
self,
|
|
room_id: str,
|
|
player_id: str,
|
|
name: str,
|
|
is_host: bool = False,
|
|
*,
|
|
user_id: str | None = None,
|
|
) -> dict[str, Any]:
|
|
room = self.persistence.get_room(room_id)
|
|
if room is None:
|
|
raise ValueError("room_not_found")
|
|
|
|
game_state = room["game_state"]
|
|
game_state.setdefault("inventory_by_player", {})
|
|
game_state["inventory_by_player"].setdefault(player_id, [])
|
|
global_flags = game_state.get("global_flags", {})
|
|
if isinstance(global_flags, dict):
|
|
player_states = global_flags.get("player_states", {})
|
|
if not isinstance(player_states, dict):
|
|
player_states = {}
|
|
player_states[player_id] = {
|
|
"status": "alive",
|
|
"is_alive": True,
|
|
"deaths": 0,
|
|
"revives": 0,
|
|
"last_event": "join",
|
|
"updated_at": game_state.get("last_updated_at") or "",
|
|
}
|
|
global_flags["player_states"] = player_states
|
|
|
|
self.persistence.add_or_update_player(
|
|
room_id,
|
|
player_id,
|
|
name,
|
|
is_host=is_host,
|
|
is_ready=False,
|
|
is_online=True,
|
|
user_id=user_id,
|
|
)
|
|
self.persistence.update_room_state(room_id, room["status"], game_state)
|
|
return game_state
|
|
|
|
def get_room_state(self, room_id: str) -> tuple[dict[str, Any], list[dict[str, Any]], str] | None:
|
|
room = self.persistence.get_room(room_id)
|
|
if room is None:
|
|
return None
|
|
players = self.persistence.list_players(room_id)
|
|
return room["game_state"], players, room["status"]
|
|
|
|
def set_room_state(self, room_id: str, status: str, state: dict[str, Any]) -> None:
|
|
self.persistence.update_room_state(room_id, status, state)
|