add countdown & improve
This commit is contained in:
parent
b917d3476d
commit
9af4670869
33
app.py
33
app.py
@ -127,9 +127,10 @@ def upload():
|
||||
|
||||
# build per-game question list
|
||||
questions = []
|
||||
for _, row in df.iterrows():
|
||||
for i, (_, row) in enumerate(df.iterrows()):
|
||||
col = row['correct']
|
||||
questions.append({
|
||||
'qid': i,
|
||||
'question': str(row['question']),
|
||||
'options': [str(row[f'answer{i}']) for i in range(1, 5)],
|
||||
'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']:
|
||||
return
|
||||
game = games[secret]
|
||||
|
||||
curr = game['questions'][game['current_q']]
|
||||
if int(data.get('qid', -1)) != int(curr['qid']):
|
||||
return
|
||||
|
||||
if game.get('revealed'):
|
||||
return
|
||||
if any(pid == t[0] for t in game['answered']):
|
||||
return
|
||||
|
||||
# capture reaction time
|
||||
now = time.perf_counter()
|
||||
q_started = game.get('q_started', now)
|
||||
rt = max(0.0, now - q_started)
|
||||
|
||||
# store (pid, answer, rt)
|
||||
game['answered'].append((pid, data.get('answer'), rt))
|
||||
_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:
|
||||
return
|
||||
game = games[secret]
|
||||
game['revealed'] = True
|
||||
game['current_q'] += 1
|
||||
|
||||
if game['current_q'] < len(game['questions']):
|
||||
_send_question(secret)
|
||||
else:
|
||||
# mark finished & emit final boards
|
||||
game['finished'] = True
|
||||
board = sorted(
|
||||
[{'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')
|
||||
for psid,pdata in game['players'].items():
|
||||
placement = next(i+1 for i,p in enumerate(board) if p['name']==pdata['name'])
|
||||
socketio.emit(
|
||||
'game_over',
|
||||
{'placement': placement, 'score': pdata['score']},
|
||||
room=psid
|
||||
)
|
||||
|
||||
socketio.emit('game_over', {'placement': placement, 'score': pdata['score']}, room=psid)
|
||||
|
||||
|
||||
@socketio.on('rejoin_game')
|
||||
@ -449,12 +445,13 @@ def _send_question(secret):
|
||||
game['revealed'] = False
|
||||
q = game['questions'][game['current_q']]
|
||||
game['answered'].clear()
|
||||
|
||||
# NEW: start monotonic timer for this question
|
||||
game['q_started'] = time.perf_counter()
|
||||
game['q_deadline_s'] = 20 # configurable per question if you want
|
||||
|
||||
socketio.emit('new_question', {'question': q['question'], 'options': q['options']}, room='player')
|
||||
game['q_deadline_s'] = 20
|
||||
socketio.emit('new_question', {
|
||||
'qid': q['qid'],
|
||||
'question': q['question'],
|
||||
'options': q['options']
|
||||
}, room='player')
|
||||
socketio.emit('new_question', {'question': q['question']}, room='host')
|
||||
|
||||
|
||||
|
||||
@ -102,7 +102,7 @@
|
||||
<ul id="perQ" class="list-group mb-3 text-center"></ul>
|
||||
</div>
|
||||
<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="nextBtn" class="btn btn-warning" disabled>Nächste Frage</button>
|
||||
</div>
|
||||
@ -126,7 +126,11 @@
|
||||
|
||||
/* ------------------ Persistence (no backend change) ------------------ */
|
||||
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) {
|
||||
try {
|
||||
@ -158,7 +162,7 @@
|
||||
function showSidebar(titleText = 'Rangliste') {
|
||||
document.body.classList.add('with-sidebar');
|
||||
const panel = document.getElementById('final-results');
|
||||
panel.classList.remove('centerboard'); // NEW: ensure sidebar mode
|
||||
panel.classList.remove('centerboard');
|
||||
$('#finalResultsTitle').text(titleText);
|
||||
$('#final-results').show();
|
||||
}
|
||||
@ -184,6 +188,48 @@
|
||||
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 ------------------ */
|
||||
(function restoreFromStorageOnLoad() {
|
||||
const stored = loadLeaderboardFromStorage();
|
||||
@ -216,9 +262,7 @@
|
||||
console.log('Roster update:', data.players);
|
||||
$('#roster').empty();
|
||||
(data.players || []).forEach(name => {
|
||||
$('#roster').append(
|
||||
`<li class="list-group-item">${name}</li>`
|
||||
);
|
||||
$('#roster').append(`<li class="list-group-item">${name}</li>`);
|
||||
});
|
||||
$('#startBtn').prop('disabled', (data.players || []).length === 0);
|
||||
});
|
||||
@ -238,20 +282,24 @@
|
||||
$('#host-question').show();
|
||||
$('#qText').text(data.question || '');
|
||||
$('#host-results').hide();
|
||||
$('#perQ').empty();
|
||||
$('#showAnswerBtn').prop({ disabled: false }).show();
|
||||
$('#nextBtn').prop('disabled', true);
|
||||
$('#controlsBar').show(); // show sticky buttons
|
||||
$('#controlsBar').show();
|
||||
|
||||
// Keep the sidebar visible during the game
|
||||
showSidebar('Rangliste');
|
||||
|
||||
/* NEW: (re)start the 21s auto-reveal timer */
|
||||
// Auto-reveal after 20s
|
||||
if (answerTimer) clearTimeout(answerTimer);
|
||||
answerTimer = setTimeout(() => {
|
||||
if (!$('#showAnswerBtn').prop('disabled')) {
|
||||
$('#showAnswerBtn').trigger('click');
|
||||
}
|
||||
}, 21000);
|
||||
}, 20000);
|
||||
|
||||
// === Show countdown inside the answer area ===
|
||||
showCountdownInAnswer(20000);
|
||||
});
|
||||
|
||||
// Live overall leaderboard updates -> fill the right sidebar (top 10)
|
||||
@ -259,7 +307,6 @@
|
||||
console.log('Overall leader:', data.board);
|
||||
const board = (data && Array.isArray(data.board)) ? data.board : [];
|
||||
renderAndShow('Rangliste', board);
|
||||
// Persist so a reload restores instantly
|
||||
saveLeaderboardToStorage('Rangliste', board);
|
||||
});
|
||||
|
||||
@ -267,44 +314,42 @@
|
||||
$('#nextBtn').off('click').on('click', () => {
|
||||
console.log('Next question clicked');
|
||||
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
|
||||
stopCountdownInAnswer();
|
||||
socket.emit('next_question');
|
||||
});
|
||||
|
||||
// when host clicks “Show Answer”
|
||||
$('#showAnswerBtn').off('click').on('click', () => {
|
||||
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
|
||||
stopCountdownInAnswer();
|
||||
socket.emit('show_answer');
|
||||
});
|
||||
|
||||
// once server confirms the answer is revealed
|
||||
socket.on('answer_revealed', data => {
|
||||
$('#perQ').empty().append(
|
||||
`<li class="list-group-item list-group-item-success" style="font-size:2.5rem;">${data.correct}</li>`
|
||||
);
|
||||
// Ensure the field is visible and swap countdown → answer
|
||||
$('#host-results').show();
|
||||
replaceCountdownWithAnswer(`${data.correct}`);
|
||||
|
||||
$('#showAnswerBtn').prop('disabled', true);
|
||||
$('#nextBtn').prop('disabled', false);
|
||||
|
||||
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
|
||||
stopCountdownInAnswer();
|
||||
});
|
||||
|
||||
// Final results (use the same sidebar, change the title)
|
||||
socket.on('game_over', data => {
|
||||
$('#controlsBar').hide();
|
||||
/* NEW: clear any lingering timer */
|
||||
if (answerTimer) { clearTimeout(answerTimer); answerTimer = null; }
|
||||
stopCountdownInAnswer();
|
||||
|
||||
if (data && Array.isArray(data.board)) {
|
||||
console.log('Game over');
|
||||
$('#qrContainer, #startBtn, #rosterHeader, #roster, #host-question, #host-results').hide();
|
||||
$('#newGameButton').show();
|
||||
|
||||
// NEW: switch to centered leaderboard
|
||||
showCenteredBoard('Finale Rangliste', data.board);
|
||||
|
||||
$('#startBtn').prop('disabled', true);
|
||||
|
||||
// Persist final board for reload
|
||||
saveLeaderboardToStorage('Finale Rangliste', data.board);
|
||||
}
|
||||
});
|
||||
@ -312,15 +357,11 @@
|
||||
function showCenteredBoard(title, board) {
|
||||
renderLeaderboard(board, 10);
|
||||
$('#finalResultsTitle').text(title);
|
||||
|
||||
// remove sidebar layout
|
||||
document.body.classList.remove('with-sidebar');
|
||||
|
||||
// switch the panel into centered mode + make sure it's visible
|
||||
const panel = document.getElementById('final-results');
|
||||
panel.classList.add('centerboard');
|
||||
panel.style.display = 'block'; // ← force visible
|
||||
$('#final-results').show(); // ← double-sure in jQuery land
|
||||
panel.style.display = 'block';
|
||||
$('#final-results').show();
|
||||
}
|
||||
|
||||
/* ------------------ Initial UI state for lobby ------------------ */
|
||||
|
||||
@ -80,6 +80,9 @@
|
||||
|
||||
|
||||
<script>
|
||||
let currentQuestionText = '';
|
||||
let currentQid = null;
|
||||
|
||||
// Key for storing a stable per-question order in this browser
|
||||
function orderKeyForQuestion(qText) {
|
||||
return 'order:' + hashStr(qText || '');
|
||||
@ -144,9 +147,6 @@
|
||||
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)
|
||||
let audioCtx = null;
|
||||
function playBeep() {
|
||||
@ -217,6 +217,7 @@
|
||||
socket.on('new_question', data => {
|
||||
$('#view-join, #view-wait').hide();
|
||||
$('#view-question').show();
|
||||
currentQid = data.qid;
|
||||
currentQuestionText = data.question || '';
|
||||
renderOptions(data.options, false, currentQuestionText);
|
||||
playBeep();
|
||||
@ -245,7 +246,7 @@
|
||||
const answer = $me.text();
|
||||
|
||||
// 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)
|
||||
try {
|
||||
|
||||
@ -26,7 +26,7 @@
|
||||
</p>
|
||||
<p class="text-muted">
|
||||
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>
|
||||
|
||||
<!-- Dateivorlage -->
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user