add countdown & improve

This commit is contained in:
lelo 2025-10-25 20:58:54 +00:00
parent b917d3476d
commit 9af4670869
4 changed files with 87 additions and 48 deletions

33
app.py
View File

@ -127,9 +127,10 @@ def upload():
# build per-game question list # build per-game question list
questions = [] questions = []
for _, row in df.iterrows(): for i, (_, row) in enumerate(df.iterrows()):
col = row['correct'] col = row['correct']
questions.append({ questions.append({
'qid': i,
'question': str(row['question']), 'question': str(row['question']),
'options': [str(row[f'answer{i}']) for i in range(1, 5)], 'options': [str(row[f'answer{i}']) for i in range(1, 5)],
'correct': str(row[col]) 'correct': str(row[col])
@ -342,17 +343,18 @@ def on_submit_answer(data):
if not secret or secret not in games or pid not in games[secret]['players']: if not secret or secret not in games or pid not in games[secret]['players']:
return return
game = games[secret] game = games[secret]
curr = game['questions'][game['current_q']]
if int(data.get('qid', -1)) != int(curr['qid']):
return
if game.get('revealed'): if game.get('revealed'):
return return
if any(pid == t[0] for t in game['answered']): if any(pid == t[0] for t in game['answered']):
return return
# capture reaction time
now = time.perf_counter() now = time.perf_counter()
q_started = game.get('q_started', now) q_started = game.get('q_started', now)
rt = max(0.0, now - q_started) rt = max(0.0, now - q_started)
# store (pid, answer, rt)
game['answered'].append((pid, data.get('answer'), rt)) game['answered'].append((pid, data.get('answer'), rt))
_score_and_emit(secret) _score_and_emit(secret)
@ -363,12 +365,11 @@ def on_next_question():
if session.get('role') != 'host' or not secret or secret not in games: if session.get('role') != 'host' or not secret or secret not in games:
return return
game = games[secret] game = games[secret]
game['revealed'] = True
game['current_q'] += 1 game['current_q'] += 1
if game['current_q'] < len(game['questions']): if game['current_q'] < len(game['questions']):
_send_question(secret) _send_question(secret)
else: else:
# mark finished & emit final boards
game['finished'] = True game['finished'] = True
board = sorted( board = sorted(
[{'name':v['name'],'score':v['score']} for v in game['players'].values()], [{'name':v['name'],'score':v['score']} for v in game['players'].values()],
@ -377,12 +378,7 @@ def on_next_question():
socketio.emit('game_over', {'board': board}, room='host') socketio.emit('game_over', {'board': board}, room='host')
for psid,pdata in game['players'].items(): for psid,pdata in game['players'].items():
placement = next(i+1 for i,p in enumerate(board) if p['name']==pdata['name']) placement = next(i+1 for i,p in enumerate(board) if p['name']==pdata['name'])
socketio.emit( socketio.emit('game_over', {'placement': placement, 'score': pdata['score']}, room=psid)
'game_over',
{'placement': placement, 'score': pdata['score']},
room=psid
)
@socketio.on('rejoin_game') @socketio.on('rejoin_game')
@ -449,12 +445,13 @@ def _send_question(secret):
game['revealed'] = False game['revealed'] = False
q = game['questions'][game['current_q']] q = game['questions'][game['current_q']]
game['answered'].clear() game['answered'].clear()
# NEW: start monotonic timer for this question
game['q_started'] = time.perf_counter() game['q_started'] = time.perf_counter()
game['q_deadline_s'] = 20 # configurable per question if you want game['q_deadline_s'] = 20
socketio.emit('new_question', {
socketio.emit('new_question', {'question': q['question'], 'options': q['options']}, room='player') 'qid': q['qid'],
'question': q['question'],
'options': q['options']
}, room='player')
socketio.emit('new_question', {'question': q['question']}, room='host') socketio.emit('new_question', {'question': q['question']}, room='host')

View File

@ -102,7 +102,7 @@
<ul id="perQ" class="list-group mb-3 text-center"></ul> <ul id="perQ" class="list-group mb-3 text-center"></ul>
</div> </div>
<div id="controlsBar" class="controls-bar" style="display:none;"> <div id="controlsBar" class="controls-bar" style="display:none;">
<div class="d-flex gap-2 justify-content-center"> <div class="d-flex gap-2 justify-content-center align-items-center flex-wrap">
<button id="showAnswerBtn" class="btn btn-info">Antwort zeigen</button> <button id="showAnswerBtn" class="btn btn-info">Antwort zeigen</button>
<button id="nextBtn" class="btn btn-warning" disabled>Nächste Frage</button> <button id="nextBtn" class="btn btn-warning" disabled>Nächste Frage</button>
</div> </div>
@ -126,7 +126,11 @@
/* ------------------ Persistence (no backend change) ------------------ */ /* ------------------ Persistence (no backend change) ------------------ */
const LS_KEY = 'leaderboardState'; // { title: string, board: array, ts: number } const LS_KEY = 'leaderboardState'; // { title: string, board: array, ts: number }
let answerTimer = null;
/* Timers */
let answerTimer = null; // existing auto-reveal timeout
let countdownInterval = null; // visible countdown updater
let countdownDeadline = 0;
function saveLeaderboardToStorage(title, board) { function saveLeaderboardToStorage(title, board) {
try { try {
@ -158,7 +162,7 @@
function showSidebar(titleText = 'Rangliste') { function showSidebar(titleText = 'Rangliste') {
document.body.classList.add('with-sidebar'); document.body.classList.add('with-sidebar');
const panel = document.getElementById('final-results'); const panel = document.getElementById('final-results');
panel.classList.remove('centerboard'); // NEW: ensure sidebar mode panel.classList.remove('centerboard');
$('#finalResultsTitle').text(titleText); $('#finalResultsTitle').text(titleText);
$('#final-results').show(); $('#final-results').show();
} }
@ -184,6 +188,48 @@
showSidebar(title); showSidebar(title);
} }
/* ------------------ COUNTDOWN-IN-ANSWER helpers ------------------ */
function showCountdownInAnswer(msTotal = 20000) {
stopCountdownInAnswer(); // clean slate
countdownDeadline = Date.now() + msTotal;
// Put a single LI into #perQ and show the host-results box
$('#perQ')
.empty()
.append(
`<li id="countdownItem"
class="list-group-item list-group-item-light"
style="font-size:2.5rem;">
<strong><span id="countdownValue">${(msTotal/1000).toFixed(1)}</span>s</strong>
</li>`
);
$('#host-results').show();
// Update every 100ms
countdownInterval = setInterval(() => {
const remainingMs = Math.max(0, countdownDeadline - Date.now());
const seconds = (remainingMs / 1000).toFixed(1);
$('#countdownValue').text(seconds);
if (remainingMs <= 0) {
stopCountdownInAnswer();
}
}, 100);
}
function stopCountdownInAnswer() {
if (countdownInterval) { clearInterval(countdownInterval); countdownInterval = null; }
}
function replaceCountdownWithAnswer(text) {
// Swap the LI content & styling to the “answer revealed” state
$('#countdownItem')
.removeClass('list-group-item-light')
.addClass('list-group-item-success')
.css('font-size', '2.5rem')
.html(`${text}`);
}
/* ------------------ Restore from storage on load ------------------ */ /* ------------------ Restore from storage on load ------------------ */
(function restoreFromStorageOnLoad() { (function restoreFromStorageOnLoad() {
const stored = loadLeaderboardFromStorage(); const stored = loadLeaderboardFromStorage();
@ -216,9 +262,7 @@
console.log('Roster update:', data.players); console.log('Roster update:', data.players);
$('#roster').empty(); $('#roster').empty();
(data.players || []).forEach(name => { (data.players || []).forEach(name => {
$('#roster').append( $('#roster').append(`<li class="list-group-item">${name}</li>`);
`<li class="list-group-item">${name}</li>`
);
}); });
$('#startBtn').prop('disabled', (data.players || []).length === 0); $('#startBtn').prop('disabled', (data.players || []).length === 0);
}); });
@ -238,20 +282,24 @@
$('#host-question').show(); $('#host-question').show();
$('#qText').text(data.question || ''); $('#qText').text(data.question || '');
$('#host-results').hide(); $('#host-results').hide();
$('#perQ').empty();
$('#showAnswerBtn').prop({ disabled: false }).show(); $('#showAnswerBtn').prop({ disabled: false }).show();
$('#nextBtn').prop('disabled', true); $('#nextBtn').prop('disabled', true);
$('#controlsBar').show(); // show sticky buttons $('#controlsBar').show();
// Keep the sidebar visible during the game // Keep the sidebar visible during the game
showSidebar('Rangliste'); showSidebar('Rangliste');
/* NEW: (re)start the 21s auto-reveal timer */ // Auto-reveal after 20s
if (answerTimer) clearTimeout(answerTimer); if (answerTimer) clearTimeout(answerTimer);
answerTimer = setTimeout(() => { answerTimer = setTimeout(() => {
if (!$('#showAnswerBtn').prop('disabled')) { if (!$('#showAnswerBtn').prop('disabled')) {
$('#showAnswerBtn').trigger('click'); $('#showAnswerBtn').trigger('click');
} }
}, 21000); }, 20000);
// === Show countdown inside the answer area ===
showCountdownInAnswer(20000);
}); });
// Live overall leaderboard updates -> fill the right sidebar (top 10) // Live overall leaderboard updates -> fill the right sidebar (top 10)
@ -259,7 +307,6 @@
console.log('Overall leader:', data.board); console.log('Overall leader:', data.board);
const board = (data && Array.isArray(data.board)) ? data.board : []; const board = (data && Array.isArray(data.board)) ? data.board : [];
renderAndShow('Rangliste', board); renderAndShow('Rangliste', board);
// Persist so a reload restores instantly
saveLeaderboardToStorage('Rangliste', board); saveLeaderboardToStorage('Rangliste', board);
}); });
@ -267,44 +314,42 @@
$('#nextBtn').off('click').on('click', () => { $('#nextBtn').off('click').on('click', () => {
console.log('Next question clicked'); console.log('Next question clicked');
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; } if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
stopCountdownInAnswer();
socket.emit('next_question'); socket.emit('next_question');
}); });
// when host clicks “Show Answer” // when host clicks “Show Answer”
$('#showAnswerBtn').off('click').on('click', () => { $('#showAnswerBtn').off('click').on('click', () => {
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; } if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
stopCountdownInAnswer();
socket.emit('show_answer'); socket.emit('show_answer');
}); });
// once server confirms the answer is revealed // once server confirms the answer is revealed
socket.on('answer_revealed', data => { socket.on('answer_revealed', data => {
$('#perQ').empty().append( // Ensure the field is visible and swap countdown → answer
`<li class="list-group-item list-group-item-success" style="font-size:2.5rem;">${data.correct}</li>`
);
$('#host-results').show(); $('#host-results').show();
replaceCountdownWithAnswer(`${data.correct}`);
$('#showAnswerBtn').prop('disabled', true); $('#showAnswerBtn').prop('disabled', true);
$('#nextBtn').prop('disabled', false); $('#nextBtn').prop('disabled', false);
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; } if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
stopCountdownInAnswer();
}); });
// Final results (use the same sidebar, change the title) // Final results (use the same sidebar, change the title)
socket.on('game_over', data => { socket.on('game_over', data => {
$('#controlsBar').hide(); $('#controlsBar').hide();
/* NEW: clear any lingering timer */
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; } if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
stopCountdownInAnswer();
if (data && Array.isArray(data.board)) { if (data && Array.isArray(data.board)) {
console.log('Game over'); console.log('Game over');
$('#qrContainer, #startBtn, #rosterHeader, #roster, #host-question, #host-results').hide(); $('#qrContainer, #startBtn, #rosterHeader, #roster, #host-question, #host-results').hide();
$('#newGameButton').show(); $('#newGameButton').show();
// NEW: switch to centered leaderboard
showCenteredBoard('Finale Rangliste', data.board); showCenteredBoard('Finale Rangliste', data.board);
$('#startBtn').prop('disabled', true); $('#startBtn').prop('disabled', true);
// Persist final board for reload
saveLeaderboardToStorage('Finale Rangliste', data.board); saveLeaderboardToStorage('Finale Rangliste', data.board);
} }
}); });
@ -312,15 +357,11 @@
function showCenteredBoard(title, board) { function showCenteredBoard(title, board) {
renderLeaderboard(board, 10); renderLeaderboard(board, 10);
$('#finalResultsTitle').text(title); $('#finalResultsTitle').text(title);
// remove sidebar layout
document.body.classList.remove('with-sidebar'); document.body.classList.remove('with-sidebar');
// switch the panel into centered mode + make sure it's visible
const panel = document.getElementById('final-results'); const panel = document.getElementById('final-results');
panel.classList.add('centerboard'); panel.classList.add('centerboard');
panel.style.display = 'block'; // ← force visible panel.style.display = 'block';
$('#final-results').show(); // ← double-sure in jQuery land $('#final-results').show();
} }
/* ------------------ Initial UI state for lobby ------------------ */ /* ------------------ Initial UI state for lobby ------------------ */

View File

@ -80,6 +80,9 @@
<script> <script>
let currentQuestionText = '';
let currentQid = null;
// Key for storing a stable per-question order in this browser // Key for storing a stable per-question order in this browser
function orderKeyForQuestion(qText) { function orderKeyForQuestion(qText) {
return 'order:' + hashStr(qText || ''); return 'order:' + hashStr(qText || '');
@ -144,9 +147,6 @@
return 'sel:' + hashStr(qText || ''); return 'sel:' + hashStr(qText || '');
} }
// Keep the current question text so clicks can be stored against it
let currentQuestionText = '';
// Web Audio beep for new questions (autoplay-safe after first user interaction) // Web Audio beep for new questions (autoplay-safe after first user interaction)
let audioCtx = null; let audioCtx = null;
function playBeep() { function playBeep() {
@ -217,6 +217,7 @@
socket.on('new_question', data => { socket.on('new_question', data => {
$('#view-join, #view-wait').hide(); $('#view-join, #view-wait').hide();
$('#view-question').show(); $('#view-question').show();
currentQid = data.qid;
currentQuestionText = data.question || ''; currentQuestionText = data.question || '';
renderOptions(data.options, false, currentQuestionText); renderOptions(data.options, false, currentQuestionText);
playBeep(); playBeep();
@ -245,7 +246,7 @@
const answer = $me.text(); const answer = $me.text();
// emit once // emit once
socket.emit('submit_answer', { answer }); socket.emit('submit_answer', { answer, qid: currentQid });
// Persist selection for this question (so it's there after reloads) // Persist selection for this question (so it's there after reloads)
try { try {

View File

@ -26,7 +26,7 @@
</p> </p>
<p class="text-muted"> <p class="text-muted">
Sobald die richtige Lösung eingeblendet wurde, werden <strong>keine weiteren Antworten</strong> mehr gewertet. Sobald die richtige Lösung eingeblendet wurde, werden <strong>keine weiteren Antworten</strong> mehr gewertet.
Die Rangliste aktualisiert sich nach jeder gewerteten Antwort und zeigt am Ende die finale Platzierung. Die Rangliste aktualisiert sich permanent und zeigt am Ende die finale Platzierung an.
</p> </p>
<!-- Dateivorlage --> <!-- Dateivorlage -->