From 8da834c5c109969e1639d5e63355e71666da3a55 Mon Sep 17 00:00:00 2001 From: Thorsten Date: Tue, 1 Sep 2026 17:44:46 +0200 Subject: [PATCH] Add game end status with an end_game DM tool and automatic 0-HP detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Games now have a status/ended_reason pair. The DM can call the new end_game tool when the story reaches a real conclusion (victory, defeat, or a resolved one-shot), and the backend independently ends the game whenever a character's HP drops to 0 or below, regardless of whether the DM narrates it. The frontend shows a banner and a "Beendet" badge once a game ends. HP moves from the freeform combat_stats bag into dedicated current_hp/max_hp columns on Character, since reliably detecting 0 HP requires a real integer rather than parsing strings like "3/10" out of an LLM-authored key/value dict. Also fixed combat_stats to fully replace on each upsert instead of merging, matching its documented contract — the merge was leaving stale keys (old HP/TP text) behind after the model stopped sending them. Co-Authored-By: Claude Sonnet 5 --- ...e7f316_add_game_status_and_character_hp.py | 34 ++++++++++++++++ backend/app/api/routes_games.py | 2 + backend/app/api/ws_game.py | 9 ++++- backend/app/llm/orchestrator.py | 35 +++++++++++++++- backend/app/llm/prompts/dm_system_prompt.txt | 2 + backend/app/llm/tools/character_sheet.py | 31 +++++++++++--- backend/app/llm/tools/end_game.py | 40 +++++++++++++++++++ backend/app/models/character.py | 2 + backend/app/models/game.py | 2 + backend/app/schemas/character.py | 2 + backend/app/schemas/game.py | 2 + frontend/src/api/characters.ts | 2 + frontend/src/api/games.ts | 2 + frontend/src/components/GameCard.tsx | 5 +++ frontend/src/hooks/useGameSocket.ts | 4 ++ frontend/src/pages/CharacterDetail.tsx | 21 +++++++++- frontend/src/pages/GameSession.tsx | 9 +++++ 17 files changed, 196 insertions(+), 8 deletions(-) create mode 100644 backend/app/alembic/versions/c9a1d5e7f316_add_game_status_and_character_hp.py create mode 100644 backend/app/llm/tools/end_game.py diff --git a/backend/app/alembic/versions/c9a1d5e7f316_add_game_status_and_character_hp.py b/backend/app/alembic/versions/c9a1d5e7f316_add_game_status_and_character_hp.py new file mode 100644 index 0000000..ebf18c0 --- /dev/null +++ b/backend/app/alembic/versions/c9a1d5e7f316_add_game_status_and_character_hp.py @@ -0,0 +1,34 @@ +"""add game status/ended_reason and character current_hp/max_hp + +Revision ID: c9a1d5e7f316 +Revises: b8e4f1a9c203 +Create Date: 2026-09-01 16:00:00.000000 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision: str = 'c9a1d5e7f316' +down_revision: Union[str, None] = 'b8e4f1a9c203' +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.add_column( + 'games', + sa.Column('status', sa.String(length=20), nullable=False, server_default='active'), + ) + op.add_column('games', sa.Column('ended_reason', sa.Text(), nullable=True)) + op.add_column('characters', sa.Column('current_hp', sa.Integer(), nullable=True)) + op.add_column('characters', sa.Column('max_hp', sa.Integer(), nullable=True)) + + +def downgrade() -> None: + op.drop_column('characters', 'max_hp') + op.drop_column('characters', 'current_hp') + op.drop_column('games', 'ended_reason') + op.drop_column('games', 'status') diff --git a/backend/app/api/routes_games.py b/backend/app/api/routes_games.py index 0ff8b7c..cb28043 100644 --- a/backend/app/api/routes_games.py +++ b/backend/app/api/routes_games.py @@ -71,6 +71,8 @@ async def _serialize_games( created_at=game.created_at, is_participant=is_participant, my_character_id=viewer_participation.get(game.id), + status=game.status, + ended_reason=game.ended_reason, ) ) return result diff --git a/backend/app/api/ws_game.py b/backend/app/api/ws_game.py index c199b7f..77bdaea 100644 --- a/backend/app/api/ws_game.py +++ b/backend/app/api/ws_game.py @@ -123,9 +123,16 @@ async def game_websocket(websocket: WebSocket, game_id: uuid.UUID, ticket: str) async def _broadcast_roll(notation: str) -> None: await manager.broadcast(game_id, {"type": "rolling", "notation": notation}) + async def _broadcast_game_ended(reason: str) -> None: + await manager.broadcast(game_id, {"type": "game_ended", "reason": reason}) + try: dm_message = await run_dm_turn( - session, game_id, latest_player_message=content, on_roll=_broadcast_roll + session, + game_id, + latest_player_message=content, + on_roll=_broadcast_roll, + on_game_ended=_broadcast_game_ended, ) except Exception: # noqa: BLE001 logger.exception("DM turn failed for game %s", game_id) diff --git a/backend/app/llm/orchestrator.py b/backend/app/llm/orchestrator.py index f49d113..0941fef 100644 --- a/backend/app/llm/orchestrator.py +++ b/backend/app/llm/orchestrator.py @@ -9,7 +9,7 @@ from app.config import settings from app.llm.client import get_dm_system_prompt, get_llm_client from app.llm.context import build_context from app.llm.json_utils import fix_double_escaped_unicode -from app.llm.tools import character_sheet, dice +from app.llm.tools import character_sheet, dice, end_game from app.models.game import Game from app.models.message import Message from app.rag.retrieval import build_rag_block @@ -22,6 +22,7 @@ MAX_TOKENS = 4096 TOOLS = [ {"type": "function", "function": dice.TOOL_SCHEMA}, {"type": "function", "function": character_sheet.TOOL_SCHEMA}, + {"type": "function", "function": end_game.TOOL_SCHEMA}, ] @@ -35,6 +36,8 @@ async def _execute_tool_call( return dice.roll(tool_input["notation"]) if tool_name == "upsert_character_sheet": return await character_sheet.upsert(session, game_id, tool_input) + if tool_name == "end_game": + return await end_game.end(session, game_id, tool_input) return {"error": f"Unknown tool {tool_name!r}"} except Exception as exc: # noqa: BLE001 logger.warning("Tool call %s failed: %s", tool_name, exc) @@ -42,11 +45,30 @@ async def _execute_tool_call( return {"error": str(exc)} +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 + dropped to 0 HP or below. Returns the end reason if the game was just ended, else None.""" + current_hp = result.get("current_hp") + if current_hp is None or current_hp > 0: + return None + + game = await session.get(Game, game_id) + if game is None or game.status == "ended": + return None + + reason = f"{result.get('name', 'Ein Charakter')} ist bei {current_hp} Trefferpunkten zusammengebrochen." + game.status = "ended" + game.ended_reason = reason + await session.commit() + return reason + + async def run_dm_turn( session: AsyncSession, game_id: uuid.UUID, latest_player_message: str | None = None, on_roll: Callable[[str], Awaitable[None]] | None = None, + on_game_ended: Callable[[str], Awaitable[None]] | None = None, ) -> Message: client = get_llm_client() system_prompt = get_dm_system_prompt() @@ -90,6 +112,17 @@ async def run_dm_turn( if tool_call.function.name == "roll_dice" and on_roll is not None: await on_roll(tool_input.get("notation", "")) result = await _execute_tool_call(session, game_id, tool_call.function.name, tool_input) + + end_reason = None + if tool_call.function.name == "end_game" and "reason" in result: + end_reason = result["reason"] + elif tool_call.function.name == "upsert_character_sheet": + end_reason = await _check_hp_game_over(session, game_id, result) + if end_reason: + result = {**result, "game_ended": True, "end_reason": end_reason} + if end_reason and on_game_ended is not None: + await on_game_ended(end_reason) + messages.append( { "role": "tool", diff --git a/backend/app/llm/prompts/dm_system_prompt.txt b/backend/app/llm/prompts/dm_system_prompt.txt index e09b8bb..5a6310f 100644 --- a/backend/app/llm/prompts/dm_system_prompt.txt +++ b/backend/app/llm/prompts/dm_system_prompt.txt @@ -21,6 +21,8 @@ Phase 2: Das Spiel leiten - 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. * 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. +* 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. +* 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. * Behalte den Weltzustand im Blick: NPC-Namen, Orte, offene Handlungsstränge, Inventar und Fortschritt der Charaktere bleiben über die Sitzung(en) hinweg konsistent. * Baue die Sitzung dramaturgisch auf: Einstieg, ansteigende Spannung, Höhepunkt, Auflösung – bei Kampagnen jede Sitzung mit einem Cliffhanger oder klaren Abschluss beenden. * Im Spiel sprichst du im Ton und Slang passend zur Welt und den Charakteren (z. B. archaisch-episch in High Fantasy, derb-direkt bei Piraten). Außerhalb bleibst du locker, freundlich und klar in der Ansprache. diff --git a/backend/app/llm/tools/character_sheet.py b/backend/app/llm/tools/character_sheet.py index ac37b5f..45e0f2a 100644 --- a/backend/app/llm/tools/character_sheet.py +++ b/backend/app/llm/tools/character_sheet.py @@ -32,12 +32,24 @@ TOOL_SCHEMA = { "type": "object", "description": "Ability scores, e.g. {\"STR\": 15, \"DEX\": 12, \"CON\": 14, \"INT\": 10, \"WIS\": 8, \"CHA\": 13}", }, + "current_hp": { + "type": "integer", + "description": ( + "Current hit points. Always send this together with max_hp whenever HP changes " + "(damage, healing, character creation) — the server uses it to detect when a " + "character goes down. Do NOT also put HP/TP in combat_stats, this is the only place for it." + ), + }, + "max_hp": { + "type": "integer", + "description": "Maximum hit points. Send together with current_hp.", + }, "combat_stats": { "type": "object", "description": ( - "Key/value readouts, e.g. {\"HP\": \"13/13\", \"RK\": \"19\", \"Initiative\": \"+1\", " - "\"Tempo\": \"7,5 m\", \"Übungsbonus\": \"+2\"}. Send the full current set each time — " - "this replaces whatever was stored before." + "Key/value readouts EXCLUDING hit points (use current_hp/max_hp for those), e.g. " + "{\"RK\": \"19\", \"Initiative\": \"+1\", \"Tempo\": \"7,5 m\", \"Übungsbonus\": \"+2\"}. " + "Send the full current set each time — this replaces whatever was stored before." ), }, "abilities": { @@ -108,7 +120,11 @@ async def upsert(session: AsyncSession, game_id: uuid.UUID, tool_input: dict) -> if "stats" in tool_input and tool_input["stats"] is not None: character.stats = {**(character.stats or {}), **tool_input["stats"]} if "combat_stats" in tool_input and tool_input["combat_stats"] is not None: - character.combat_stats = {**(character.combat_stats or {}), **tool_input["combat_stats"]} + character.combat_stats = tool_input["combat_stats"] + if "current_hp" in tool_input and tool_input["current_hp"] is not None: + character.current_hp = tool_input["current_hp"] + if "max_hp" in tool_input and tool_input["max_hp"] is not None: + character.max_hp = tool_input["max_hp"] if "abilities" in tool_input and tool_input["abilities"] is not None: character.abilities = tool_input["abilities"] if "equipment" in tool_input and tool_input["equipment"] is not None: @@ -122,4 +138,9 @@ async def upsert(session: AsyncSession, game_id: uuid.UUID, tool_input: dict) -> await session.commit() await session.refresh(character) - return {"character_id": str(character.id), "name": character.name} + return { + "character_id": str(character.id), + "name": character.name, + "current_hp": character.current_hp, + "max_hp": character.max_hp, + } diff --git a/backend/app/llm/tools/end_game.py b/backend/app/llm/tools/end_game.py new file mode 100644 index 0000000..70f5fce --- /dev/null +++ b/backend/app/llm/tools/end_game.py @@ -0,0 +1,40 @@ +import uuid + +from sqlalchemy.ext.asyncio import AsyncSession + +from app.models.game import Game + +TOOL_SCHEMA = { + "name": "end_game", + "description": ( + "Call when the story reaches a real conclusion — the party wins, loses, or a one-shot's " + "plot is resolved. Marks the game as ended so players see a clear ending. Do not call this " + "just because a scene ends; only for a genuine story conclusion." + ), + "parameters": { + "type": "object", + "properties": { + "reason": { + "type": "string", + "description": ( + "A short narrative summary of how/why the story ended (victory, defeat, or " + "resolution), shown to the players, e.g. 'Das Dorf ist gerettet, die Kerze brennt wieder.'" + ), + }, + }, + "required": ["reason"], + }, +} + + +async def end(session: AsyncSession, game_id: uuid.UUID, tool_input: dict) -> dict: + game = await session.get(Game, game_id) + if game is None: + raise ValueError(f"Game {game_id} not found") + + if game.status != "ended": + game.status = "ended" + game.ended_reason = tool_input["reason"] + await session.commit() + + return {"status": "ended", "reason": game.ended_reason} diff --git a/backend/app/models/character.py b/backend/app/models/character.py index f675982..f2a2ad5 100644 --- a/backend/app/models/character.py +++ b/backend/app/models/character.py @@ -24,6 +24,8 @@ class Character(Base): stats: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict) description: Mapped[str] = mapped_column(Text, nullable=False, default="") combat_stats: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict) + current_hp: Mapped[int | None] = mapped_column(Integer, nullable=True) + max_hp: Mapped[int | None] = mapped_column(Integer, nullable=True) abilities: Mapped[list] = mapped_column(JSONB, nullable=False, default=list) equipment: Mapped[list] = mapped_column(JSONB, nullable=False, default=list) created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False) diff --git a/backend/app/models/game.py b/backend/app/models/game.py index b0f22ba..57b4a9e 100644 --- a/backend/app/models/game.py +++ b/backend/app/models/game.py @@ -22,6 +22,8 @@ class Game(Base): participation_code: Mapped[str] = mapped_column( String(length=16), unique=True, nullable=False, index=True ) + status: Mapped[str] = mapped_column(String(length=20), nullable=False, default="active") + ended_reason: Mapped[str | None] = mapped_column(Text, nullable=True) created_at: Mapped[datetime] = mapped_column( server_default=func.now(), nullable=False, index=True ) diff --git a/backend/app/schemas/character.py b/backend/app/schemas/character.py index 33006f2..67dcd13 100644 --- a/backend/app/schemas/character.py +++ b/backend/app/schemas/character.py @@ -13,6 +13,8 @@ class CharacterRead(BaseModel): level: int stats: dict combat_stats: dict + current_hp: int | None + max_hp: int | None abilities: list equipment: list description: str diff --git a/backend/app/schemas/game.py b/backend/app/schemas/game.py index 5b5be77..31ea714 100644 --- a/backend/app/schemas/game.py +++ b/backend/app/schemas/game.py @@ -21,6 +21,8 @@ class GameRead(BaseModel): created_at: datetime is_participant: bool my_character_id: uuid.UUID | None + status: str + ended_reason: str | None class GameJoin(BaseModel): diff --git a/frontend/src/api/characters.ts b/frontend/src/api/characters.ts index e21d4fb..93039cf 100644 --- a/frontend/src/api/characters.ts +++ b/frontend/src/api/characters.ts @@ -14,6 +14,8 @@ export interface Character { level: number; stats: Record; combat_stats: Record; + current_hp: number | null; + max_hp: number | null; abilities: CharacterAbility[]; equipment: string[]; description: string; diff --git a/frontend/src/api/games.ts b/frontend/src/api/games.ts index bbed7c7..d10fc21 100644 --- a/frontend/src/api/games.ts +++ b/frontend/src/api/games.ts @@ -12,6 +12,8 @@ export interface Game { created_at: string; is_participant: boolean; my_character_id: string | null; + status: "active" | "ended"; + ended_reason: string | null; } export interface Message { diff --git a/frontend/src/components/GameCard.tsx b/frontend/src/components/GameCard.tsx index 3bdc765..7d88390 100644 --- a/frontend/src/components/GameCard.tsx +++ b/frontend/src/components/GameCard.tsx @@ -12,6 +12,11 @@ export default function GameCard({ game }: { game: Game }) { >

{game.name}

+ {game.status === "ended" && ( + + Beendet + + )} {game.participation_code && ( Code: {game.participation_code} diff --git a/frontend/src/hooks/useGameSocket.ts b/frontend/src/hooks/useGameSocket.ts index 2998bc4..7aa0c65 100644 --- a/frontend/src/hooks/useGameSocket.ts +++ b/frontend/src/hooks/useGameSocket.ts @@ -9,6 +9,7 @@ export function useGameSocket( onError: (detail: string) => void, onTyping: () => void, onRolling: (notation: string) => void, + onGameEnded: (reason: string) => void, ) { const wsRef = useRef(null); const onMessageRef = useRef(onMessage); @@ -19,6 +20,8 @@ export function useGameSocket( onTypingRef.current = onTyping; const onRollingRef = useRef(onRolling); onRollingRef.current = onRolling; + const onGameEndedRef = useRef(onGameEnded); + onGameEndedRef.current = onGameEnded; useEffect(() => { if (!gameId) return; @@ -39,6 +42,7 @@ export function useGameSocket( else if (data.type === "error") onErrorRef.current(data.detail); else if (data.type === "typing") onTypingRef.current(); else if (data.type === "rolling") onRollingRef.current(data.notation ?? ""); + else if (data.type === "game_ended") onGameEndedRef.current(data.reason ?? ""); }; ws.onclose = () => { if (!intentionalClose) onErrorRef.current("connection_lost"); diff --git a/frontend/src/pages/CharacterDetail.tsx b/frontend/src/pages/CharacterDetail.tsx index 661a749..5605d0c 100644 --- a/frontend/src/pages/CharacterDetail.tsx +++ b/frontend/src/pages/CharacterDetail.tsx @@ -87,12 +87,31 @@ export default function CharacterDetail() {
)} - {Object.keys(character.combat_stats).length > 0 && ( + {(character.current_hp !== null || Object.keys(character.combat_stats).length > 0) && (

Kampfwerte

+ {character.current_hp !== null && ( +
+
+ Trefferpunkte +
+
+ {character.current_hp} + {character.max_hp !== null ? ` / ${character.max_hp}` : ""} +
+
+ )} {Object.entries(character.combat_stats).map(([key, value]) => (
(null); const [isTyping, setIsTyping] = useState(false); const [rollingNotation, setRollingNotation] = useState(null); + const [endedReason, setEndedReason] = useState(null); async function loadGame() { if (!gameId) return; const g = await getGame(gameId); setGame(g); + setEndedReason(g.status === "ended" ? g.ended_reason : null); return g; } @@ -102,6 +104,7 @@ export default function GameSession() { }, () => setIsTyping(true), (notation) => setRollingNotation(notation), + (reason) => setEndedReason(reason), ); async function handleSend(content: string) { @@ -180,6 +183,12 @@ export default function GameSession() {
+ {endedReason && ( +
+ Spiel beendet. {endedReason} +
+ )} +