Let players roll their own physical dice instead of the DM
Adds the "Ich würfle selbst" checkbox the user asked for, plus the
structural piece that makes it actually reliable: a tool call can't
block mid-turn waiting for a human to go find a d20, so this can't be
a pure client-side toggle — the DM has to think in two turns (ask,
then later recognize the answer), and it's easy for an LLM to lose
track of that across a real gap in the conversation.
game_participants gets self_rolls (the toggle) and pending_roll (what
roll is currently awaited, if any). When self_rolls is on, roll_dice
doesn't touch the RNG — it validates the notation, stores it as
pending_roll, and returns an "awaiting_player_roll" result that tells
the DM to ask for that exact roll and wait, never inventing a number.
At the top of the player's next turn, orchestrator.run_dm_turn reads
back any pending_roll, injects it as an explicit reminder into the
system prompt ("the player's message is probably answering this"),
and clears it — so the DM doesn't have to rely on remembering what it
asked for several messages ago.
Frontend: the checkbox lives in the game header (PATCH
/api/games/{id}/self-rolls, per-participant). A persistent "🎲 Du bist
am Zug" banner shows the pending notation/reason — persistent, not
transient like the typing/rolling indicators, since answering it means
physically finding a die and rolling, which takes real time. It's
seeded from GameRead.my_pending_roll on load so it survives a page
reload, and only clears when the player actually sends their next
message (not when the DM's message arrives, which would make it
disappear before there was time to read it).
Verified live end-to-end against x.ai in a real session: toggled the
setting, asked for something requiring a check, got "würfle bitte
1d20+1" instead of an auto-rolled result, confirmed the banner
survived a full page reload, replied "14", and the DM used that
number directly ("Du hast 14 gewürfelt — das reicht") without
re-rolling — with pending_roll correctly cleared in the DB afterward.
Also confirmed per-participant scoping (a second participant's flag
stayed off) and that toggling back off works cleanly.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -54,6 +54,34 @@ async def _execute_tool_call(
|
||||
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."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
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."""
|
||||
@@ -76,12 +104,38 @@ async def run_dm_turn(
|
||||
session: AsyncSession,
|
||||
game_id: uuid.UUID,
|
||||
latest_player_message: str | None = None,
|
||||
user_id: uuid.UUID | 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,
|
||||
) -> Message:
|
||||
client = get_llm_client()
|
||||
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)
|
||||
if game is not None:
|
||||
system_prompt = (
|
||||
@@ -145,9 +199,17 @@ async def run_dm_turn(
|
||||
|
||||
for tool_call in message.tool_calls:
|
||||
tool_input = fix_double_escaped_unicode(json.loads(tool_call.function.arguments))
|
||||
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)
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
@@ -19,7 +19,7 @@ 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.
|
||||
- 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.
|
||||
* 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.
|
||||
* 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).
|
||||
* 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",
|
||||
"description": (
|
||||
"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": {
|
||||
"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)
|
||||
if not match:
|
||||
raise ValueError(f"Invalid dice notation: {notation!r}")
|
||||
@@ -44,6 +49,12 @@ def roll(notation: str) -> dict:
|
||||
if sign == "-":
|
||||
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)]
|
||||
total = sum(rolls) + modifier
|
||||
|
||||
|
||||
Reference in New Issue
Block a user