Compact layout, multi-vote, step reveal, imposter weights + resolve bug fix

BUG FIX: resolve_round now reads liar_keys directly from DB via
performResolveRound() helper, bypassing loadRoom()'s redaction
(liarKeys=[] when roundOutcome is null) — fixes 0 points + no_liar bug.

resolve logic extracted into performResolveRound() used by both
manual resolve_round and auto-resolve in lock_vote.

Migration V7:
- gtl_rooms: reveal_index INT DEFAULT -1, imposter_weights VARCHAR(500)
- gtl_players: vote_locked TINYINT, vote_request TINYINT

API:
- lock_vote: stores JSON votes array, locks player, auto-resolves when all locked
- request_voting: democratic vote-start; opens voting when all players request
- reveal_next: increments reveal_index one answer at a time
- reveal/reveal_all: sets reveal_index=9999 (show all)
- update_weights: saves imposter_weights JSON per room
- resolveVotes(): handles votes[] array instead of single voteFor string
- new_round: resets vote_locked, vote_request, reveal_index, active_emojis
- assign_questions: resets vote state + reveal_index on each new question set

Layout:
- wrap max-width 640→960px for grid layout
- Player view: 3-col grid (sidebar scores | gameplay | emoji reactions)
- Host view: 2-col grid (sidebar players+tally+scores | main content)
- Compact sb-row sidebar rows with avatar + name + score

Voting:
- Multi-select checkboxes (client-side) + "Stimme abschicken" lock button
- Niemand exclusive: checking it clears other selections and vice versa
- Once locked: checkboxes hidden, confirmation shown
- Auto-resolve triggers when last player locks vote

Reveal:
- "Nächste aufdecken" reveals one answer at a time via reveal_index
- "Alle aufdecken" reveals everything at once
- Host sees which answers are still hidden vs revealed
- Players only see answers up to current reveal_index

Imposter weights:
- JSON field in host UI e.g. {"3-5":1,"6-9":2,"10+":3}
- randomImposters() reads weights to pick appropriate count
- Saved per-room via update_weights API

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
danny 2026-06-14 13:01:41 +02:00
parent 758001597c
commit e3ef770c81
3 changed files with 690 additions and 355 deletions

392
api.php
View file

@ -45,7 +45,8 @@ function loadRoom(PDO $pdo, string $code): ?array
{
$stmt = $pdo->prepare(
'SELECT code, revealed, liar_keys, normal_question, imposter_question,
round_num, voted_out_keys, round_outcome, voting_open, active_emojis
round_num, voted_out_keys, round_outcome, voting_open, active_emojis,
reveal_index, imposter_weights
FROM gtl_rooms WHERE code = ?'
);
$stmt->execute([$code]);
@ -56,8 +57,8 @@ function loadRoom(PDO $pdo, string $code): ?array
$ps = $pdo->prepare(
'SELECT p.pkey, p.name, p.user_id, p.question, p.answer, p.answered, p.score, p.vote_for,
u.avatar
'SELECT p.pkey, p.name, p.user_id, p.question, p.answer, p.answered, p.score,
p.vote_for, p.vote_locked, p.vote_request, u.avatar
FROM gtl_players p
LEFT JOIN gtl_users u ON u.id = p.user_id
WHERE p.room_code = ? ORDER BY p.id ASC'
@ -66,16 +67,28 @@ function loadRoom(PDO $pdo, string $code): ?array
$players = [];
foreach ($ps->fetchAll() as $row) {
// Parse vote_for: JSON array (new) or legacy single pkey string
$voteRaw = $row['vote_for'] ?? null;
if ($voteRaw !== null && str_starts_with(ltrim((string) $voteRaw), '[')) {
$parsedVotes = json_decode($voteRaw, true) ?: [];
} elseif ($voteRaw !== null && $voteRaw !== '') {
$parsedVotes = [$voteRaw];
} else {
$parsedVotes = [];
}
$players[$row['pkey']] = [
'pkey' => $row['pkey'],
'name' => $row['name'],
'userId' => $row['user_id'] ? (int) $row['user_id'] : null,
'avatar' => $row['avatar'] ?? null,
'question' => $row['question'] ?? '',
'answer' => $row['answer'] ?? '',
'answered' => (bool) $row['answered'],
'score' => (int) $row['score'],
'voteFor' => $row['vote_for'] ?? '',
'pkey' => $row['pkey'],
'name' => $row['name'],
'userId' => $row['user_id'] ? (int) $row['user_id'] : null,
'avatar' => $row['avatar'] ?? null,
'question' => $row['question'] ?? '',
'answer' => $row['answer'] ?? '',
'answered' => (bool) $row['answered'],
'score' => (int) $row['score'],
'votes' => $parsedVotes,
'voteLocked' => (bool) ($row['vote_locked'] ?? false),
'voteRequest' => (bool) ($row['vote_request'] ?? false),
];
}
@ -92,6 +105,8 @@ function loadRoom(PDO $pdo, string $code): ?array
'votedOutKeys' => $j($room['voted_out_keys']),
'roundOutcome' => $outcome,
'votingOpen' => (bool) ($room['voting_open'] ?? false),
'revealIndex' => (int) ($room['reveal_index'] ?? -1),
'imposterWeights' => $room['imposter_weights'] ?? null,
'activeEmojis' => array_values(array_filter(
$j($room['active_emojis'] ?? '[]'),
fn($e) => ($e['ts'] ?? 0) >= (time() - 4)
@ -120,11 +135,21 @@ function resolveVotes(array $players, array $liarKeys): array
$tally[$p['pkey']] = 0;
}
foreach ($players as $p) {
$vf = $p['voteFor'] ?? '';
if ($vf === '' || $vf === '__nobody__') {
$votes = $p['votes'] ?? [];
if (!is_array($votes)) $votes = [];
if (empty($votes)) {
$tally['__nobody__']++;
} elseif (array_key_exists($vf, $tally)) {
$tally[$vf]++;
} else {
// __nobody__ is exclusive: if present, count only as nobody
if (in_array('__nobody__', $votes, true)) {
$tally['__nobody__']++;
} else {
foreach ($votes as $vf) {
if (array_key_exists($vf, $tally)) {
$tally[$vf]++;
}
}
}
}
}
@ -200,6 +225,118 @@ function archiveRound(PDO $pdo, array $state, int $now): void
}
}
/**
* Führt die Rundenauswertung durch. Liest liar_keys direkt aus der DB,
* damit die Redaktion in loadRoom() (liarKeys=[] solange roundOutcome=null) umgangen wird.
* Schreibt Ergebnis, Archiv, Punkte und Profil-Stats.
*
* @return array Neuer state nach Auswertung (loadRoom-Ergebnis).
*/
function performResolveRound(PDO $pdo, string $code, int $now): array
{
$j = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : [];
// Liar-Keys direkt lesen — loadRoom() würde sie ohne roundOutcome verstecken
$lkStmt = $pdo->prepare('SELECT liar_keys FROM gtl_rooms WHERE code=?');
$lkStmt->execute([$code]);
$lkRow = $lkStmt->fetch();
$liarKeys = $j($lkRow['liar_keys'] ?? '');
$state = loadRoom($pdo, $code);
$players = $state['players'];
$votedOut = resolveVotes(array_values($players), $liarKeys);
if (empty($liarKeys)) {
$outcome = 'no_liar';
} elseif (empty($votedOut)) {
$outcome = 'imposters_win';
} elseif (empty(array_diff($liarKeys, $votedOut))) {
$outcome = 'innocents_win';
} else {
$outcome = 'imposters_win';
}
$pdo->prepare(
'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, revealed=1, reveal_index=9999, updated_at=?
WHERE code=?'
)->execute([json_encode($votedOut), $outcome, $now, $code]);
// Verlauf speichern
$existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?');
$existing->execute([$code, $state['roundNum']]);
$existingRow = $existing->fetch();
if ($existingRow) {
$roundId = (int) $existingRow['id'];
$pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?')
->execute([$outcome, $roundId]);
$updVo = $pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?');
foreach ($players as $p) {
$updVo->execute([in_array($p['pkey'], $votedOut, true) ? 1 : 0, $roundId, $p['pkey']]);
}
} else {
$pdo->prepare(
'INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)'
)->execute([$code, $state['roundNum'], $now, $outcome]);
$roundId = (int) $pdo->lastInsertId();
$ins = $pdo->prepare(
'INSERT IGNORE INTO gtl_round_players
(round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer)
VALUES (?,?,?,?,?,?,?,?)'
);
foreach ($players as $p) {
$ins->execute([
$roundId, $p['userId'], $p['name'], $p['pkey'],
in_array($p['pkey'], $liarKeys, true) ? 1 : 0,
in_array($p['pkey'], $votedOut, true) ? 1 : 0,
$p['question'], $p['answer'],
]);
}
}
// Punkte + Profil-Stats
$updStats = $pdo->prepare(
'UPDATE gtl_user_stats SET
games_played = games_played + 1,
games_won = games_won + ?,
games_lost = games_lost + ?,
times_imposter = times_imposter + ?,
imposter_wins = imposter_wins + ?,
imposter_losses = imposter_losses + ?,
innocent_wins = innocent_wins + ?,
innocent_losses = innocent_losses + ?
WHERE user_id = ?'
);
$updScore = $pdo->prepare(
'UPDATE gtl_players SET score=score+1, updated_at=? WHERE room_code=? AND pkey=?'
);
foreach ($players as $p) {
$wasImposter = in_array($p['pkey'], $liarKeys, true);
$wasVotedOut = in_array($p['pkey'], $votedOut, true);
$playerWon = $wasImposter ? !$wasVotedOut : ($outcome === 'innocents_win');
if ($playerWon) {
$updScore->execute([$now, $code, $p['pkey']]);
}
if (!$p['userId']) continue;
$updStats->execute([
$playerWon ? 1 : 0,
$playerWon ? 0 : 1,
$wasImposter ? 1 : 0,
$wasImposter && $playerWon ? 1 : 0,
$wasImposter && !$playerWon ? 1 : 0,
!$wasImposter && $playerWon ? 1 : 0,
!$wasImposter && !$playerWon ? 1 : 0,
$p['userId'],
]);
}
return loadRoom($pdo, $code);
}
$cfg = require __DIR__ . '/config.php';
try {
@ -308,13 +445,17 @@ try {
$pdo->prepare(
'UPDATE gtl_rooms
SET normal_question=?, imposter_question=?, liar_keys=?,
voted_out_keys=NULL, round_outcome=NULL, updated_at=?
voted_out_keys=NULL, round_outcome=NULL, voting_open=0,
reveal_index=-1, updated_at=?
WHERE code=?'
)->execute([$normalQ, $imposterQ, json_encode($imposterKeys), $now, $code]);
$ps = $pdo->prepare('SELECT pkey FROM gtl_players WHERE room_code=?');
$ps->execute([$code]);
$upd = $pdo->prepare('UPDATE gtl_players SET question=?, updated_at=? WHERE room_code=? AND pkey=?');
$upd = $pdo->prepare(
'UPDATE gtl_players SET question=?, vote_for=NULL, vote_locked=0, vote_request=0, updated_at=?
WHERE room_code=? AND pkey=?'
);
foreach (array_column($ps->fetchAll(), 'pkey') as $pk) {
$q = in_array($pk, $imposterKeys, true) ? $imposterQ : $normalQ;
$upd->execute([$q, $now, $code, $pk]);
@ -351,11 +492,26 @@ try {
break;
case 'reveal':
// Alle gleichzeitig aufdecken
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, updated_at=? WHERE code=?')
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=9999, updated_at=? WHERE code=?')
->execute([$now, $code]);
respond(['ok' => true]);
respond(['ok' => true, 'state' => loadRoom($pdo, $code)]);
break;
case 'reveal_next':
// Nächste Antwort einzeln aufdecken
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$riRow = $pdo->prepare('SELECT reveal_index FROM gtl_rooms WHERE code=?');
$riRow->execute([$code]);
$riData = $riRow->fetch();
if (!$riData) respond(['error' => 'Raum nicht gefunden.'], 404);
$newIdx = (int) $riData['reveal_index'] + 1;
$pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=?, updated_at=? WHERE code=?')
->execute([$newIdx, $now, $code]);
respond(['ok' => true, 'state' => loadRoom($pdo, $code)]);
break;
case 'open_voting':
@ -386,148 +542,80 @@ try {
respond(['ok' => true]);
break;
case 'vote':
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$voteFor = (string) ($body['voteFor'] ?? '');
case 'request_voting':
// Demokratischer Voting-Antrag: sobald ALLE Spieler angefragt haben → auto-open
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$pdo->prepare('UPDATE gtl_players SET vote_request=1, updated_at=? WHERE room_code=? AND pkey=?')
->execute([$now, $code, $pkey]);
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Wenn alle Spieler request gesetzt haben → Voting öffnen
$pending = $pdo->prepare('SELECT COUNT(*) FROM gtl_players WHERE room_code=? AND vote_request=0');
$pending->execute([$code]);
if ((int) $pending->fetchColumn() === 0) {
$pdo->prepare('UPDATE gtl_rooms SET voting_open=1, updated_at=? WHERE code=?')
->execute([$now, $code]);
}
respond(['ok' => true, 'state' => loadRoom($pdo, $code)]);
break;
// Voting gesperrt prüfen
$vCheck = $pdo->prepare('SELECT voting_open FROM gtl_rooms WHERE code=?');
$vCheck->execute([$code]);
$vRow = $vCheck->fetch();
if (!$vRow || !$vRow['voting_open']) {
case 'lock_vote':
// Stimme final abschicken. Sperrt die Auswahl; wenn alle gesperrt → Auto-Auswertung.
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$pkey = (string) ($body['pkey'] ?? '');
$votes = array_values(array_filter((array) ($body['votes'] ?? []), 'is_string'));
$vLock = $pdo->prepare('SELECT voting_open FROM gtl_rooms WHERE code=?');
$vLock->execute([$code]);
$vLockRow = $vLock->fetch();
if (!$vLockRow || !$vLockRow['voting_open']) {
respond(['error' => 'Das Voting ist noch nicht geöffnet.'], 403);
}
if ($voteFor !== '__nobody__' && $voteFor === $pkey) respond(['error' => 'Du kannst nicht für dich selbst stimmen.'], 400);
// Niemand ist exklusiv; eigene pkey nicht erlaubt
if (in_array('__nobody__', $votes, true)) {
$votes = ['__nobody__'];
} else {
$votes = array_values(array_filter($votes, fn($v) => $v !== $pkey));
}
$pdo->prepare(
'UPDATE gtl_players SET vote_for=?, updated_at=? WHERE room_code=? AND pkey=?'
)->execute([$voteFor !== '' ? $voteFor : null, $now, $code, $pkey]);
'UPDATE gtl_players SET vote_for=?, vote_locked=1, updated_at=? WHERE room_code=? AND pkey=?'
)->execute([json_encode($votes), $now, $code, $pkey]);
$pdo->prepare('UPDATE gtl_rooms SET updated_at=? WHERE code=?')->execute([$now, $code]);
// Auto-Auswertung wenn alle Spieler abgestimmt haben
$unlocked = $pdo->prepare('SELECT COUNT(*) FROM gtl_players WHERE room_code=? AND vote_locked=0');
$unlocked->execute([$code]);
if ((int) $unlocked->fetchColumn() === 0) {
$newState = performResolveRound($pdo, $code, $now);
respond(['ok' => true, 'autoResolved' => true, 'state' => $newState]);
}
respond(['ok' => true, 'state' => loadRoom($pdo, $code)]);
break;
case 'update_weights':
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$weights = (string) ($body['weights'] ?? '');
$decoded = json_decode($weights, true);
if (!is_array($decoded)) respond(['error' => 'Ungültiges JSON für Imposter-Gewichte.'], 400);
$pdo->prepare('UPDATE gtl_rooms SET imposter_weights=?, updated_at=? WHERE code=?')
->execute([$weights, $now, $code]);
respond(['ok' => true]);
break;
case 'resolve_round':
// Manueller Trigger durch Host — nutzt den gemeinsamen Helper
$body = input();
$code = slugCode((string) ($body['code'] ?? ''));
$state = loadRoom($pdo, $code);
if ($state === null) respond(['error' => 'Raum nicht gefunden.'], 404);
if (!$state['revealed']) respond(['error' => 'Runde noch nicht aufgedeckt.'], 400);
$players = $state['players'];
$liarKeys = $state['liarKeys'];
$votedOut = resolveVotes(array_values($players), $liarKeys);
// Outcome-Logik:
// - Niemand hatte Max + kein Imposter gesetzt → innocents_win
// - Niemand hatte Max + Imposter exist. → imposters_win
// - Alle Imposters rausgewählt → innocents_win
// - Mind. 1 Imposter überlebt → imposters_win
if (empty($liarKeys)) {
// Kein Imposter gesetzt: bei voting war niemand der Böse
// Niemand gewinnt = Spiel war "clean"
$outcome = 'no_liar';
} elseif (empty($votedOut)) {
// Niemand rausgewählt UND es gibt Imposters → Imposters gewinnen
$outcome = 'imposters_win';
} elseif (empty(array_diff($liarKeys, $votedOut))) {
// Alle Imposters raus → Innocents gewinnen
$outcome = 'innocents_win';
} else {
// Mind. 1 Imposter überlebt
$outcome = 'imposters_win';
$check = loadRoom($pdo, $code);
if ($check === null) respond(['error' => 'Raum nicht gefunden.'], 404);
if (!$check['revealed'] && $check['revealIndex'] < 0) {
respond(['error' => 'Runde noch nicht aufgedeckt.'], 400);
}
$pdo->prepare(
'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, updated_at=? WHERE code=?'
)->execute([json_encode($votedOut), $outcome, $now, $code]);
// Verlauf speichern
$existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?');
$existing->execute([$code, $state['roundNum']]);
$existingRow = $existing->fetch();
if ($existingRow) {
$roundId = (int) $existingRow['id'];
$pdo->prepare('UPDATE gtl_game_rounds SET outcome=? WHERE id=?')
->execute([$outcome, $roundId]);
$pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?');
// Update voted_out for each player
$updVo = $pdo->prepare('UPDATE gtl_round_players SET voted_out=? WHERE round_id=? AND pkey=?');
foreach ($players as $p) {
$updVo->execute([in_array($p['pkey'], $votedOut, true) ? 1 : 0, $roundId, $p['pkey']]);
}
} else {
$pdo->prepare('INSERT INTO gtl_game_rounds (room_code, round_num, played_at, outcome) VALUES (?,?,?,?)')
->execute([$code, $state['roundNum'], $now, $outcome]);
$roundId = (int) $pdo->lastInsertId();
$ins = $pdo->prepare(
'INSERT IGNORE INTO gtl_round_players
(round_id, user_id, player_name, pkey, was_imposter, voted_out, question, answer)
VALUES (?,?,?,?,?,?,?,?)'
);
foreach ($players as $p) {
$ins->execute([
$roundId, $p['userId'], $p['name'], $p['pkey'],
in_array($p['pkey'], $liarKeys, true) ? 1 : 0,
in_array($p['pkey'], $votedOut, true) ? 1 : 0,
$p['question'], $p['answer'],
]);
}
}
// Statistiken aktualisieren
$updStats = $pdo->prepare(
'UPDATE gtl_user_stats SET
games_played = games_played + 1,
games_won = games_won + ?,
games_lost = games_lost + ?,
times_imposter = times_imposter + ?,
imposter_wins = imposter_wins + ?,
imposter_losses = imposter_losses + ?,
innocent_wins = innocent_wins + ?,
innocent_losses = innocent_losses + ?
WHERE user_id = ?'
);
$updScore = $pdo->prepare(
'UPDATE gtl_players SET score=score+1, updated_at=? WHERE room_code=? AND pkey=?'
);
foreach ($players as $p) {
$wasImposter = in_array($p['pkey'], $liarKeys, true);
$wasVotedOut = in_array($p['pkey'], $votedOut, true);
if ($wasImposter) {
$playerWon = !$wasVotedOut;
} else {
$playerWon = ($outcome === 'innocents_win');
}
// Automatische Punktevergabe
if ($playerWon) {
$updScore->execute([$now, $code, $p['pkey']]);
}
// Profil-Statistiken (nur für eingeloggte User)
if (!$p['userId']) continue;
$updStats->execute([
$playerWon ? 1 : 0,
$playerWon ? 0 : 1,
$wasImposter ? 1 : 0,
$wasImposter && $playerWon ? 1 : 0,
$wasImposter && !$playerWon ? 1 : 0,
!$wasImposter && $playerWon ? 1 : 0,
!$wasImposter && !$playerWon ? 1 : 0,
$p['userId'],
]);
}
respond(['ok' => true, 'state' => loadRoom($pdo, $code)]);
$newState = performResolveRound($pdo, $code, $now);
respond(['ok' => true, 'state' => $newState]);
break;
case 'get_host_history':
@ -596,13 +684,15 @@ try {
'UPDATE gtl_rooms
SET revealed=0, liar_keys=NULL, voted_out_keys=NULL, round_outcome=NULL,
normal_question=NULL, imposter_question=NULL, voting_open=0,
reveal_index=-1, active_emojis=NULL,
round_num=round_num+1, updated_at=?
WHERE code=?'
)->execute([$now, $code]);
$pdo->prepare(
'UPDATE gtl_players
SET question=NULL, answer=NULL, answered=0, vote_for=NULL, updated_at=?
SET question=NULL, answer=NULL, answered=0, vote_for=NULL,
vote_locked=0, vote_request=0, updated_at=?
WHERE room_code=?'
)->execute([$now, $code]);