diff --git a/api.php b/api.php index 4b9602a..cc1583d 100644 --- a/api.php +++ b/api.php @@ -46,7 +46,7 @@ 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, - reveal_index, imposter_weights + reveal_index, revealed_keys, imposter_weights FROM gtl_rooms WHERE code = ?' ); $stmt->execute([$code]); @@ -106,12 +106,23 @@ function loadRoom(PDO $pdo, string $code): ?array 'roundOutcome' => $outcome, 'votingOpen' => (bool) ($room['voting_open'] ?? false), 'revealIndex' => (int) ($room['reveal_index'] ?? -1), + 'revealedKeys' => $j($room['revealed_keys'] ?? ''), 'imposterWeights' => $room['imposter_weights'] ?? null, 'activeEmojis' => array_values(array_filter( $j($room['active_emojis'] ?? '[]'), fn($e) => ($e['ts'] ?? 0) >= (time() - 4) )), 'players' => $players, + 'chat' => (function() use ($pdo, $code) { + try { + $cs = $pdo->prepare( + 'SELECT player_name, message, created_at FROM gtl_chat_messages + WHERE room_code=? ORDER BY created_at DESC, id DESC LIMIT 30' + ); + $cs->execute([$code]); + return array_reverse($cs->fetchAll()); + } catch (Throwable) { return []; } + })(), ]; } @@ -257,10 +268,11 @@ function performResolveRound(PDO $pdo, string $code, int $now): array $outcome = 'imposters_win'; } + $allPkeys = array_keys($players); $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]); + 'UPDATE gtl_rooms SET voted_out_keys=?, round_outcome=?, revealed=1, reveal_index=9999, + revealed_keys=?, updated_at=? WHERE code=?' + )->execute([json_encode($votedOut), $outcome, json_encode($allPkeys), $now, $code]); // Verlauf speichern $existing = $pdo->prepare('SELECT id FROM gtl_game_rounds WHERE room_code=? AND round_num=?'); @@ -446,7 +458,7 @@ try { 'UPDATE gtl_rooms SET normal_question=?, imposter_question=?, liar_keys=?, voted_out_keys=NULL, round_outcome=NULL, voting_open=0, - reveal_index=-1, updated_at=? + reveal_index=-1, revealed_keys=NULL, updated_at=? WHERE code=?' )->execute([$normalQ, $imposterQ, json_encode($imposterKeys), $now, $code]); @@ -495,13 +507,37 @@ try { // Alle gleichzeitig aufdecken $body = input(); $code = slugCode((string) ($body['code'] ?? '')); - $pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=9999, updated_at=? WHERE code=?') - ->execute([$now, $code]); + // Collect all player pkeys for this room + $pkStmt = $pdo->prepare('SELECT pkey FROM gtl_players WHERE room_code=?'); + $pkStmt->execute([$code]); + $allKeys = array_column($pkStmt->fetchAll(), 'pkey'); + $pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=9999, revealed_keys=?, updated_at=? WHERE code=?') + ->execute([json_encode($allKeys), $now, $code]); + respond(['ok' => true, 'state' => loadRoom($pdo, $code)]); + break; + + case 'reveal_answer': + // Gezielt eine Antwort aufdecken (Host klickt Spielerkarte) + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $rpkey = (string) ($body['pkey'] ?? ''); + if ($rpkey === '') respond(['error' => 'pkey fehlt.'], 400); + $rkStmt = $pdo->prepare('SELECT revealed_keys FROM gtl_rooms WHERE code=?'); + $rkStmt->execute([$code]); + $rkRow = $rkStmt->fetch(); + if (!$rkRow) respond(['error' => 'Raum nicht gefunden.'], 404); + $j2 = fn($v) => (!empty($v) && is_string($v)) ? (json_decode($v, true) ?: []) : []; + $rkeys = $j2($rkRow['revealed_keys'] ?? ''); + if (!in_array($rpkey, $rkeys, true)) { + $rkeys[] = $rpkey; + } + $pdo->prepare('UPDATE gtl_rooms SET revealed=1, reveal_index=?, revealed_keys=?, updated_at=? WHERE code=?') + ->execute([count($rkeys), json_encode($rkeys), $now, $code]); respond(['ok' => true, 'state' => loadRoom($pdo, $code)]); break; case 'reveal_next': - // Nächste Antwort einzeln aufdecken + // Legacy: Nächste Antwort sequenziell aufdecken (fallback) $body = input(); $code = slugCode((string) ($body['code'] ?? '')); $riRow = $pdo->prepare('SELECT reveal_index FROM gtl_rooms WHERE code=?'); @@ -684,7 +720,7 @@ 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, + reveal_index=-1, revealed_keys=NULL, active_emojis=NULL, round_num=round_num+1, updated_at=? WHERE code=?' )->execute([$now, $code]); @@ -727,6 +763,25 @@ try { respond(['ok' => true]); break; + case 'send_chat': + $body = input(); + $code = slugCode((string) ($body['code'] ?? '')); + $sender = substr(trim((string) ($body['name'] ?? '')), 0, 40); + $message = substr(trim((string) ($body['message'] ?? '')), 0, 500); + if ($code === '' || $sender === '' || $message === '') { + respond(['error' => 'Fehlende Parameter.'], 400); + } + $pdo->prepare( + 'INSERT INTO gtl_chat_messages (room_code, player_name, message, created_at) VALUES (?,?,?,?)' + )->execute([$code, $sender, $message, $now]); + // Keep only last 200 messages per room + $pdo->prepare( + 'DELETE FROM gtl_chat_messages WHERE room_code=? AND id NOT IN + (SELECT id FROM (SELECT id FROM gtl_chat_messages WHERE room_code=? ORDER BY id DESC LIMIT 200) t)' + )->execute([$code, $code]); + respond(['ok' => true]); + break; + default: respond(['error' => 'Unbekannte Aktion.'], 400); } diff --git a/index.html b/index.html index c8211f3..4a6e55a 100644 --- a/index.html +++ b/index.html @@ -320,6 +320,23 @@ .nav-links a{padding:4px 8px;font-size:11px} } + /* ── Chat ───────────────────────────────────────────────── */ + .chat-card{display:flex;flex-direction:column;max-height:280px} + .chat-msgs{flex:1;overflow-y:auto;min-height:80px;max-height:200px; + display:flex;flex-direction:column;gap:4px;padding:8px 0; + scrollbar-width:thin;scrollbar-color:var(--line) transparent} + .chat-msg{font-size:12.5px;line-height:1.4;word-break:break-word} + .chat-msg .cn{font-weight:700;color:var(--accent2);margin-right:4px} + .chat-msg .ct{color:var(--text)} + .chat-row{display:flex;gap:6px;margin-top:8px} + .chat-row input{flex:1;padding:8px 10px;font-size:13px;margin:0;height:36px} + .chat-row button{padding:0 12px;font-size:13px;height:36px;width:auto;white-space:nowrap} + + /* ── Vote results transparency ────────────────────────────── */ + .vote-result-list{margin-top:8px;display:flex;flex-direction:column;gap:4px} + .vote-result-row{font-size:12.5px;color:var(--muted);line-height:1.4} + .vote-result-row b{color:var(--text)} + /* ── Emoji-Bar ──────────────────────────────────────────── */ .emoji-bar{display:flex;align-items:center;gap:8px;margin-top:14px; padding:10px 14px;background:var(--bg);border:1px solid var(--line); @@ -431,6 +448,17 @@
+ +Noch keine Nachrichten.
Noch keine abgeschlossenen Runden.
Noch keine Nachrichten.
Noch keine Nachrichten.
'; + lastChatLen=0; return; + } + if(msgs.length===lastChatLen) return; + lastChatLen=msgs.length; + const atBottom=wrap.scrollHeight-wrap.scrollTop<=wrap.clientHeight+40; + wrap.innerHTML=msgs.map(m=>`Noch keine Antworten.
'; @@ -976,10 +1117,10 @@ const App = (() => { if(anyRevealed && players.length){ const tally={'__nobody__':0}; players.forEach(p=>{ tally[p.pkey]=0; }); - players.forEach(p=>{ + // Only count players who have explicitly locked their vote + players.filter(p=>p.voteLocked).forEach(p=>{ const votes=p.votes||[]; - if(!votes.length){ tally['__nobody__']++; } - else if(votes.includes('__nobody__')){ tally['__nobody__']++; } + if(!votes.length||votes.includes('__nobody__')){ tally['__nobody__']++; } else{ votes.forEach(v=>{ if(tally[v]!==undefined) tally[v]++; }); } }); const locked=players.filter(p=>p.voteLocked).length; @@ -1135,6 +1276,10 @@ const App = (() => { try{ const d=await api('reveal',{code:room}); render(d.state); } catch(e){ err(e.message); } } + async function revealAnswer(pk){ + try{ const d=await api('reveal_answer',{code:room,pkey:pk}); render(d.state); } + catch(e){ err(e.message); } + } async function revealNext(){ try{ const d=await api('reveal_next',{code:room}); render(d.state); } catch(e){ err(e.message); } @@ -1162,7 +1307,7 @@ const App = (() => { try{ await api('new_round',{code:room}); selectedImposters=new Set(); questionsLoaded=false; lastJSON=''; - lastRoundNum=-1; localVotes=new Set(); + lastRoundNum=-1; localVotes=new Set(); lastChatLen=0; $('hNormalQ').value=''; $('hImposterQ').value=''; refresh(); }catch(e){ err(e.message); } @@ -1186,7 +1331,7 @@ const App = (() => { function leave(){ clearInterval(timer); role=room=pkey=name=null; lastState=null; selectedImposters=new Set(); questionsLoaded=false; lastJSON=''; - lastRoundNum=-1; + lastRoundNum=-1; lastChatLen=0; sessionStorage.removeItem('bsb_session'); show('playerView',false); show('hostView',false); show('lobby',true); } @@ -1220,10 +1365,10 @@ const App = (() => { return { hostOpen, playerJoin, submitAnswer, removePlayer, score, - reveal, revealNext, openVoting, resolveRound, newRound, resetScores, deleteRoom, + reveal, revealAnswer, revealNext, openVoting, resolveRound, newRound, resetScores, deleteRoom, leave, logout, assignQuestions, deleteAnswer, saveWeights, toggleImposter, randomImposters, clearImposters, sendEmoji, - toggleVoteCheck, lockVote, requestVoting + toggleVoteCheck, lockVote, requestVoting, sendChat }; })(); diff --git a/migrate.php b/migrate.php index cd47fcc..a498e77 100644 --- a/migrate.php +++ b/migrate.php @@ -6,7 +6,7 @@ */ declare(strict_types=1); -const LATEST_MIGRATION = 7; +const LATEST_MIGRATION = 8; function runMigrations(PDO $pdo, string $dbname): void { @@ -163,6 +163,22 @@ function runMigrations(PDO $pdo, string $dbname): void 'TINYINT(1) NOT NULL DEFAULT 0'); markMigration($pdo, 7); } + + // ── V8: Gezieltes Aufdecken (revealed_keys), Lobby-Chat ────── + if ($current < 8) { + addColumnIfMissing($pdo, $dbname, 'gtl_rooms', 'revealed_keys', + 'TEXT NULL DEFAULT NULL AFTER reveal_index'); + $pdo->exec("CREATE TABLE IF NOT EXISTS `gtl_chat_messages` ( + `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, + `room_code` VARCHAR(12) NOT NULL, + `player_name` VARCHAR(40) NOT NULL, + `message` VARCHAR(500) NOT NULL, + `created_at` INT UNSIGNED NOT NULL, + PRIMARY KEY (`id`), + INDEX `idx_room` (`room_code`, `created_at`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"); + markMigration($pdo, 8); + } } // ── Hilfsfunktionen ──────────────────────────────────────────