Files
dr_mp_quiz/templates/index.html
T
2026-05-08 15:23:29 +03:00

827 lines
26 KiB
HTML

<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Викторина ко Дню Молодёжного Парламента ДНР</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.quiz-container {
max-width: 900px;
width: 100%;
background: white;
border-radius: 25px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
overflow: hidden;
animation: fadeIn 0.5s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-20px); }
to { opacity: 1; transform: translateY(0); }
}
.quiz-header {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
padding: 30px;
text-align: center;
}
.quiz-header h1 {
font-size: 28px;
margin-bottom: 10px;
}
.quiz-header p {
font-size: 14px;
opacity: 0.9;
}
.quiz-info {
display: flex;
justify-content: space-between;
padding: 15px 30px;
background: #f8f9fa;
border-bottom: 2px solid #e0e0e0;
}
.question-counter, .score {
font-weight: bold;
font-size: 18px;
}
.question-counter {
color: #f5576c;
}
.score {
color: #4CAF50;
}
.timer-container {
padding: 20px 30px 0;
}
.timer-bar {
width: 100%;
height: 8px;
background: #e0e0e0;
border-radius: 10px;
overflow: hidden;
}
.timer-progress {
height: 100%;
background: linear-gradient(90deg, #4CAF50, #8BC34A);
width: 100%;
transition: width 0.1s linear;
border-radius: 10px;
}
.timer-text {
text-align: center;
margin-top: 8px;
font-size: 14px;
color: #666;
}
/* Вопрос с возможностью подсветки */
.question-wrapper {
margin: 20px 30px;
padding: 20px;
border-radius: 15px;
transition: all 0.3s ease;
position: relative;
}
.question-wrapper.correct-highlight {
background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
border: 2px solid #28a745;
box-shadow: 0 0 15px rgba(40, 167, 69, 0.3);
}
.question-wrapper.wrong-highlight {
background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
border: 2px solid #dc3545;
box-shadow: 0 0 15px rgba(220, 53, 69, 0.3);
}
.question-text {
font-size: 24px;
font-weight: 600;
color: #333;
line-height: 1.4;
margin-bottom: 10px;
}
.question-wrapper.correct-highlight .question-text {
color: #155724;
}
.question-wrapper.wrong-highlight .question-text {
color: #721c24;
}
.options {
padding: 0 30px 30px;
display: grid;
gap: 15px;
}
.option-btn {
width: 100%;
padding: 15px 20px;
font-size: 16px;
text-align: left;
background: #f8f9fa;
border: 2px solid #e0e0e0;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
font-family: inherit;
font-weight: 500;
}
.option-btn:hover:not(:disabled) {
background: #e3f2fd;
border-color: #2196F3;
transform: translateX(5px);
}
.option-btn.correct {
background: #d4edda;
border-color: #28a745;
color: #155724;
}
.option-btn.wrong {
background: #f8d7da;
border-color: #dc3545;
color: #721c24;
}
.option-btn:disabled {
cursor: not-allowed;
opacity: 0.7;
}
.next-btn {
margin: 10px 30px 30px;
padding: 15px;
font-size: 18px;
font-weight: bold;
border: none;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
width: calc(100% - 60px);
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.next-btn:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.feedback {
padding: 20px 30px;
background: #f0f8ff;
border-radius: 12px;
margin: 0 30px 20px;
}
.feedback h4 {
color: #2196F3;
margin-bottom: 10px;
}
.feedback p {
color: #555;
}
.result-container {
padding: 30px;
text-align: center;
}
.result-score {
font-size: 48px;
font-weight: bold;
color: #f5576c;
margin: 20px 0;
}
.result-grade {
font-size: 32px;
margin: 20px 0;
}
.result-message {
font-size: 18px;
color: #666;
margin: 20px 0;
line-height: 1.6;
}
.result-buttons {
margin: 20px 0 30px;
}
.result-buttons .btn {
padding: 15px;
font-size: 18px;
font-weight: bold;
border: none;
border-radius: 12px;
cursor: pointer;
transition: all 0.3s ease;
width: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.result-buttons .btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.qr-container {
margin: 30px 0;
padding: 20px;
background: #f8f9fa;
border-radius: 15px;
text-align: center;
}
.qr-code {
display: inline-block;
padding: 15px;
background: white;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin-bottom: 15px;
}
.qr-code img {
max-width: 180px;
height: auto;
display: block;
}
.qr-link {
font-size: 12px;
color: #666;
word-break: break-all;
margin-top: 10px;
}
.qr-link a {
color: #667eea;
text-decoration: none;
}
.qr-link a:hover {
text-decoration: underline;
}
.questions-review {
margin-top: 30px;
padding: 20px;
background: #f8f9fa;
border-radius: 15px;
text-align: left;
max-height: 500px;
overflow-y: auto;
}
.questions-review h3 {
margin-bottom: 20px;
color: #333;
text-align: center;
}
.review-item {
background: white;
border-radius: 10px;
padding: 15px;
margin-bottom: 15px;
border-left: 5px solid;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.review-item.correct {
border-left-color: #28a745;
}
.review-item.wrong {
border-left-color: #dc3545;
}
.review-status {
display: inline-block;
padding: 3px 10px;
border-radius: 20px;
font-size: 12px;
font-weight: bold;
margin-bottom: 8px;
}
.status-correct {
background: #d4edda;
color: #155724;
}
.status-wrong {
background: #f8d7da;
color: #721c24;
}
.review-question {
font-weight: bold;
font-size: 16px;
margin-bottom: 10px;
color: #333;
}
.review-answer {
margin: 8px 0;
font-size: 14px;
}
.user-answer {
color: #dc3545;
}
.correct-answer {
color: #28a745;
font-weight: bold;
}
.review-explanation {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid #e0e0e0;
font-size: 13px;
color: #666;
font-style: italic;
}
.hidden {
display: none;
}
@media (max-width: 600px) {
.question-text {
font-size: 18px;
}
.option-btn {
font-size: 14px;
padding: 12px 15px;
}
.quiz-header h1 {
font-size: 22px;
}
.questions-review {
margin-top: 20px;
padding: 15px;
}
.result-score {
font-size: 36px;
}
.result-grade {
font-size: 24px;
}
.qr-code img {
max-width: 150px;
}
.question-wrapper {
margin: 15px 15px;
padding: 15px;
}
}
</style>
</head>
<body>
<div class="quiz-container" id="quizContainer">
<div class="quiz-header">
<h1>🇩🇬 Викторина ко Дню Молодёжного Парламента ДНР</h1>
<p>Проверь свои знания о молодёжной политике Республики!</p>
</div>
<div id="gameArea">
<div class="quiz-info">
<span class="question-counter" id="questionCounter">Вопрос 1/7</span>
<span class="score" id="scoreDisplay">Счёт: 0</span>
</div>
<div id="questionArea">
<div class="timer-container">
<div class="timer-bar">
<div class="timer-progress" id="timerProgress"></div>
</div>
<div class="timer-text" id="timerText">⏱️ 10 секунд</div>
</div>
<div class="question-wrapper" id="questionWrapper">
<div class="question-text" id="questionText">
Загрузка вопроса...
</div>
</div>
<div class="options" id="optionsContainer">
<button class="option-btn" data-index="0">Вариант 1</button>
<button class="option-btn" data-index="1">Вариант 2</button>
<button class="option-btn" data-index="2">Вариант 3</button>
<button class="option-btn" data-index="3">Вариант 4</button>
</div>
<div class="feedback hidden" id="feedback">
<h4 id="feedbackTitle"></h4>
<p id="feedbackText"></p>
</div>
<button class="next-btn hidden" id="nextBtn">➡️ Следующий вопрос</button>
</div>
<div id="resultArea" class="result-container hidden">
<h2>🎉 Викторина завершена! 🎉</h2>
<div class="result-score" id="resultScore">0/7</div>
<div class="result-grade" id="resultGrade"></div>
<div class="result-message" id="resultMessage"></div>
<div class="result-buttons">
<button class="btn" id="restartBtn">🔄 Пройти викторину заново</button>
</div>
<div class="qr-container" id="qrContainer">
<div class="qr-code">
<img id="qrImage" alt="QR-код с результатом">
</div>
<div class="qr-link" id="qrLink"></div>
</div>
<div id="questionsReview" class="questions-review hidden"></div>
</div>
</div>
</div>
<script>
let gameId = null;
let currentQuestion = null;
let timerInterval = null;
let timeLeft = 10;
let isAnswered = false;
let totalQuestions = 7;
let currentScore = 0;
let currentResultId = null;
// DOM элементы
const questionCounter = document.getElementById('questionCounter');
const scoreDisplay = document.getElementById('scoreDisplay');
const timerProgress = document.getElementById('timerProgress');
const timerText = document.getElementById('timerText');
const questionText = document.getElementById('questionText');
const questionWrapper = document.getElementById('questionWrapper');
const optionsContainer = document.getElementById('optionsContainer');
const feedback = document.getElementById('feedback');
const nextBtn = document.getElementById('nextBtn');
const questionArea = document.getElementById('questionArea');
const resultArea = document.getElementById('resultArea');
const questionsReview = document.getElementById('questionsReview');
const qrContainer = document.getElementById('qrContainer');
const qrImage = document.getElementById('qrImage');
const qrLink = document.getElementById('qrLink');
const optionBtns = document.querySelectorAll('.option-btn');
async function startNewGame() {
try {
const response = await fetch('/api/new_game', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
});
const data = await response.json();
gameId = data.game_id;
totalQuestions = data.total_questions;
currentScore = 0;
currentResultId = null;
updateScoreDisplay();
displayQuestion(data.question, data.question_number);
questionArea.classList.remove('hidden');
resultArea.classList.add('hidden');
questionsReview.classList.add('hidden');
isAnswered = false;
removeQuestionHighlight();
startTimer(10);
} catch (error) {
console.error('Ошибка:', error);
alert('Не удалось начать игру. Проверьте соединение.');
}
}
function highlightQuestion(isCorrect) {
removeQuestionHighlight();
if (isCorrect) {
questionWrapper.classList.add('correct-highlight');
} else {
questionWrapper.classList.add('wrong-highlight');
}
}
function removeQuestionHighlight() {
questionWrapper.classList.remove('correct-highlight');
questionWrapper.classList.remove('wrong-highlight');
}
function displayQuestion(question, qNumber) {
if (!question) return;
currentQuestion = question;
questionCounter.textContent = `Вопрос ${qNumber}/${totalQuestions}`;
questionText.textContent = question.text;
question.options.forEach((option, index) => {
if (optionBtns[index]) {
optionBtns[index].textContent = `${String.fromCharCode(65+index)}. ${option}`;
optionBtns[index].disabled = false;
optionBtns[index].classList.remove('correct', 'wrong');
}
});
feedback.classList.add('hidden');
nextBtn.classList.add('hidden');
isAnswered = false;
removeQuestionHighlight();
}
function startTimer(seconds) {
if (timerInterval) clearInterval(timerInterval);
timeLeft = seconds;
updateTimerUI();
timerInterval = setInterval(() => {
if (!isAnswered && timeLeft > 0) {
timeLeft--;
updateTimerUI();
if (timeLeft === 0) {
clearInterval(timerInterval);
handleTimeout();
}
}
}, 1000);
}
function updateTimerUI() {
const percentage = (timeLeft / 10) * 100;
timerProgress.style.width = `${percentage}%`;
timerText.textContent = `⏱️ ${timeLeft} секунд`;
if (timeLeft <= 3) {
timerProgress.style.background = '#ff5722';
timerText.style.color = '#ff5722';
} else {
timerProgress.style.background = 'linear-gradient(90deg, #4CAF50, #8BC34A)';
timerText.style.color = '#666';
}
}
async function handleTimeout() {
if (isAnswered) return;
isAnswered = true;
clearInterval(timerInterval);
highlightQuestion(false);
optionBtns.forEach(btn => btn.disabled = true);
try {
const response = await fetch('/api/check_answer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
game_id: gameId,
answer: -1
})
});
const data = await response.json();
if (data.is_finished) {
showResult(data.result);
} else {
showFeedback({
is_correct: false,
correct_answer: currentQuestion.options[0],
explanation: 'Время вышло!'
});
setTimeout(() => loadNextQuestion(data), 2000);
}
} catch (error) {
console.error('Ошибка:', error);
}
}
async function handleAnswer(answerIndex) {
if (isAnswered) return;
isAnswered = true;
clearInterval(timerInterval);
const selectedBtn = optionBtns[answerIndex];
// ВАЖНО: проверяем правильность ответа
// currentQuestion.correct приходит от сервера с индексом правильного ответа
const isCorrect = (answerIndex === currentQuestion.correct);
console.log('Answer index:', answerIndex);
console.log('Correct index:', currentQuestion.correct);
console.log('Is correct:', isCorrect);
// Подсвечиваем вопрос
highlightQuestion(isCorrect);
if (isCorrect) {
selectedBtn.classList.add('correct');
currentScore++;
updateScoreDisplay();
} else {
selectedBtn.classList.add('wrong');
const correctBtn = optionBtns[currentQuestion.correct];
if (correctBtn) correctBtn.classList.add('correct');
}
optionBtns.forEach(btn => btn.disabled = true);
try {
const response = await fetch('/api/check_answer', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
game_id: gameId,
answer: answerIndex
})
});
const data = await response.json();
if (data.is_finished) {
showResult(data.result);
} else {
showFeedback(data.result);
setTimeout(() => loadNextQuestion(data), 2000);
}
} catch (error) {
console.error('Ошибка:', error);
}
}
function showFeedback(result) {
const feedbackTitle = document.getElementById('feedbackTitle');
const feedbackText = document.getElementById('feedbackText');
if (result.is_correct) {
feedbackTitle.textContent = '✅ Правильно!';
feedbackTitle.style.color = '#28a745';
feedbackText.textContent = result.explanation || 'Отличный результат!';
} else {
feedbackTitle.textContent = '❌ Неправильно!';
feedbackTitle.style.color = '#dc3545';
feedbackText.innerHTML = `Правильный ответ: ${result.correct_answer}<br>${result.explanation || ''}`;
}
feedback.classList.remove('hidden');
}
function loadNextQuestion(data) {
if (data.next_question) {
displayQuestion(data.next_question, data.question_number);
startTimer(10);
}
}
function displayAllQuestions(questionsSummary) {
questionsReview.innerHTML = '<h3>📋 Детальный разбор всех вопросов</h3>';
questionsReview.classList.remove('hidden');
questionsSummary.forEach((item, index) => {
const questionDiv = document.createElement('div');
questionDiv.className = `review-item ${item.is_correct ? 'correct' : 'wrong'}`;
const status = item.is_correct ?
'<span class="review-status status-correct">✅ Правильно</span>' :
'<span class="review-status status-wrong">❌ Неправильно</span>';
let userAnswerDisplay = '';
if (item.user_answer_text === 'Время вышло') {
userAnswerDisplay = `<div class="review-answer">📝 Ваш ответ: <span class="user-answer">⏰ Время вышло!</span></div>`;
} else {
const letter = String.fromCharCode(65 + item.user_answer);
userAnswerDisplay = `<div class="review-answer">📝 Ваш ответ: <span class="user-answer">${letter}. ${item.user_answer_text}</span></div>`;
}
const correctLetter = String.fromCharCode(65 + item.correct_index);
questionDiv.innerHTML = `
${status}
<div class="review-question">${index + 1}. ${item.question_text}</div>
${userAnswerDisplay}
<div class="review-answer">✅ Правильный ответ: <span class="correct-answer">${correctLetter}. ${item.correct_answer}</span></div>
${item.explanation ? `<div class="review-explanation">💡 Пояснение: ${item.explanation}</div>` : ''}
`;
questionsReview.appendChild(questionDiv);
});
}
async function displayQRCode(resultId) {
try {
const response = await fetch(`/api/qrcode/${resultId}`);
if (response.ok) {
const blob = await response.blob();
const url = URL.createObjectURL(blob);
qrImage.src = url;
// Ссылка на изображение с результатами
const fullUrl = window.location.origin + `/api/result/${resultId}`;
qrLink.innerHTML = `📎 Ссылка на результат: <a href="${fullUrl}" target="_blank">${fullUrl}</a>`;
} else {
qrContainer.innerHTML = '<p style="color: red;">❌ Не удалось сгенерировать QR-код</p>';
}
} catch (error) {
console.error('Ошибка:', error);
qrContainer.innerHTML = '<p style="color: red;">❌ Ошибка при генерации QR-кода</p>';
}
}
function showResult(result) {
clearInterval(timerInterval);
questionArea.classList.add('hidden');
resultArea.classList.remove('hidden');
const resultScore = document.getElementById('resultScore');
const resultGrade = document.getElementById('resultGrade');
const resultMessage = document.getElementById('resultMessage');
resultScore.textContent = `${result.score}/${result.total} (${result.percentage}%)`;
resultGrade.textContent = result.grade;
resultMessage.textContent = result.message;
currentResultId = result.result_id;
displayQRCode(currentResultId);
if (result.questions_summary) {
displayAllQuestions(result.questions_summary);
}
}
function updateScoreDisplay() {
scoreDisplay.textContent = `Счёт: ${currentScore}`;
}
optionBtns.forEach(btn => {
btn.addEventListener('click', () => {
const index = parseInt(btn.dataset.index);
handleAnswer(index);
});
});
document.getElementById('restartBtn').addEventListener('click', () => {
startNewGame();
});
startNewGame();
</script>
</body>
</html>