Živý režim po vzoru Kahootu (OpenSpec změna `zivy-rezim-trida`, nová capability `live-room`). - Schválená učitelka založí nad publikovanou sadou místnost (režim Psaní / Výběr A–D, délka, časový limit); tabule ukáže 6místný kód a QR. - Připojení kódem a přezdívkou; přihlášeným se kola zapisují do DB a žebříčků, ostatní mají body jen v místnosti. - Synchronní průběh řízený učitelkou: otázka končí limitem nebo odpovědí všech, pak vyhodnocení a průběžné pořadí, na konci stupně vítězů. - Bodování shodné s běžnou hrou včetně bonusu za sérii. - Moderace (vyhození hráče, zamčení místnosti), rate limit neúspěšných pokusů o kód podle session i IP, aktualizace pollingem. - Specifikace synchronizovány do `openspec/specs/live-room/`, změna archivována. Closes #23 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_013nPfHY7UqPQTQpoHNjSQ4K Reviewed-on: #27 Co-authored-by: David Spáčil <spacildavi@gmail.com>
943 lines
32 KiB
Python
943 lines
32 KiB
Python
"""Živá místnost pro třídu: stav v paměti, líné přechody fází a body.
|
||
|
||
Místnosti drží jeden proces pod jedním zámkem (vzor `game_state`). Přechody
|
||
fází se vyhodnocují líně při každém volání podle monotónních hodin, žádné
|
||
vlákno ani časovač neběží. Zápisy do DB (mistrovství, kola) se jen řadí do
|
||
fronty a vykoná je volající mimo zámek přes `drain_writes()`.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import random
|
||
import secrets
|
||
import threading
|
||
import time
|
||
from collections.abc import Callable, Mapping, Sequence
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Literal
|
||
|
||
from poznavacky.game_state import (
|
||
InvalidAnswerError,
|
||
RoundAnswerRecord,
|
||
RoundQuestion,
|
||
RoundRecord,
|
||
RoundType,
|
||
prepare_questions,
|
||
to_item_spec,
|
||
)
|
||
from poznavacky.scoring import (
|
||
AnswerItemSpec,
|
||
AnswerVerdict,
|
||
GameMode,
|
||
ScoringConfig,
|
||
calculate_question_score,
|
||
calculate_round_max_points,
|
||
calculate_weighted_accuracy,
|
||
evaluate_writing_answer,
|
||
)
|
||
|
||
LivePhase = Literal["lobby", "priprava", "otazka", "vyhodnoceni", "konec"]
|
||
BoardAction = Literal[
|
||
"start",
|
||
"dalsi",
|
||
"ukoncit-otazku",
|
||
"ukoncit-hru",
|
||
"zamknout",
|
||
"odemknout",
|
||
"vyhodit",
|
||
]
|
||
|
||
PREPARE_SECONDS = 3.0
|
||
ROOM_TTL_SECONDS = 7200.0
|
||
ENDED_TTL_SECONDS = 900.0
|
||
MAX_PLAYERS = 60
|
||
NICKNAME_MAX_LENGTH = 20
|
||
CODE_DIGITS = 6
|
||
TIME_LIMITS: tuple[int, ...] = (10, 20, 30, 45, 60)
|
||
DEFAULT_TIME_LIMITS: Mapping[str, int] = {"abcd": 30, "psani": 45}
|
||
TOP_COUNT = 5
|
||
PODIUM_COUNT = 3
|
||
BOARD_ACTIONS: frozenset[str] = frozenset(
|
||
{
|
||
"start",
|
||
"dalsi",
|
||
"ukoncit-otazku",
|
||
"ukoncit-hru",
|
||
"zamknout",
|
||
"odemknout",
|
||
"vyhodit",
|
||
}
|
||
)
|
||
|
||
|
||
class LiveRoomError(Exception):
|
||
"""Základní chyba operace nad živou místností."""
|
||
|
||
|
||
class RoomNotFoundError(LiveRoomError):
|
||
"""Místnost s daným kódem či id neexistuje, zanikla nebo skončila."""
|
||
|
||
|
||
class RoomForbiddenError(LiveRoomError):
|
||
"""K místnosti nebo hráči nemá volající přístup."""
|
||
|
||
|
||
class RoomConflictError(LiveRoomError):
|
||
"""Operace neodpovídá aktuální fázi místnosti."""
|
||
|
||
|
||
class JoinRejectedError(LiveRoomError):
|
||
"""Připojení do existující místnosti bylo odmítnuto (důvod ve zprávě)."""
|
||
|
||
|
||
class PlayerKickedError(RoomForbiddenError):
|
||
"""Hráč byl z místnosti vyhozen."""
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class LiveAnswer:
|
||
"""Vyhodnocená (nebo propadlá) odpověď hráče na jednu otázku."""
|
||
|
||
question_index: int
|
||
verdict: AnswerVerdict
|
||
reason: str
|
||
submitted_text: str
|
||
selected_option_index: int | None
|
||
reaction_time_ms: int
|
||
points: int
|
||
streak_bonus: int
|
||
streak_after: int
|
||
answered: bool
|
||
|
||
|
||
@dataclass
|
||
class LivePlayer:
|
||
"""Hráč v místnosti navázaný na session."""
|
||
|
||
player_id: str
|
||
session_key: str
|
||
user_id: int | None
|
||
name: str
|
||
first_question_index: int
|
||
join_order: int
|
||
score: int = 0
|
||
streak: int = 0
|
||
best_streak: int = 0
|
||
kicked: bool = False
|
||
answers: dict[int, LiveAnswer] = field(default_factory=dict)
|
||
|
||
def plays(self, question_index: int) -> bool:
|
||
"""Zda hráč hraje danou otázku (pozdní příchod ji vynechá)."""
|
||
return not self.kicked and question_index >= self.first_question_index
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class MasteryWrite:
|
||
"""Úloha: aktualizovat mistrovství po uzavření otázky."""
|
||
|
||
user_id: int
|
||
item_id: int
|
||
mode: GameMode
|
||
verdict: AnswerVerdict
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class RoundWrite:
|
||
"""Úloha: zapsat dohrané kolo přihlášeného hráče."""
|
||
|
||
record: RoundRecord
|
||
|
||
|
||
PendingWrite = MasteryWrite | RoundWrite
|
||
|
||
|
||
@dataclass
|
||
class LiveRoom:
|
||
"""Serverový stav jedné živé místnosti."""
|
||
|
||
room_id: str
|
||
code: str
|
||
owner_user_id: int
|
||
sada_id: int
|
||
sada_slug: str
|
||
sada_nazev: str
|
||
mode: GameMode
|
||
round_type: RoundType
|
||
time_limit_s: int
|
||
scoring: ScoringConfig
|
||
set_items: tuple[AnswerItemSpec, ...]
|
||
questions: tuple[RoundQuestion, ...]
|
||
max_points: int
|
||
created_at: float
|
||
phase: LivePhase = "lobby"
|
||
current_index: int = 0
|
||
shown_at: float | None = None
|
||
opens_at: float | None = None
|
||
deadline: float | None = None
|
||
closed_through: int = -1
|
||
started_at_iso: str | None = None
|
||
ended_at: float | None = None
|
||
locked: bool = False
|
||
version: int = 1
|
||
players: dict[str, LivePlayer] = field(default_factory=dict)
|
||
player_by_session: dict[str, str] = field(default_factory=dict)
|
||
kicked_sessions: set[str] = field(default_factory=set)
|
||
join_counter: int = 0
|
||
|
||
@property
|
||
def question_count(self) -> int:
|
||
return len(self.questions)
|
||
|
||
@property
|
||
def current_question(self) -> RoundQuestion:
|
||
return self.questions[self.current_index]
|
||
|
||
def active_players(self) -> list[LivePlayer]:
|
||
"""Nevyhození hráči v pořadí připojení."""
|
||
return sorted(
|
||
(p for p in self.players.values() if not p.kicked),
|
||
key=lambda p: p.join_order,
|
||
)
|
||
|
||
def ranking(self) -> list[LivePlayer]:
|
||
"""Nevyhození hráči seřazení podle skóre (shoda podle připojení)."""
|
||
return sorted(
|
||
self.active_players(),
|
||
key=lambda p: (-p.score, p.join_order),
|
||
)
|
||
|
||
def rank_of(self, player: LivePlayer) -> int:
|
||
"""Pořadí hráče; hráči se stejným skóre sdílejí místo."""
|
||
return 1 + sum(
|
||
1 for p in self.active_players() if p.score > player.score
|
||
)
|
||
|
||
def eligible_players(self) -> list[LivePlayer]:
|
||
"""Hráči, kteří hrají aktuální otázku."""
|
||
return [
|
||
p for p in self.active_players() if p.plays(self.current_index)
|
||
]
|
||
|
||
def bump(self) -> None:
|
||
self.version += 1
|
||
|
||
|
||
def normalize_nickname(raw: str | None) -> str:
|
||
"""Ořízne přezdívku a sloučí vnitřní mezery."""
|
||
return " ".join(str(raw or "").split())
|
||
|
||
|
||
def default_time_limit(mode: GameMode) -> int:
|
||
"""Výchozí časový limit otázky pro režim."""
|
||
return DEFAULT_TIME_LIMITS[mode]
|
||
|
||
|
||
def _ms(seconds: float) -> int:
|
||
return max(0, int(round(seconds * 1000)))
|
||
|
||
|
||
def _player_public(room: LiveRoom, player: LivePlayer) -> dict[str, Any]:
|
||
return {
|
||
"id": player.player_id,
|
||
"name": player.name,
|
||
"score": player.score,
|
||
"rank": room.rank_of(player),
|
||
}
|
||
|
||
|
||
def _timing(room: LiveRoom, now: float) -> dict[str, Any]:
|
||
return {
|
||
"server_now": now,
|
||
"shown_at": room.shown_at,
|
||
"opens_at": room.opens_at,
|
||
"deadline": room.deadline,
|
||
"time_limit_s": room.time_limit_s,
|
||
"prepare_seconds": PREPARE_SECONDS,
|
||
}
|
||
|
||
|
||
def _base_payload(room: LiveRoom, now: float) -> dict[str, Any]:
|
||
return {
|
||
"version": room.version,
|
||
"phase": room.phase,
|
||
"code": room.code,
|
||
"mode": room.mode,
|
||
"round_type": room.round_type,
|
||
"locked": room.locked,
|
||
"set": {
|
||
"id": room.sada_id,
|
||
"slug": room.sada_slug,
|
||
"nazev": room.sada_nazev,
|
||
},
|
||
"progress": {
|
||
"current": room.current_index + 1,
|
||
"total": room.question_count,
|
||
},
|
||
"timing": _timing(room, now),
|
||
"player_count": len(room.active_players()),
|
||
}
|
||
|
||
|
||
def _distribution(room: LiveRoom) -> dict[str, Any]:
|
||
q = room.current_question
|
||
answers = [
|
||
p.answers[room.current_index]
|
||
for p in room.eligible_players()
|
||
if room.current_index in p.answers
|
||
]
|
||
if room.mode == "abcd":
|
||
counts = [0] * len(q.abcd_options)
|
||
for ans in answers:
|
||
if ans.selected_option_index is not None:
|
||
counts[ans.selected_option_index] += 1
|
||
return {"options": counts}
|
||
verdicts = {"spravne": 0, "castecne": 0, "spatne": 0}
|
||
for ans in answers:
|
||
verdicts[ans.verdict] += 1
|
||
return {"verdicts": verdicts}
|
||
|
||
|
||
def serialize_board(room: LiveRoom, now: float) -> dict[str, Any]:
|
||
"""Stav pro tabuli učitelky (včetně správné odpovědi ve vyhodnocení)."""
|
||
payload = _base_payload(room, now)
|
||
payload["room_id"] = room.room_id
|
||
payload["players"] = [
|
||
_player_public(room, p) for p in room.active_players()
|
||
]
|
||
if room.phase in ("priprava", "otazka", "vyhodnoceni"):
|
||
q = room.current_question
|
||
eligible = room.eligible_players()
|
||
question: dict[str, Any] = {
|
||
"index": q.index,
|
||
"photo_url": f"/media/{q.photo_full_path}",
|
||
"answered_count": sum(
|
||
1
|
||
for p in eligible
|
||
if room.current_index in p.answers
|
||
and p.answers[room.current_index].answered
|
||
),
|
||
"eligible_count": len(eligible),
|
||
}
|
||
if room.mode == "abcd":
|
||
question["options"] = [
|
||
{"index": idx, "text": opt.text}
|
||
for idx, opt in enumerate(q.abcd_options)
|
||
]
|
||
payload["question"] = question
|
||
if room.phase == "vyhodnoceni":
|
||
q = room.current_question
|
||
payload["reveal"] = {
|
||
"canonical_name": q.canonical_name,
|
||
"latin_name": q.latin_name,
|
||
"correct_option_index": q.correct_option_index,
|
||
**_distribution(room),
|
||
}
|
||
payload["top"] = [
|
||
_player_public(room, p) for p in room.ranking()[:TOP_COUNT]
|
||
]
|
||
if room.phase == "konec":
|
||
payload["podium"] = [
|
||
_player_public(room, p) for p in room.ranking()[:PODIUM_COUNT]
|
||
]
|
||
return payload
|
||
|
||
|
||
def serialize_player(
|
||
room: LiveRoom,
|
||
player: LivePlayer,
|
||
now: float,
|
||
) -> dict[str, Any]:
|
||
"""Stav pro telefon hráče bez správné odpovědi před vyhodnocením."""
|
||
payload = _base_payload(room, now)
|
||
payload["me"] = {
|
||
"id": player.player_id,
|
||
"name": player.name,
|
||
"score": player.score,
|
||
"streak": player.streak,
|
||
"rank": room.rank_of(player),
|
||
"is_authenticated": player.user_id is not None,
|
||
}
|
||
if room.phase in ("priprava", "otazka", "vyhodnoceni"):
|
||
idx = room.current_index
|
||
q = room.current_question
|
||
question: dict[str, Any] = {
|
||
"index": idx,
|
||
"plays": player.plays(idx),
|
||
"answered": idx in player.answers
|
||
and player.answers[idx].answered,
|
||
}
|
||
if room.mode == "abcd":
|
||
question["option_count"] = len(q.abcd_options)
|
||
payload["question"] = question
|
||
if room.phase == "vyhodnoceni":
|
||
idx = room.current_index
|
||
q = room.current_question
|
||
ans = player.answers.get(idx)
|
||
payload["result"] = (
|
||
None
|
||
if ans is None
|
||
else {
|
||
"verdict": ans.verdict,
|
||
"answered": ans.answered,
|
||
"points": ans.points,
|
||
"streak_bonus": ans.streak_bonus,
|
||
"streak": ans.streak_after,
|
||
"selected_option_index": ans.selected_option_index,
|
||
}
|
||
)
|
||
payload["reveal"] = {
|
||
"canonical_name": q.canonical_name,
|
||
"latin_name": q.latin_name,
|
||
"correct_option_index": q.correct_option_index,
|
||
}
|
||
if room.phase == "konec":
|
||
payload["podium"] = [
|
||
_player_public(room, p) for p in room.ranking()[:PODIUM_COUNT]
|
||
]
|
||
return payload
|
||
|
||
|
||
class LiveRoomStore:
|
||
"""Vláknově bezpečné úložiště živých místností s líným časováním."""
|
||
|
||
def __init__(
|
||
self,
|
||
*,
|
||
clock: Callable[[], float] = time.monotonic,
|
||
room_ttl_seconds: float = ROOM_TTL_SECONDS,
|
||
ended_ttl_seconds: float = ENDED_TTL_SECONDS,
|
||
max_players: int = MAX_PLAYERS,
|
||
code_factory: Callable[[], str] | None = None,
|
||
) -> None:
|
||
self._clock = clock
|
||
self._room_ttl = float(room_ttl_seconds)
|
||
self._ended_ttl = float(ended_ttl_seconds)
|
||
self._max_players = int(max_players)
|
||
self._code_factory = code_factory or (
|
||
lambda: f"{secrets.randbelow(10**CODE_DIGITS):0{CODE_DIGITS}d}"
|
||
)
|
||
self._lock = threading.Lock()
|
||
self._rooms: dict[str, LiveRoom] = {}
|
||
self._room_by_code: dict[str, str] = {}
|
||
self._pending: list[PendingWrite] = []
|
||
|
||
# --- interní pomocníci (volat se zámkem) ---------------------------
|
||
|
||
def _now(self, now: float | None) -> float:
|
||
return self._clock() if now is None else float(now)
|
||
|
||
def _purge_locked(self, now: float) -> None:
|
||
expired = [
|
||
rid
|
||
for rid, room in self._rooms.items()
|
||
if (now - room.created_at) > self._room_ttl
|
||
or (
|
||
room.ended_at is not None
|
||
and (now - room.ended_at) > self._ended_ttl
|
||
)
|
||
]
|
||
for rid in expired:
|
||
room = self._rooms.pop(rid)
|
||
if self._room_by_code.get(room.code) == rid:
|
||
del self._room_by_code[room.code]
|
||
|
||
def _room_locked(self, room_id: str, now: float) -> LiveRoom:
|
||
self._purge_locked(now)
|
||
room = self._rooms.get(room_id)
|
||
if room is None:
|
||
raise RoomNotFoundError("Místnost neexistuje nebo už zanikla.")
|
||
self._tick_locked(room, now)
|
||
return room
|
||
|
||
def _owned_room_locked(
|
||
self,
|
||
room_id: str,
|
||
owner_user_id: int,
|
||
now: float,
|
||
) -> LiveRoom:
|
||
room = self._room_locked(room_id, now)
|
||
if room.owner_user_id != owner_user_id:
|
||
raise RoomForbiddenError("Tabuli může ovládat jen zakladatelka.")
|
||
return room
|
||
|
||
def _player_locked(self, room: LiveRoom, session_key: str) -> LivePlayer:
|
||
if session_key in room.kicked_sessions:
|
||
raise PlayerKickedError("Byl(a) jsi z místnosti vyřazen(a).")
|
||
pid = room.player_by_session.get(session_key)
|
||
if pid is None:
|
||
raise RoomForbiddenError("Do této místnosti nejsi připojen(a).")
|
||
return room.players[pid]
|
||
|
||
def _tick_locked(self, room: LiveRoom, now: float) -> None:
|
||
if (
|
||
room.phase == "priprava"
|
||
and room.opens_at is not None
|
||
and now >= room.opens_at
|
||
):
|
||
room.phase = "otazka"
|
||
room.bump()
|
||
if room.phase == "otazka":
|
||
assert room.deadline is not None
|
||
if now >= room.deadline:
|
||
self._close_question_locked(room, room.deadline)
|
||
elif self._all_answered(room):
|
||
self._close_question_locked(room, now)
|
||
|
||
@staticmethod
|
||
def _all_answered(room: LiveRoom) -> bool:
|
||
idx = room.current_index
|
||
return all(idx in p.answers for p in room.eligible_players())
|
||
|
||
def _show_question_locked(
|
||
self,
|
||
room: LiveRoom,
|
||
index: int,
|
||
now: float,
|
||
) -> None:
|
||
room.current_index = index
|
||
room.shown_at = now
|
||
room.opens_at = now + PREPARE_SECONDS
|
||
room.deadline = room.opens_at + room.time_limit_s
|
||
room.phase = "priprava"
|
||
room.bump()
|
||
|
||
def _close_question_locked(self, room: LiveRoom, at: float) -> None:
|
||
idx = room.current_index
|
||
q = room.current_question
|
||
assert room.shown_at is not None
|
||
for player in room.eligible_players():
|
||
if idx not in player.answers:
|
||
player.streak = 0
|
||
player.answers[idx] = LiveAnswer(
|
||
question_index=idx,
|
||
verdict="spatne",
|
||
reason="no_answer",
|
||
submitted_text="",
|
||
selected_option_index=None,
|
||
reaction_time_ms=_ms(at - room.shown_at),
|
||
points=0,
|
||
streak_bonus=0,
|
||
streak_after=0,
|
||
answered=False,
|
||
)
|
||
if player.user_id is not None:
|
||
self._pending.append(
|
||
MasteryWrite(
|
||
user_id=player.user_id,
|
||
item_id=q.item_id,
|
||
mode=room.mode,
|
||
verdict=player.answers[idx].verdict,
|
||
)
|
||
)
|
||
room.closed_through = idx
|
||
room.phase = "vyhodnoceni"
|
||
room.bump()
|
||
|
||
def _finish_locked(
|
||
self,
|
||
room: LiveRoom,
|
||
now: float,
|
||
now_utc_iso: str,
|
||
) -> None:
|
||
if room.phase == "konec":
|
||
return
|
||
completed = room.closed_through >= room.question_count - 1
|
||
room.phase = "konec"
|
||
room.ended_at = now
|
||
room.bump()
|
||
if self._room_by_code.get(room.code) == room.room_id:
|
||
del self._room_by_code[room.code]
|
||
if not completed or room.started_at_iso is None:
|
||
return
|
||
for player in room.active_players():
|
||
if player.user_id is None:
|
||
continue
|
||
played = [
|
||
player.answers[i]
|
||
for i in range(room.question_count)
|
||
if player.plays(i) and i in player.answers
|
||
]
|
||
correct = sum(1 for a in played if a.verdict == "spravne")
|
||
partial = sum(1 for a in played if a.verdict == "castecne")
|
||
self._pending.append(
|
||
RoundWrite(
|
||
RoundRecord(
|
||
user_id=player.user_id,
|
||
sada_id=room.sada_id,
|
||
mode=room.mode,
|
||
round_type=room.round_type,
|
||
question_count=room.question_count,
|
||
total_points=player.score,
|
||
max_points=room.max_points,
|
||
accuracy=calculate_weighted_accuracy(
|
||
correct, partial, room.question_count
|
||
),
|
||
started_at_iso=room.started_at_iso,
|
||
completed_at_iso=now_utc_iso,
|
||
answers=tuple(
|
||
RoundAnswerRecord(
|
||
item_id=room.questions[a.question_index].item_id,
|
||
photo_id=room.questions[
|
||
a.question_index
|
||
].photo_id,
|
||
submitted_text=a.submitted_text,
|
||
verdict=a.verdict,
|
||
reaction_time_ms=a.reaction_time_ms,
|
||
points=a.points,
|
||
)
|
||
for a in played
|
||
),
|
||
)
|
||
)
|
||
)
|
||
|
||
def _new_code_locked(self) -> str:
|
||
for _ in range(1000):
|
||
code = self._code_factory()
|
||
if code not in self._room_by_code:
|
||
return code
|
||
raise RuntimeError("Nepodařilo se přidělit volný kód místnosti.")
|
||
|
||
# --- veřejné API -----------------------------------------------------
|
||
|
||
def create_room(
|
||
self,
|
||
*,
|
||
owner_user_id: int,
|
||
sada_id: int,
|
||
sada_slug: str,
|
||
sada_nazev: str,
|
||
mode: GameMode,
|
||
round_type: RoundType,
|
||
time_limit_s: int,
|
||
quick_round_size: int,
|
||
scoring: ScoringConfig,
|
||
all_set_items: Sequence[Mapping[str, Any]],
|
||
photos_by_item: Mapping[int, Sequence[Mapping[str, Any]]],
|
||
now_utc_iso: str,
|
||
rng: random.Random | None = None,
|
||
now_monotonic: float | None = None,
|
||
) -> LiveRoom:
|
||
"""Založí místnost; předchozí neukončenou místnost učitelky ukončí."""
|
||
if round_type not in ("cele", "rychle"):
|
||
raise ValueError("Živá místnost podporuje jen délku cele/rychle.")
|
||
if time_limit_s not in TIME_LIMITS:
|
||
raise ValueError("Neplatný časový limit otázky.")
|
||
questions = prepare_questions(
|
||
mode=mode,
|
||
round_type=round_type,
|
||
quick_round_size=quick_round_size,
|
||
all_set_items=all_set_items,
|
||
photos_by_item=photos_by_item,
|
||
rng=rng if rng is not None else random.Random(),
|
||
)
|
||
set_items = tuple(to_item_spec(item) for item in all_set_items)
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
self._purge_locked(now)
|
||
for room in list(self._rooms.values()):
|
||
if room.owner_user_id == owner_user_id:
|
||
self._tick_locked(room, now)
|
||
self._finish_locked(room, now, now_utc_iso)
|
||
room_id = secrets.token_urlsafe(16)
|
||
while room_id in self._rooms:
|
||
room_id = secrets.token_urlsafe(16)
|
||
room = LiveRoom(
|
||
room_id=room_id,
|
||
code=self._new_code_locked(),
|
||
owner_user_id=owner_user_id,
|
||
sada_id=sada_id,
|
||
sada_slug=sada_slug,
|
||
sada_nazev=sada_nazev,
|
||
mode=mode,
|
||
round_type=round_type,
|
||
time_limit_s=int(time_limit_s),
|
||
scoring=scoring,
|
||
set_items=set_items,
|
||
questions=tuple(questions),
|
||
max_points=calculate_round_max_points(
|
||
mode, len(questions), scoring
|
||
),
|
||
created_at=now,
|
||
)
|
||
self._rooms[room_id] = room
|
||
self._room_by_code[room.code] = room_id
|
||
return room
|
||
|
||
def join(
|
||
self,
|
||
code: str,
|
||
*,
|
||
session_key: str,
|
||
user_id: int | None,
|
||
display_name: str | None,
|
||
nickname: str | None,
|
||
now_monotonic: float | None = None,
|
||
) -> LiveRoom:
|
||
"""Připojí hráče kódem, případně vrátí již připojeného hráče.
|
||
|
||
`RoomNotFoundError` znamená neplatný kód (počítá se do rate limitu),
|
||
`JoinRejectedError` odmítnutí v existující místnosti.
|
||
"""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
self._purge_locked(now)
|
||
room_id = self._room_by_code.get(str(code).strip())
|
||
if room_id is None:
|
||
raise RoomNotFoundError("Místnost s tímto kódem neexistuje.")
|
||
room = self._rooms[room_id]
|
||
self._tick_locked(room, now)
|
||
if session_key in room.kicked_sessions:
|
||
raise JoinRejectedError(
|
||
"Z této místnosti jsi byl(a) vyřazen(a)."
|
||
)
|
||
if session_key in room.player_by_session:
|
||
return room
|
||
if room.locked:
|
||
raise JoinRejectedError("Místnost je zamčená.")
|
||
if len(room.active_players()) >= self._max_players:
|
||
raise JoinRejectedError("Místnost je plná.")
|
||
|
||
if user_id is not None:
|
||
name = normalize_nickname(display_name) or "Hráč"
|
||
else:
|
||
name = normalize_nickname(nickname)
|
||
if not (1 <= len(name) <= NICKNAME_MAX_LENGTH):
|
||
raise JoinRejectedError(
|
||
"Přezdívka musí mít 1 až "
|
||
f"{NICKNAME_MAX_LENGTH} znaků."
|
||
)
|
||
taken = {p.name.casefold() for p in room.active_players()}
|
||
if name.casefold() in taken:
|
||
raise JoinRejectedError(
|
||
"Tuto přezdívku už někdo má, zvol jinou."
|
||
)
|
||
|
||
first_index = (
|
||
0 if room.phase == "lobby" else room.current_index + 1
|
||
)
|
||
room.join_counter += 1
|
||
player = LivePlayer(
|
||
player_id=secrets.token_urlsafe(8),
|
||
session_key=session_key,
|
||
user_id=user_id,
|
||
name=name,
|
||
first_question_index=first_index,
|
||
join_order=room.join_counter,
|
||
)
|
||
room.players[player.player_id] = player
|
||
room.player_by_session[session_key] = player.player_id
|
||
room.bump()
|
||
return room
|
||
|
||
def room_for_session(
|
||
self,
|
||
code: str,
|
||
session_key: str,
|
||
*,
|
||
now_monotonic: float | None = None,
|
||
) -> str | None:
|
||
"""Id místnosti s kódem, kde je session hráčem (i po konci hry)."""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
self._purge_locked(now)
|
||
for room in self._rooms.values():
|
||
if (
|
||
room.code == code
|
||
and session_key in room.player_by_session
|
||
and session_key not in room.kicked_sessions
|
||
):
|
||
return room.room_id
|
||
return None
|
||
|
||
def room_code(
|
||
self,
|
||
room_id: str,
|
||
*,
|
||
now_monotonic: float | None = None,
|
||
) -> str:
|
||
"""Vrátí kód místnosti podle id."""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
return self._room_locked(room_id, now).code
|
||
|
||
def board_state(
|
||
self,
|
||
room_id: str,
|
||
owner_user_id: int,
|
||
*,
|
||
known_version: int | None = None,
|
||
now_monotonic: float | None = None,
|
||
) -> dict[str, Any] | None:
|
||
"""Stav tabule; `None`, pokud se od `known_version` nezměnil."""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
room = self._owned_room_locked(room_id, owner_user_id, now)
|
||
if known_version == room.version:
|
||
return None
|
||
return serialize_board(room, now)
|
||
|
||
def player_state(
|
||
self,
|
||
room_id: str,
|
||
session_key: str,
|
||
*,
|
||
known_version: int | None = None,
|
||
now_monotonic: float | None = None,
|
||
) -> dict[str, Any] | None:
|
||
"""Stav telefonu; `None`, pokud se od `known_version` nezměnil."""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
room = self._room_locked(room_id, now)
|
||
player = self._player_locked(room, session_key)
|
||
if known_version == room.version:
|
||
return None
|
||
return serialize_player(room, player, now)
|
||
|
||
def board_action(
|
||
self,
|
||
room_id: str,
|
||
owner_user_id: int,
|
||
action: str,
|
||
*,
|
||
now_utc_iso: str,
|
||
player_id: str | None = None,
|
||
now_monotonic: float | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Provede akci učitelky z tabule a vrátí nový stav tabule."""
|
||
if action not in BOARD_ACTIONS:
|
||
raise RoomConflictError("Neznámá akce.")
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
room = self._owned_room_locked(room_id, owner_user_id, now)
|
||
if action == "start":
|
||
if room.phase != "lobby":
|
||
raise RoomConflictError("Hra už běží.")
|
||
if not room.active_players():
|
||
raise RoomConflictError("Čeká se na prvního hráče.")
|
||
room.started_at_iso = now_utc_iso
|
||
self._show_question_locked(room, 0, now)
|
||
elif action == "dalsi":
|
||
if room.phase != "vyhodnoceni":
|
||
raise RoomConflictError("Další otázka až po vyhodnocení.")
|
||
if room.current_index + 1 < room.question_count:
|
||
self._show_question_locked(
|
||
room, room.current_index + 1, now
|
||
)
|
||
else:
|
||
self._finish_locked(room, now, now_utc_iso)
|
||
elif action == "ukoncit-otazku":
|
||
if room.phase != "otazka":
|
||
raise RoomConflictError("Otázka teď neběží.")
|
||
self._close_question_locked(room, now)
|
||
elif action == "ukoncit-hru":
|
||
if room.phase == "konec":
|
||
raise RoomConflictError("Hra už skončila.")
|
||
self._finish_locked(room, now, now_utc_iso)
|
||
elif action in ("zamknout", "odemknout"):
|
||
wanted = action == "zamknout"
|
||
if room.locked != wanted:
|
||
room.locked = wanted
|
||
room.bump()
|
||
elif action == "vyhodit":
|
||
player = room.players.get(str(player_id or ""))
|
||
if player is None or player.kicked:
|
||
raise RoomConflictError("Hráč v místnosti není.")
|
||
player.kicked = True
|
||
room.kicked_sessions.add(player.session_key)
|
||
room.bump()
|
||
self._tick_locked(room, now)
|
||
return serialize_board(room, now)
|
||
|
||
def submit_answer(
|
||
self,
|
||
room_id: str,
|
||
session_key: str,
|
||
*,
|
||
answer_text: str | None = None,
|
||
option_index: int | None = None,
|
||
now_monotonic: float | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Vyhodnotí odpověď hráče na otevřenou otázku a vrátí jeho stav."""
|
||
now = self._now(now_monotonic)
|
||
with self._lock:
|
||
room = self._room_locked(room_id, now)
|
||
player = self._player_locked(room, session_key)
|
||
idx = room.current_index
|
||
if room.phase != "otazka":
|
||
raise RoomConflictError("Na otázku teď nelze odpovídat.")
|
||
if not player.plays(idx):
|
||
raise RoomConflictError("Tuto otázku nehraješ.")
|
||
if idx in player.answers:
|
||
raise RoomConflictError("Na tuto otázku už jsi odpověděl(a).")
|
||
|
||
q = room.current_question
|
||
selected: int | None = None
|
||
if room.mode == "psani":
|
||
raw = "" if answer_text is None else str(answer_text)
|
||
evaluation = evaluate_writing_answer(
|
||
raw, q.to_item_spec(), room.set_items
|
||
)
|
||
verdict = evaluation.verdict
|
||
reason = evaluation.reason
|
||
text = raw.strip()
|
||
else:
|
||
if (
|
||
isinstance(option_index, bool)
|
||
or not isinstance(option_index, int)
|
||
or not (0 <= option_index < len(q.abcd_options))
|
||
):
|
||
raise InvalidAnswerError(
|
||
"Vybraná možnost A–D je mimo platný rozsah."
|
||
)
|
||
selected = option_index
|
||
chosen = q.abcd_options[option_index]
|
||
verdict = "spravne" if chosen.is_correct else "spatne"
|
||
reason = "abcd_correct" if chosen.is_correct else "abcd_wrong"
|
||
text = chosen.text
|
||
|
||
if verdict == "spravne":
|
||
player.streak += 1
|
||
player.best_streak = max(player.best_streak, player.streak)
|
||
else:
|
||
player.streak = 0
|
||
assert room.shown_at is not None
|
||
reaction_ms = _ms(now - room.shown_at)
|
||
score = calculate_question_score(
|
||
room.mode, verdict, reaction_ms, player.streak, room.scoring
|
||
)
|
||
player.score += score.total
|
||
player.answers[idx] = LiveAnswer(
|
||
question_index=idx,
|
||
verdict=verdict,
|
||
reason=reason,
|
||
submitted_text=text,
|
||
selected_option_index=selected,
|
||
reaction_time_ms=reaction_ms,
|
||
points=score.total,
|
||
streak_bonus=score.streak_bonus,
|
||
streak_after=player.streak,
|
||
answered=True,
|
||
)
|
||
room.bump()
|
||
self._tick_locked(room, now)
|
||
return serialize_player(room, player, now)
|
||
|
||
def drain_writes(self) -> list[PendingWrite]:
|
||
"""Vyzvedne frontu zápisů do DB (vykonat mimo zámek)."""
|
||
with self._lock:
|
||
pending, self._pending = self._pending, []
|
||
return pending
|
||
|
||
def get_room(self, room_id: str) -> LiveRoom | None:
|
||
"""Přímý přístup k místnosti (jen pro testy)."""
|
||
with self._lock:
|
||
return self._rooms.get(room_id)
|
||
|
||
def reset(self) -> None:
|
||
"""Vyprázdní všechny místnosti (pro testy)."""
|
||
with self._lock:
|
||
self._rooms.clear()
|
||
self._room_by_code.clear()
|
||
self._pending.clear()
|