Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cc680dc392 | |||
| f5c62d27fd |
@@ -0,0 +1,34 @@
|
|||||||
|
"""add self_rolls and pending_roll to game_participants
|
||||||
|
|
||||||
|
Revision ID: a3c7e9f1b204
|
||||||
|
Revises: f1a2b3c4d5e6
|
||||||
|
Create Date: 2026-09-03 09:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = 'a3c7e9f1b204'
|
||||||
|
down_revision: Union[str, None] = 'f1a2b3c4d5e6'
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
'game_participants',
|
||||||
|
sa.Column('self_rolls', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||||
|
)
|
||||||
|
op.add_column(
|
||||||
|
'game_participants',
|
||||||
|
sa.Column('pending_roll', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column('game_participants', 'pending_roll')
|
||||||
|
op.drop_column('game_participants', 'self_rolls')
|
||||||
@@ -14,7 +14,7 @@ from app.models.game import Game, GameParticipant
|
|||||||
from app.models.message import Message
|
from app.models.message import Message
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.rag.adventure_ingestion import ingest_adventure_text
|
from app.rag.adventure_ingestion import ingest_adventure_text
|
||||||
from app.schemas.game import GameCreate, GameJoin, GameRead
|
from app.schemas.game import GameCreate, GameJoin, GameRead, SelfRollsUpdate
|
||||||
from app.schemas.game_setup import GameSetupChatRequest, GameSetupChatResponse
|
from app.schemas.game_setup import GameSetupChatRequest, GameSetupChatResponse
|
||||||
from app.schemas.message import MessageRead
|
from app.schemas.message import MessageRead
|
||||||
from app.ws_tickets import issue_ticket
|
from app.ws_tickets import issue_ticket
|
||||||
@@ -43,17 +43,28 @@ async def _serialize_games(
|
|||||||
|
|
||||||
participant_rows = (
|
participant_rows = (
|
||||||
await session.execute(
|
await session.execute(
|
||||||
select(GameParticipant.game_id, GameParticipant.user_id, GameParticipant.character_id, User.name)
|
select(
|
||||||
|
GameParticipant.game_id,
|
||||||
|
GameParticipant.user_id,
|
||||||
|
GameParticipant.character_id,
|
||||||
|
GameParticipant.self_rolls,
|
||||||
|
GameParticipant.pending_roll,
|
||||||
|
User.name,
|
||||||
|
)
|
||||||
.join(User, User.id == GameParticipant.user_id)
|
.join(User, User.id == GameParticipant.user_id)
|
||||||
.where(GameParticipant.game_id.in_(game_ids))
|
.where(GameParticipant.game_id.in_(game_ids))
|
||||||
)
|
)
|
||||||
).all()
|
).all()
|
||||||
participants_by_game: dict[uuid.UUID, list[str]] = {}
|
participants_by_game: dict[uuid.UUID, list[str]] = {}
|
||||||
viewer_participation: dict[uuid.UUID, uuid.UUID | None] = {}
|
viewer_participation: dict[uuid.UUID, uuid.UUID | None] = {}
|
||||||
for game_id, participant_user_id, character_id, name in participant_rows:
|
viewer_self_rolls: dict[uuid.UUID, bool] = {}
|
||||||
|
viewer_pending_roll: dict[uuid.UUID, dict | None] = {}
|
||||||
|
for game_id, participant_user_id, character_id, self_rolls, pending_roll, name in participant_rows:
|
||||||
participants_by_game.setdefault(game_id, []).append(name)
|
participants_by_game.setdefault(game_id, []).append(name)
|
||||||
if participant_user_id == viewer_id:
|
if participant_user_id == viewer_id:
|
||||||
viewer_participation[game_id] = character_id
|
viewer_participation[game_id] = character_id
|
||||||
|
viewer_self_rolls[game_id] = self_rolls
|
||||||
|
viewer_pending_roll[game_id] = pending_roll
|
||||||
|
|
||||||
result = []
|
result = []
|
||||||
for game in games:
|
for game in games:
|
||||||
@@ -75,6 +86,8 @@ async def _serialize_games(
|
|||||||
status=game.status,
|
status=game.status,
|
||||||
ended_reason=game.ended_reason,
|
ended_reason=game.ended_reason,
|
||||||
has_adventure=bool(game.adventure_text.strip()),
|
has_adventure=bool(game.adventure_text.strip()),
|
||||||
|
my_self_rolls=viewer_self_rolls.get(game.id, False),
|
||||||
|
my_pending_roll=viewer_pending_roll.get(game.id),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return result
|
return result
|
||||||
@@ -277,6 +290,24 @@ async def join_game(
|
|||||||
return serialized[0]
|
return serialized[0]
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{game_id}/self-rolls", response_model=GameRead)
|
||||||
|
async def update_self_rolls(
|
||||||
|
game_id: uuid.UUID,
|
||||||
|
payload: SelfRollsUpdate,
|
||||||
|
session: AsyncSession = Depends(get_async_session),
|
||||||
|
user: User = Depends(current_active_user),
|
||||||
|
) -> GameRead:
|
||||||
|
participant = await _require_participant(session, game_id, user.id)
|
||||||
|
participant.self_rolls = payload.self_rolls
|
||||||
|
if not payload.self_rolls:
|
||||||
|
participant.pending_roll = None
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
game = await session.get(Game, game_id)
|
||||||
|
serialized = await _serialize_games(session, [game], user.id)
|
||||||
|
return serialized[0]
|
||||||
|
|
||||||
|
|
||||||
@router.post("/{game_id}/ws-ticket")
|
@router.post("/{game_id}/ws-ticket")
|
||||||
async def create_ws_ticket(
|
async def create_ws_ticket(
|
||||||
game_id: uuid.UUID,
|
game_id: uuid.UUID,
|
||||||
|
|||||||
@@ -74,13 +74,16 @@ async def _serialize_message(session, message: Message) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
async def _run_and_broadcast_dm_turn(
|
async def _run_and_broadcast_dm_turn(
|
||||||
session: AsyncSession, game_id: uuid.UUID, latest_player_message: str
|
session: AsyncSession, game_id: uuid.UUID, latest_player_message: str, user_id: uuid.UUID | None = None
|
||||||
) -> None:
|
) -> None:
|
||||||
await manager.broadcast(game_id, {"type": "typing"})
|
await manager.broadcast(game_id, {"type": "typing"})
|
||||||
|
|
||||||
async def _broadcast_roll(notation: str) -> None:
|
async def _broadcast_roll(notation: str) -> None:
|
||||||
await manager.broadcast(game_id, {"type": "rolling", "notation": notation})
|
await manager.broadcast(game_id, {"type": "rolling", "notation": notation})
|
||||||
|
|
||||||
|
async def _broadcast_awaiting_roll(notation: str, reason: str) -> None:
|
||||||
|
await manager.broadcast(game_id, {"type": "awaiting_roll", "notation": notation, "reason": reason})
|
||||||
|
|
||||||
async def _broadcast_game_ended(reason: str) -> None:
|
async def _broadcast_game_ended(reason: str) -> None:
|
||||||
await manager.broadcast(game_id, {"type": "game_ended", "reason": reason})
|
await manager.broadcast(game_id, {"type": "game_ended", "reason": reason})
|
||||||
|
|
||||||
@@ -89,7 +92,9 @@ async def _run_and_broadcast_dm_turn(
|
|||||||
session,
|
session,
|
||||||
game_id,
|
game_id,
|
||||||
latest_player_message=latest_player_message,
|
latest_player_message=latest_player_message,
|
||||||
|
user_id=user_id,
|
||||||
on_roll=_broadcast_roll,
|
on_roll=_broadcast_roll,
|
||||||
|
on_awaiting_roll=_broadcast_awaiting_roll,
|
||||||
on_game_ended=_broadcast_game_ended,
|
on_game_ended=_broadcast_game_ended,
|
||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
@@ -123,7 +128,7 @@ async def game_websocket(websocket: WebSocket, game_id: uuid.UUID, ticket: str)
|
|||||||
await session.execute(select(Message.id).where(Message.game_id == game_id).limit(1))
|
await session.execute(select(Message.id).where(Message.game_id == game_id).limit(1))
|
||||||
).first() is not None
|
).first() is not None
|
||||||
if not has_messages:
|
if not has_messages:
|
||||||
await _run_and_broadcast_dm_turn(session, game_id, KICKOFF_QUERY)
|
await _run_and_broadcast_dm_turn(session, game_id, KICKOFF_QUERY, user_id=user_id)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
@@ -164,7 +169,7 @@ async def game_websocket(websocket: WebSocket, game_id: uuid.UUID, ticket: str)
|
|||||||
{"type": "message", "message": await _serialize_message(session, player_message)},
|
{"type": "message", "message": await _serialize_message(session, player_message)},
|
||||||
)
|
)
|
||||||
|
|
||||||
await _run_and_broadcast_dm_turn(session, game_id, content)
|
await _run_and_broadcast_dm_turn(session, game_id, content, user_id=user_id)
|
||||||
except WebSocketDisconnect:
|
except WebSocketDisconnect:
|
||||||
pass
|
pass
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ from app.config import settings
|
|||||||
from app.llm.client import get_dm_system_prompt, get_llm_client
|
from app.llm.client import get_dm_system_prompt, get_llm_client
|
||||||
from app.llm.context import build_context
|
from app.llm.context import build_context
|
||||||
from app.llm.json_utils import fix_double_escaped_unicode
|
from app.llm.json_utils import fix_double_escaped_unicode
|
||||||
from app.llm.tools import character_sheet, dice, end_game, monster, world_state
|
from app.llm.tools import character_sheet, dice, end_game, link_existing_character, monster, world_state
|
||||||
|
from app.models.character import Character
|
||||||
from app.models.game import Game, GameParticipant
|
from app.models.game import Game, GameParticipant
|
||||||
from app.models.message import Message
|
from app.models.message import Message
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
@@ -28,6 +29,7 @@ TOOLS = [
|
|||||||
{"type": "function", "function": end_game.TOOL_SCHEMA},
|
{"type": "function", "function": end_game.TOOL_SCHEMA},
|
||||||
{"type": "function", "function": monster.TOOL_SCHEMA},
|
{"type": "function", "function": monster.TOOL_SCHEMA},
|
||||||
{"type": "function", "function": world_state.TOOL_SCHEMA},
|
{"type": "function", "function": world_state.TOOL_SCHEMA},
|
||||||
|
{"type": "function", "function": link_existing_character.TOOL_SCHEMA},
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
@@ -47,6 +49,8 @@ async def _execute_tool_call(
|
|||||||
return await monster.update(session, game_id, tool_input)
|
return await monster.update(session, game_id, tool_input)
|
||||||
if tool_name == "update_world_state":
|
if tool_name == "update_world_state":
|
||||||
return await world_state.update(session, game_id, tool_input)
|
return await world_state.update(session, game_id, tool_input)
|
||||||
|
if tool_name == "link_existing_character":
|
||||||
|
return await link_existing_character.link(session, game_id, tool_input)
|
||||||
return {"error": f"Unknown tool {tool_name!r}"}
|
return {"error": f"Unknown tool {tool_name!r}"}
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.warning("Tool call %s failed: %s", tool_name, exc)
|
logger.warning("Tool call %s failed: %s", tool_name, exc)
|
||||||
@@ -54,6 +58,57 @@ async def _execute_tool_call(
|
|||||||
return {"error": str(exc)}
|
return {"error": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
async def _request_player_roll(
|
||||||
|
session: AsyncSession, participant: GameParticipant, notation: str, reason: str
|
||||||
|
) -> dict:
|
||||||
|
"""Handles a roll_dice call for a player who rolls their own physical dice: validates the
|
||||||
|
notation without touching the RNG, records it as the participant's pending roll (picked up
|
||||||
|
and cleared at the top of their next turn), and returns a tool result that tells the DM to
|
||||||
|
ask for it and wait instead of rolling itself."""
|
||||||
|
try:
|
||||||
|
dice.parse_notation(notation)
|
||||||
|
except ValueError as exc:
|
||||||
|
return {"error": str(exc)}
|
||||||
|
|
||||||
|
participant.pending_roll = {"notation": notation, "reason": reason}
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"awaiting_player_roll": True,
|
||||||
|
"notation": notation,
|
||||||
|
"reason": reason,
|
||||||
|
"note": (
|
||||||
|
f"Der Spieler würfelt selbst mit physischen Würfeln. Nenne ihm klar und knapp, was er "
|
||||||
|
f"würfeln soll ({notation}" + (f", {reason}" if reason else "") + "), und warte auf "
|
||||||
|
"seine Antwort mit dem Ergebnis in einer künftigen Nachricht — würfle nicht selbst und "
|
||||||
|
"erfinde kein Ergebnis."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _format_character_sheet(character: Character) -> str:
|
||||||
|
parts = [
|
||||||
|
f"- {character.name} ({character.race or '?'} {character.char_class or '?'}, Stufe {character.level})"
|
||||||
|
]
|
||||||
|
if character.stats:
|
||||||
|
parts.append(f" Werte: {character.stats}")
|
||||||
|
hp = None
|
||||||
|
if character.current_hp is not None or character.max_hp is not None:
|
||||||
|
hp = f"{character.current_hp if character.current_hp is not None else '?'}/{character.max_hp if character.max_hp is not None else '?'}"
|
||||||
|
if hp:
|
||||||
|
parts.append(f" TP: {hp}")
|
||||||
|
if character.combat_stats:
|
||||||
|
parts.append(f" Kampfwerte: {character.combat_stats}")
|
||||||
|
if character.abilities:
|
||||||
|
ability_names = ", ".join(a.get("name", "") for a in character.abilities if isinstance(a, dict))
|
||||||
|
parts.append(f" Fähigkeiten: {ability_names}")
|
||||||
|
if character.equipment:
|
||||||
|
parts.append(f" Ausrüstung: {', '.join(character.equipment)}")
|
||||||
|
if character.description:
|
||||||
|
parts.append(f" Hintergrund: {character.description}")
|
||||||
|
return "\n".join(parts)
|
||||||
|
|
||||||
|
|
||||||
async def _check_hp_game_over(session: AsyncSession, game_id: uuid.UUID, result: dict) -> str | None:
|
async def _check_hp_game_over(session: AsyncSession, game_id: uuid.UUID, result: dict) -> str | None:
|
||||||
"""After an upsert_character_sheet call, auto-ends the game if the character it touched
|
"""After an upsert_character_sheet call, auto-ends the game if the character it touched
|
||||||
dropped to 0 HP or below. Returns the end reason if the game was just ended, else None."""
|
dropped to 0 HP or below. Returns the end reason if the game was just ended, else None."""
|
||||||
@@ -76,12 +131,38 @@ async def run_dm_turn(
|
|||||||
session: AsyncSession,
|
session: AsyncSession,
|
||||||
game_id: uuid.UUID,
|
game_id: uuid.UUID,
|
||||||
latest_player_message: str | None = None,
|
latest_player_message: str | None = None,
|
||||||
|
user_id: uuid.UUID | None = None,
|
||||||
on_roll: Callable[[str], Awaitable[None]] | None = None,
|
on_roll: Callable[[str], Awaitable[None]] | None = None,
|
||||||
|
on_awaiting_roll: Callable[[str, str], Awaitable[None]] | None = None,
|
||||||
on_game_ended: Callable[[str], Awaitable[None]] | None = None,
|
on_game_ended: Callable[[str], Awaitable[None]] | None = None,
|
||||||
) -> Message:
|
) -> Message:
|
||||||
client = get_llm_client()
|
client = get_llm_client()
|
||||||
system_prompt = get_dm_system_prompt()
|
system_prompt = get_dm_system_prompt()
|
||||||
|
|
||||||
|
participant: GameParticipant | None = None
|
||||||
|
if user_id is not None:
|
||||||
|
participant = (
|
||||||
|
await session.execute(
|
||||||
|
select(GameParticipant).where(
|
||||||
|
GameParticipant.game_id == game_id, GameParticipant.user_id == user_id
|
||||||
|
)
|
||||||
|
)
|
||||||
|
).scalar_one_or_none()
|
||||||
|
|
||||||
|
if participant is not None and participant.pending_roll:
|
||||||
|
pending = participant.pending_roll
|
||||||
|
system_prompt += (
|
||||||
|
f"\n\nOffene Würfelanfrage: Du hast {pending.get('notation')} "
|
||||||
|
f"({pending.get('reason') or 'ohne Angabe'}) angefragt, der Spieler würfelt selbst. "
|
||||||
|
"Seine gerade eingegangene Nachricht enthält vermutlich das Ergebnis dieses Wurfs — "
|
||||||
|
"nimm die genannte Zahl direkt als Wurfergebnis, würfle NICHT selbst und frag nicht "
|
||||||
|
"erneut danach, außer die Nachricht beantwortet die Anfrage erkennbar nicht."
|
||||||
|
)
|
||||||
|
# Consumed either way — if the message didn't actually answer it, the DM asking again
|
||||||
|
# via roll_dice creates a fresh pending_roll for next time.
|
||||||
|
participant.pending_roll = None
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
game = await session.get(Game, game_id)
|
game = await session.get(Game, game_id)
|
||||||
if game is not None:
|
if game is not None:
|
||||||
system_prompt = (
|
system_prompt = (
|
||||||
@@ -105,6 +186,21 @@ async def run_dm_turn(
|
|||||||
"über den Einladungslink dazukommen; du erkennst sie automatisch am Namen, sobald sie schreiben."
|
"über den Einladungslink dazukommen; du erkennst sie automatisch am Namen, sobald sie schreiben."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
linked_characters = (
|
||||||
|
await session.execute(
|
||||||
|
select(Character)
|
||||||
|
.join(GameParticipant, GameParticipant.character_id == Character.id)
|
||||||
|
.where(GameParticipant.game_id == game_id)
|
||||||
|
)
|
||||||
|
).scalars().all()
|
||||||
|
if linked_characters:
|
||||||
|
sheets = "\n".join(_format_character_sheet(c) for c in linked_characters)
|
||||||
|
system_prompt += (
|
||||||
|
"\n\nBekannte Charakterblätter (bereits vollständig vorhanden — NICHT erneut nach "
|
||||||
|
"Werten/Ausrüstung/Hintergrund fragen, nur bei tatsächlichen Änderungen über "
|
||||||
|
f"upsert_character_sheet aktualisieren):\n{sheets}"
|
||||||
|
)
|
||||||
|
|
||||||
await world_state.refresh_if_due(session, game_id, client, settings.dm_model)
|
await world_state.refresh_if_due(session, game_id, client, settings.dm_model)
|
||||||
world_summary = await world_state.get_summary(session, game_id)
|
world_summary = await world_state.get_summary(session, game_id)
|
||||||
if world_summary:
|
if world_summary:
|
||||||
@@ -145,6 +241,14 @@ async def run_dm_turn(
|
|||||||
|
|
||||||
for tool_call in message.tool_calls:
|
for tool_call in message.tool_calls:
|
||||||
tool_input = fix_double_escaped_unicode(json.loads(tool_call.function.arguments))
|
tool_input = fix_double_escaped_unicode(json.loads(tool_call.function.arguments))
|
||||||
|
|
||||||
|
if tool_call.function.name == "roll_dice" and participant is not None and participant.self_rolls:
|
||||||
|
notation = tool_input.get("notation", "")
|
||||||
|
reason = tool_input.get("reason", "")
|
||||||
|
result = await _request_player_roll(session, participant, notation, reason)
|
||||||
|
if "error" not in result and on_awaiting_roll is not None:
|
||||||
|
await on_awaiting_roll(notation, reason)
|
||||||
|
else:
|
||||||
if tool_call.function.name == "roll_dice" and on_roll is not None:
|
if tool_call.function.name == "roll_dice" and on_roll is not None:
|
||||||
await on_roll(tool_input.get("notation", ""))
|
await on_roll(tool_input.get("notation", ""))
|
||||||
result = await _execute_tool_call(session, game_id, tool_call.function.name, tool_input)
|
result = await _execute_tool_call(session, game_id, tool_call.function.name, tool_input)
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ Phase 1: Session 0 (Vorbereitung)
|
|||||||
Sobald du in ein neues Spiel geholt wirst, meldest du dich SOFORT von dir aus mit einer Begrüßung — warte nie erst auf eine Spielernachricht. Lernst du deine Spieler aktiv kennen. Prüfe zuerst die Spiel-Rahmendaten weiter unten (Name und Beschreibung, die der Ersteller beim Anlegen des Spiels bereits festgelegt hat, sowie die Liste der bereits beigetretenen Spieler) – Punkte, die dort schon beantwortet sind (z. B. Genre/Welt, Umfang, ggf. Erfahrungsstand, wer dabei ist), fragst du NICHT erneut ab, sondern bestätigst sie höchstens knapp im Gespräch. Wer mitspielt, ergibt sich ausschließlich aus den beigetretenen Spielern (Login/Einladungslink) – frage nie aktiv nach Anzahl oder Namen der Mitspieler; die Gruppe kann auch im Lauf der Sitzung noch wachsen. Stelle nur zu den noch offenen Punkten gezielt Fragen, eine nach der anderen, nicht alle auf einmal, an die Spieler, die bereits da sind:
|
Sobald du in ein neues Spiel geholt wirst, meldest du dich SOFORT von dir aus mit einer Begrüßung — warte nie erst auf eine Spielernachricht. Lernst du deine Spieler aktiv kennen. Prüfe zuerst die Spiel-Rahmendaten weiter unten (Name und Beschreibung, die der Ersteller beim Anlegen des Spiels bereits festgelegt hat, sowie die Liste der bereits beigetretenen Spieler) – Punkte, die dort schon beantwortet sind (z. B. Genre/Welt, Umfang, ggf. Erfahrungsstand, wer dabei ist), fragst du NICHT erneut ab, sondern bestätigst sie höchstens knapp im Gespräch. Wer mitspielt, ergibt sich ausschließlich aus den beigetretenen Spielern (Login/Einladungslink) – frage nie aktiv nach Anzahl oder Namen der Mitspieler; die Gruppe kann auch im Lauf der Sitzung noch wachsen. Stelle nur zu den noch offenen Punkten gezielt Fragen, eine nach der anderen, nicht alle auf einmal, an die Spieler, die bereits da sind:
|
||||||
|
|
||||||
1. Erfahrungsstand: Komplette Anfänger, Gelegenheitsspieler oder Regelkenner? Frage das pro Spieler ab, falls die Gruppe gemischt ist.
|
1. Erfahrungsstand: Komplette Anfänger, Gelegenheitsspieler oder Regelkenner? Frage das pro Spieler ab, falls die Gruppe gemischt ist.
|
||||||
2. Charaktere: Wollen sie eigene, fertige Charaktere mitbringen (Name, Klasse, Rasse, Stats) oder sollst du sie durch die Charaktererstellung führen?
|
2. Charaktere: Wollen sie einen Charakter aus einem früheren Spiel wiederverwenden, einen komplett neuen, fertigen Charakter mitbringen (Name, Klasse, Rasse, Stats), oder sollst du sie durch die Charaktererstellung führen? Nennt jemand einen Charakternamen, den er schon einmal gespielt hat, rufe SOFORT link_existing_character auf, statt nach Werten zu fragen — das Werkzeug liefert dir das komplette vorhandene Blatt zurück (oder meldet, dass es keinen Treffer gibt, dann fragt du nach oder legt neu an).
|
||||||
3. Regelkenntnis: Brauchen sie Erklärungen zu Grundmechaniken (Würfelwürfe, Angriffe, Rettungswürfe) oder reicht ein knapper Hinweis?
|
3. Regelkenntnis: Brauchen sie Erklärungen zu Grundmechaniken (Würfelwürfe, Angriffe, Rettungswürfe) oder reicht ein knapper Hinweis?
|
||||||
4. Setting/Welt: Vorgefertigte Welt (z. B. Forgotten Realms), eine von dir erfundene Welt, oder wünschen sie sich ein bestimmtes Thema/Genre (High Fantasy, düster, humorvoll, Horror, Piraten, ...)?
|
4. Setting/Welt: Vorgefertigte Welt (z. B. Forgotten Realms), eine von dir erfundene Welt, oder wünschen sie sich ein bestimmtes Thema/Genre (High Fantasy, düster, humorvoll, Horror, Piraten, ...)?
|
||||||
5. Umfang: Einzelnes One-Shot-Abenteuer (eine Sitzung) oder eine längere Kampagne über mehrere Sitzungen? Grobe Zeit, die sie investieren wollen?
|
5. Umfang: Einzelnes One-Shot-Abenteuer (eine Sitzung) oder eine längere Kampagne über mehrere Sitzungen? Grobe Zeit, die sie investieren wollen?
|
||||||
@@ -19,7 +19,8 @@ Phase 2: Das Spiel leiten
|
|||||||
- Fertigkeits-/Rettungswurf gegen einen bekannten Schwierigkeitsgrad: nenne Fähigkeit und SG direkt (z. B. „B) Die Läden zuwerfen (Stärke, SG 12)"), damit der Spieler seine Chancen vorher einschätzen kann.
|
- Fertigkeits-/Rettungswurf gegen einen bekannten Schwierigkeitsgrad: nenne Fähigkeit und SG direkt (z. B. „B) Die Läden zuwerfen (Stärke, SG 12)"), damit der Spieler seine Chancen vorher einschätzen kann.
|
||||||
- Angriffswurf gegen die Rüstungsklasse eines Gegners: die RK ist geheimes DM-Wissen und wird nicht verraten, aber sag ausdrücklich, dass es ein Angriffswurf ist (z. B. „A) Angriff mit dem Streitkolben (Angriffswurf)"), damit klar ist, dass trotzdem gewürfelt wird.
|
- Angriffswurf gegen die Rüstungsklasse eines Gegners: die RK ist geheimes DM-Wissen und wird nicht verraten, aber sag ausdrücklich, dass es ein Angriffswurf ist (z. B. „A) Angriff mit dem Streitkolben (Angriffswurf)"), damit klar ist, dass trotzdem gewürfelt wird.
|
||||||
- Keine Probe nötig (z. B. reine Bewegung, automatischer Erfolg): das darfst du auch explizit so sagen.
|
- Keine Probe nötig (z. B. reine Bewegung, automatischer Erfolg): das darfst du auch explizit so sagen.
|
||||||
* Für Würfelproben: Nenne IMMER zuerst klar, was gewürfelt wird (Fähigkeit + SG, oder „Angriffswurf") – bevor gewürfelt wird. Würfle IMMER selbst über das roll_dice-Werkzeug, sofort, im selben Zug – fordere den Spieler NICHT auf, selbst zu würfeln oder dir ein Ergebnis zu nennen, und warte nicht auf eine Bestätigung. Das gilt ausnahmslos, außer ein Spieler hat ausdrücklich gesagt, dass er lieber mit eigenen physischen Würfeln spielt und dir die Ergebnisse selbst mitteilt (dann fragst du vorher, was er bevorzugt). Ohne eine solche Ansage würfelst du immer selbst, nie erfindest du ein Ergebnis. Erkläre das Ergebnis danach ausführlich in dieser Reihenfolge: (1) wogegen gewürfelt wurde (SG bei Proben; bei Angriffswürfen ohne die RK zu nennen), (2) gewürfeltes Ergebnis inklusive Bonus, (3) ob es reicht/trifft oder nicht – erst danach folgt die erzählerische Konsequenz.
|
* Für Würfelproben: Nenne IMMER zuerst klar, was gewürfelt wird (Fähigkeit + SG, oder „Angriffswurf") – bevor gewürfelt wird. Rufe dafür IMMER das roll_dice-Werkzeug auf, sofort, im selben Zug – erfinde nie selbst ein Ergebnis und frage nicht erst, ob du würfeln sollst. Manche Spieler würfeln lieber mit eigenen physischen Würfeln (per Schalter in der Oberfläche eingestellt, nicht von dir gesteuert) – das erkennst du automatisch am Ergebnis von roll_dice: liefert es eine Zahl, erkläre sie sofort wie gewohnt; meldet es stattdessen "awaiting_player_roll", folge exakt der Anweisung im "note"-Feld (nenne die Notation, warte auf die Zahl in einer künftigen Nachricht, würfle nicht selbst). Erkläre ein echtes Ergebnis danach ausführlich in dieser Reihenfolge: (1) wogegen gewürfelt wurde (SG bei Proben; bei Angriffswürfen ohne die RK zu nennen), (2) gewürfeltes Ergebnis inklusive Bonus, (3) ob es reicht/trifft oder nicht – erst danach folgt die erzählerische Konsequenz.
|
||||||
|
* Stehen unten "Bekannte Charakterblätter", sind diese Charaktere bereits vollständig vorhanden (z. B. aus einem früheren Spiel wiederverwendet) — frag NICHT erneut nach Werten, Ausrüstung oder Hintergrund, nutze die Daten direkt und aktualisiere nur bei echten Änderungen über upsert_character_sheet.
|
||||||
* Trefferpunkte: Pflege current_hp/max_hp bei jeder Änderung (Schaden, Heilung, Erstellung) über upsert_character_sheet. Fällt ein Charakter auf 0 TP oder darunter, endet die Session automatisch serverseitig – erzähle das Ende dramaturgisch passend (Niederlage), aber erfinde danach keine Rettung oder Fortsetzung mehr.
|
* Trefferpunkte: Pflege current_hp/max_hp bei jeder Änderung (Schaden, Heilung, Erstellung) über upsert_character_sheet. Fällt ein Charakter auf 0 TP oder darunter, endet die Session automatisch serverseitig – erzähle das Ende dramaturgisch passend (Niederlage), aber erfinde danach keine Rettung oder Fortsetzung mehr.
|
||||||
* Monster/NPCs in einem Kampf: Pflege deren TP ebenso über update_monster_hp bei jeder Änderung (Auftauchen, Schaden). Das ist reines Hintergrund-Tracking, nie den Spielern zeigen (RK/TP bleiben geheim wie bisher). Meldet das Werkzeug "defeated": true, ist der Gegner besiegt – erzähle das entsprechend, das beendet aber nicht automatisch die Session (nutze dafür bei Bedarf end_game).
|
* Monster/NPCs in einem Kampf: Pflege deren TP ebenso über update_monster_hp bei jeder Änderung (Auftauchen, Schaden). Das ist reines Hintergrund-Tracking, nie den Spielern zeigen (RK/TP bleiben geheim wie bisher). Meldet das Werkzeug "defeated": true, ist der Gegner besiegt – erzähle das entsprechend, das beendet aber nicht automatisch die Session (nutze dafür bei Bedarf end_game).
|
||||||
* Erreicht die Handlung einen echten Abschluss (Sieg, gelöste Haupthandlung eines One-Shots), rufe end_game mit einer kurzen Begründung auf. Nutze es nicht für bloße Szenenwechsel, sondern nur für ein echtes Ende der Geschichte.
|
* Erreicht die Handlung einen echten Abschluss (Sieg, gelöste Haupthandlung eines One-Shots), rufe end_game mit einer kurzen Begründung auf. Nutze es nicht für bloße Szenenwechsel, sondern nur für ein echtes Ende der Geschichte.
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ TOOL_SCHEMA = {
|
|||||||
"name": "roll_dice",
|
"name": "roll_dice",
|
||||||
"description": (
|
"description": (
|
||||||
"Roll dice using standard D&D notation (e.g. '1d20+5', '2d6', 'd8-1'). "
|
"Roll dice using standard D&D notation (e.g. '1d20+5', '2d6', 'd8-1'). "
|
||||||
"Always use this tool for any dice roll that affects the game — never invent or guess a result yourself."
|
"Always use this tool for any dice roll that affects the game — never invent or guess a result yourself. "
|
||||||
|
"If the player rolls their own physical dice, this tool won't return a number — it tells you to ask for "
|
||||||
|
"the roll instead; see the tool result for exact wording."
|
||||||
),
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -28,7 +30,10 @@ TOOL_SCHEMA = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def roll(notation: str) -> dict:
|
def parse_notation(notation: str) -> tuple[int, int, int]:
|
||||||
|
"""Validates and parses dice notation into (count, sides, modifier). Raises ValueError on
|
||||||
|
anything malformed or out of range — used both by roll() and to validate a notation when
|
||||||
|
the player is rolling it themselves, before we ever touch the RNG."""
|
||||||
match = _NOTATION_RE.match(notation)
|
match = _NOTATION_RE.match(notation)
|
||||||
if not match:
|
if not match:
|
||||||
raise ValueError(f"Invalid dice notation: {notation!r}")
|
raise ValueError(f"Invalid dice notation: {notation!r}")
|
||||||
@@ -44,6 +49,12 @@ def roll(notation: str) -> dict:
|
|||||||
if sign == "-":
|
if sign == "-":
|
||||||
modifier = -modifier
|
modifier = -modifier
|
||||||
|
|
||||||
|
return count, sides, modifier
|
||||||
|
|
||||||
|
|
||||||
|
def roll(notation: str) -> dict:
|
||||||
|
count, sides, modifier = parse_notation(notation)
|
||||||
|
|
||||||
rolls = [_rng.randint(1, sides) for _ in range(count)]
|
rolls = [_rng.randint(1, sides) for _ in range(count)]
|
||||||
total = sum(rolls) + modifier
|
total = sum(rolls) + modifier
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import uuid
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from app.models.character import Character
|
||||||
|
from app.models.game import GameParticipant
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
|
TOOL_SCHEMA = {
|
||||||
|
"name": "link_existing_character",
|
||||||
|
"description": (
|
||||||
|
"Call this when a player wants to bring a character they already created in a previous "
|
||||||
|
"game, identified by name — instead of building a new one. Looks the character up among "
|
||||||
|
"that player's own characters and links it to this game. Returns the full existing sheet "
|
||||||
|
"(stats, combat stats, abilities, equipment, backstory) so you can continue with real data "
|
||||||
|
"immediately instead of asking for it again. Do NOT use this to create a new character — "
|
||||||
|
"use upsert_character_sheet for that."
|
||||||
|
),
|
||||||
|
"parameters": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"player_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "The real first name of the player this character belongs to, exactly as they introduced themselves.",
|
||||||
|
},
|
||||||
|
"character_name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "The character's name, as the player stated it.",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["player_name", "character_name"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def link(session: AsyncSession, game_id: uuid.UUID, tool_input: dict) -> dict:
|
||||||
|
player_name = tool_input["player_name"]
|
||||||
|
character_name = tool_input["character_name"]
|
||||||
|
|
||||||
|
participant_row = (
|
||||||
|
await session.execute(
|
||||||
|
select(GameParticipant, User)
|
||||||
|
.join(User, User.id == GameParticipant.user_id)
|
||||||
|
.where(GameParticipant.game_id == game_id, User.name == player_name)
|
||||||
|
)
|
||||||
|
).first()
|
||||||
|
if participant_row is None:
|
||||||
|
raise ValueError(f"No participant named {player_name!r} found in this game")
|
||||||
|
participant, user = participant_row
|
||||||
|
|
||||||
|
# Only ever search the requesting player's own characters — never let the DM link a
|
||||||
|
# character belonging to someone else, even if the name happens to match.
|
||||||
|
candidates = (
|
||||||
|
await session.execute(select(Character).where(Character.owner_id == user.id))
|
||||||
|
).scalars().all()
|
||||||
|
match = next(
|
||||||
|
(c for c in candidates if c.name.strip().lower() == character_name.strip().lower()), None
|
||||||
|
)
|
||||||
|
if match is None:
|
||||||
|
return {
|
||||||
|
"found": False,
|
||||||
|
"message": (
|
||||||
|
f"No character named {character_name!r} found for {player_name}. Ask them to "
|
||||||
|
"double-check the name, or offer to create a new character instead."
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
participant.character_id = match.id
|
||||||
|
await session.commit()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"found": True,
|
||||||
|
"character_id": str(match.id),
|
||||||
|
"name": match.name,
|
||||||
|
"race": match.race,
|
||||||
|
"char_class": match.char_class,
|
||||||
|
"level": match.level,
|
||||||
|
"stats": match.stats,
|
||||||
|
"combat_stats": match.combat_stats,
|
||||||
|
"current_hp": match.current_hp,
|
||||||
|
"max_hp": match.max_hp,
|
||||||
|
"abilities": match.abilities,
|
||||||
|
"equipment": match.equipment,
|
||||||
|
"description": match.description,
|
||||||
|
}
|
||||||
@@ -51,4 +51,10 @@ class GameParticipant(Base):
|
|||||||
character_id: Mapped[uuid.UUID | None] = mapped_column(
|
character_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||||
UUID(as_uuid=True), ForeignKey("characters.id"), nullable=True
|
UUID(as_uuid=True), ForeignKey("characters.id"), nullable=True
|
||||||
)
|
)
|
||||||
|
# Player preference: roll their own physical dice and report the result, instead of the
|
||||||
|
# DM rolling for them via roll_dice.
|
||||||
|
self_rolls: Mapped[bool] = mapped_column(nullable=False, default=False)
|
||||||
|
# Set by roll_dice when self_rolls is on: {"notation": ..., "reason": ...} for the roll the
|
||||||
|
# DM is waiting on this player to report. Cleared once the next turn consumes it.
|
||||||
|
pending_roll: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
|
||||||
joined_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
joined_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
|
||||||
|
|||||||
@@ -25,8 +25,14 @@ class GameRead(BaseModel):
|
|||||||
status: str
|
status: str
|
||||||
ended_reason: str | None
|
ended_reason: str | None
|
||||||
has_adventure: bool
|
has_adventure: bool
|
||||||
|
my_self_rolls: bool
|
||||||
|
my_pending_roll: dict | None
|
||||||
|
|
||||||
|
|
||||||
class GameJoin(BaseModel):
|
class GameJoin(BaseModel):
|
||||||
participation_code: str
|
participation_code: str
|
||||||
character_id: uuid.UUID | None = None
|
character_id: uuid.UUID | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class SelfRollsUpdate(BaseModel):
|
||||||
|
self_rolls: bool
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ export interface Game {
|
|||||||
status: "active" | "ended";
|
status: "active" | "ended";
|
||||||
ended_reason: string | null;
|
ended_reason: string | null;
|
||||||
has_adventure: boolean;
|
has_adventure: boolean;
|
||||||
|
my_self_rolls: boolean;
|
||||||
|
my_pending_roll: { notation: string; reason: string } | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Message {
|
export interface Message {
|
||||||
@@ -62,6 +64,12 @@ export const getGame = (id: string) => apiFetch<Game>(`/api/games/${id}`);
|
|||||||
|
|
||||||
export const deleteGame = (id: string) => apiFetch<void>(`/api/games/${id}`, { method: "DELETE" });
|
export const deleteGame = (id: string) => apiFetch<void>(`/api/games/${id}`, { method: "DELETE" });
|
||||||
|
|
||||||
|
export const setSelfRolls = (id: string, selfRolls: boolean) =>
|
||||||
|
apiFetch<Game>(`/api/games/${id}/self-rolls`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify({ self_rolls: selfRolls }),
|
||||||
|
});
|
||||||
|
|
||||||
export const joinGame = (id: string, participation_code: string, character_id?: string) =>
|
export const joinGame = (id: string, participation_code: string, character_id?: string) =>
|
||||||
apiFetch<Game>(`/api/games/${id}/join`, {
|
apiFetch<Game>(`/api/games/${id}/join`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
|
||||||
import { Message } from "../api/games";
|
import { Message } from "../api/games";
|
||||||
|
import { AwaitingRoll } from "../hooks/useGameSocket";
|
||||||
import MarkdownContent from "./MarkdownContent";
|
import MarkdownContent from "./MarkdownContent";
|
||||||
|
|
||||||
const DICE_FACES = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"];
|
const DICE_FACES = ["⚀", "⚁", "⚂", "⚃", "⚄", "⚅"];
|
||||||
@@ -37,16 +38,18 @@ export default function TranscriptPane({
|
|||||||
messages,
|
messages,
|
||||||
typing,
|
typing,
|
||||||
rolling,
|
rolling,
|
||||||
|
awaitingRoll,
|
||||||
}: {
|
}: {
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
typing?: boolean;
|
typing?: boolean;
|
||||||
rolling?: string | null;
|
rolling?: string | null;
|
||||||
|
awaitingRoll?: AwaitingRoll | null;
|
||||||
}) {
|
}) {
|
||||||
const bottomRef = useRef<HTMLDivElement>(null);
|
const bottomRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
bottomRef.current?.scrollIntoView({ block: "end" });
|
bottomRef.current?.scrollIntoView({ block: "end" });
|
||||||
}, [messages, typing, rolling]);
|
}, [messages, typing, rolling, awaitingRoll]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-full flex-col gap-3 overflow-y-auto p-4">
|
<div className="flex h-full flex-col gap-3 overflow-y-auto p-4">
|
||||||
@@ -66,7 +69,16 @@ export default function TranscriptPane({
|
|||||||
<MarkdownContent content={m.content} />
|
<MarkdownContent content={m.content} />
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
{rolling != null ? (
|
{awaitingRoll ? (
|
||||||
|
<div className="rounded-lg border border-amber-500/50 bg-amber-500/10 px-4 py-3">
|
||||||
|
<span className="font-semibold text-amber-400">🎲 Du bist am Zug — würfle:</span>{" "}
|
||||||
|
<span className="font-mono text-slate-100">{awaitingRoll.notation}</span>
|
||||||
|
{awaitingRoll.reason && <span className="text-sm text-slate-400"> ({awaitingRoll.reason})</span>}
|
||||||
|
<p className="mt-1 text-xs text-slate-500">
|
||||||
|
Wirf deinen Würfel und schreib das Ergebnis als Nachricht.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : rolling != null ? (
|
||||||
<DiceRollAnimation notation={rolling} />
|
<DiceRollAnimation notation={rolling} />
|
||||||
) : (
|
) : (
|
||||||
typing && (
|
typing && (
|
||||||
|
|||||||
@@ -3,6 +3,11 @@ import { useEffect, useRef } from "react";
|
|||||||
import { apiFetch } from "../api/client";
|
import { apiFetch } from "../api/client";
|
||||||
import { Message } from "../api/games";
|
import { Message } from "../api/games";
|
||||||
|
|
||||||
|
export interface AwaitingRoll {
|
||||||
|
notation: string;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
|
||||||
export function useGameSocket(
|
export function useGameSocket(
|
||||||
gameId: string | undefined,
|
gameId: string | undefined,
|
||||||
onMessage: (message: Message) => void,
|
onMessage: (message: Message) => void,
|
||||||
@@ -10,6 +15,7 @@ export function useGameSocket(
|
|||||||
onTyping: () => void,
|
onTyping: () => void,
|
||||||
onRolling: (notation: string) => void,
|
onRolling: (notation: string) => void,
|
||||||
onGameEnded: (reason: string) => void,
|
onGameEnded: (reason: string) => void,
|
||||||
|
onAwaitingRoll: (roll: AwaitingRoll) => void,
|
||||||
) {
|
) {
|
||||||
const wsRef = useRef<WebSocket | null>(null);
|
const wsRef = useRef<WebSocket | null>(null);
|
||||||
const onMessageRef = useRef(onMessage);
|
const onMessageRef = useRef(onMessage);
|
||||||
@@ -22,6 +28,8 @@ export function useGameSocket(
|
|||||||
onRollingRef.current = onRolling;
|
onRollingRef.current = onRolling;
|
||||||
const onGameEndedRef = useRef(onGameEnded);
|
const onGameEndedRef = useRef(onGameEnded);
|
||||||
onGameEndedRef.current = onGameEnded;
|
onGameEndedRef.current = onGameEnded;
|
||||||
|
const onAwaitingRollRef = useRef(onAwaitingRoll);
|
||||||
|
onAwaitingRollRef.current = onAwaitingRoll;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!gameId) return;
|
if (!gameId) return;
|
||||||
@@ -43,6 +51,8 @@ export function useGameSocket(
|
|||||||
else if (data.type === "typing") onTypingRef.current();
|
else if (data.type === "typing") onTypingRef.current();
|
||||||
else if (data.type === "rolling") onRollingRef.current(data.notation ?? "");
|
else if (data.type === "rolling") onRollingRef.current(data.notation ?? "");
|
||||||
else if (data.type === "game_ended") onGameEndedRef.current(data.reason ?? "");
|
else if (data.type === "game_ended") onGameEndedRef.current(data.reason ?? "");
|
||||||
|
else if (data.type === "awaiting_roll")
|
||||||
|
onAwaitingRollRef.current({ notation: data.notation ?? "", reason: data.reason ?? "" });
|
||||||
};
|
};
|
||||||
ws.onclose = () => {
|
ws.onclose = () => {
|
||||||
if (!intentionalClose) onErrorRef.current("connection_lost");
|
if (!intentionalClose) onErrorRef.current("connection_lost");
|
||||||
|
|||||||
@@ -2,10 +2,18 @@ import { FormEvent, useEffect, useState } from "react";
|
|||||||
import { Link, useParams, useSearchParams } from "react-router-dom";
|
import { Link, useParams, useSearchParams } from "react-router-dom";
|
||||||
|
|
||||||
import { listCharacters, Character } from "../api/characters";
|
import { listCharacters, Character } from "../api/characters";
|
||||||
import { Game, getFullMessages, getGame, getRecentMessages, joinGame, Message } from "../api/games";
|
import {
|
||||||
|
Game,
|
||||||
|
getFullMessages,
|
||||||
|
getGame,
|
||||||
|
getRecentMessages,
|
||||||
|
joinGame,
|
||||||
|
Message,
|
||||||
|
setSelfRolls,
|
||||||
|
} from "../api/games";
|
||||||
import SendMessageForm from "../components/SendMessageForm";
|
import SendMessageForm from "../components/SendMessageForm";
|
||||||
import TranscriptPane from "../components/TranscriptPane";
|
import TranscriptPane from "../components/TranscriptPane";
|
||||||
import { useGameSocket } from "../hooks/useGameSocket";
|
import { AwaitingRoll, useGameSocket } from "../hooks/useGameSocket";
|
||||||
|
|
||||||
export default function GameSession() {
|
export default function GameSession() {
|
||||||
const { gameId } = useParams<{ gameId: string }>();
|
const { gameId } = useParams<{ gameId: string }>();
|
||||||
@@ -23,12 +31,15 @@ export default function GameSession() {
|
|||||||
const [isTyping, setIsTyping] = useState(false);
|
const [isTyping, setIsTyping] = useState(false);
|
||||||
const [rollingNotation, setRollingNotation] = useState<string | null>(null);
|
const [rollingNotation, setRollingNotation] = useState<string | null>(null);
|
||||||
const [endedReason, setEndedReason] = useState<string | null>(null);
|
const [endedReason, setEndedReason] = useState<string | null>(null);
|
||||||
|
const [awaitingRoll, setAwaitingRoll] = useState<AwaitingRoll | null>(null);
|
||||||
|
const [selfRollsSaving, setSelfRollsSaving] = useState(false);
|
||||||
|
|
||||||
async function loadGame() {
|
async function loadGame() {
|
||||||
if (!gameId) return;
|
if (!gameId) return;
|
||||||
const g = await getGame(gameId);
|
const g = await getGame(gameId);
|
||||||
setGame(g);
|
setGame(g);
|
||||||
setEndedReason(g.status === "ended" ? g.ended_reason : null);
|
setEndedReason(g.status === "ended" ? g.ended_reason : null);
|
||||||
|
setAwaitingRoll(g.my_pending_roll ?? null);
|
||||||
return g;
|
return g;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,6 +76,7 @@ export default function GameSession() {
|
|||||||
try {
|
try {
|
||||||
const g = await joinGame(gameId, joinCode, selectedCharacterId || undefined);
|
const g = await joinGame(gameId, joinCode, selectedCharacterId || undefined);
|
||||||
setGame(g);
|
setGame(g);
|
||||||
|
setAwaitingRoll(g.my_pending_roll ?? null);
|
||||||
await loadRecent();
|
await loadRecent();
|
||||||
} catch {
|
} catch {
|
||||||
setJoinError("Beitritt fehlgeschlagen — Teilnahmecode prüfen.");
|
setJoinError("Beitritt fehlgeschlagen — Teilnahmecode prüfen.");
|
||||||
@@ -106,9 +118,23 @@ export default function GameSession() {
|
|||||||
() => setIsTyping(true),
|
() => setIsTyping(true),
|
||||||
(notation) => setRollingNotation(notation),
|
(notation) => setRollingNotation(notation),
|
||||||
(reason) => setEndedReason(reason),
|
(reason) => setEndedReason(reason),
|
||||||
|
(roll) => setAwaitingRoll(roll),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
async function handleToggleSelfRolls(checked: boolean) {
|
||||||
|
if (!gameId) return;
|
||||||
|
setSelfRollsSaving(true);
|
||||||
|
try {
|
||||||
|
const updated = await setSelfRolls(gameId, checked);
|
||||||
|
setGame(updated);
|
||||||
|
if (!checked) setAwaitingRoll(null);
|
||||||
|
} finally {
|
||||||
|
setSelfRollsSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSend(content: string) {
|
async function handleSend(content: string) {
|
||||||
|
setAwaitingRoll(null);
|
||||||
send(content);
|
send(content);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,7 +194,17 @@ export default function GameSession() {
|
|||||||
</h1>
|
</h1>
|
||||||
<p className="text-xs text-slate-500">{game.description}</p>
|
<p className="text-xs text-slate-500">{game.description}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2">
|
<div className="flex items-center gap-3">
|
||||||
|
<label className="flex items-center gap-1.5 text-sm text-slate-400" title="Statt dass der Dungeon Master für dich würfelt, sagt er dir nur noch, was zu würfeln ist — du würfelst selbst und teilst das Ergebnis mit.">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={game.my_self_rolls}
|
||||||
|
disabled={selfRollsSaving}
|
||||||
|
onChange={(e) => handleToggleSelfRolls(e.target.checked)}
|
||||||
|
className="h-4 w-4 accent-amber-500"
|
||||||
|
/>
|
||||||
|
Ich würfle selbst
|
||||||
|
</label>
|
||||||
{game.my_character_id && (
|
{game.my_character_id && (
|
||||||
<Link
|
<Link
|
||||||
to={`/characters/${game.my_character_id}?back=${gameId}`}
|
to={`/characters/${game.my_character_id}?back=${gameId}`}
|
||||||
@@ -193,7 +229,12 @@ export default function GameSession() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-1 flex-col overflow-hidden rounded-lg border border-slate-800 bg-slate-900">
|
<div className="flex flex-1 flex-col overflow-hidden rounded-lg border border-slate-800 bg-slate-900">
|
||||||
<TranscriptPane messages={messages} typing={isTyping} rolling={rollingNotation} />
|
<TranscriptPane
|
||||||
|
messages={messages}
|
||||||
|
typing={isTyping}
|
||||||
|
rolling={rollingNotation}
|
||||||
|
awaitingRoll={awaitingRoll}
|
||||||
|
/>
|
||||||
<SendMessageForm onSend={handleSend} />
|
<SendMessageForm onSend={handleSend} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user