This commit is contained in:
2026-05-06 00:51:12 +03:00
commit 951f4c5c60
12 changed files with 2639 additions and 0 deletions
+127
View File
@@ -0,0 +1,127 @@
# Python
.idea
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
pythonenv*
# Flask
instance/
.webassets-cache
.env
.flaskenv
# Virtual Environment
venv/
virtualenv/
.virtualenv
.venv
pip-log.txt
pip-delete-this-directory.txt
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store
*.suo
*.user
*.sln
*.csproj
# Jupyter Notebook
.ipynb_checkpoints
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Logs and databases
*.log
*.sql
*.sqlite
*.db
*.pid
*.seed
# Generated files
*.pyc
*.pyo
*.pyd
# OS files
Thumbs.db
.DS_Store
Desktop.ini
$RECYCLE.BIN/
# Project specific
qrcodes/
*.png
*.jpg
*.jpeg
*.gif
*.bmp
*.ico
saved_results.json
result_*.html
# Environment variables
.env.local
.env.production
# Docker
.dockerignore
docker-compose.override.yml
# Backup files
*.bak
*.backup
*.old
*.orig
# Temporary files
*.tmp
*.temp
*.cache
# Package manager
package-lock.json
yarn.lock
node_modules/
# Secret keys
*.key
*.pem
*.crt
secret_key.txt
# Config files with sensitive data
config.local.py
settings.local.py
# Uploads and downloads
uploads/
downloads/
temp/
# Session files
flask_session/
sessions/
+3
View File
@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.12 (quiz_dnr)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (quiz_dnr)" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/quiz_dnr.iml" filepath="$PROJECT_DIR$/.idea/quiz_dnr.iml" />
</modules>
</component>
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+16
View File
@@ -0,0 +1,16 @@
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
+1224
View File
File diff suppressed because it is too large Load Diff
+211
View File
@@ -0,0 +1,211 @@
from flask import Flask, render_template, request, jsonify, session, send_file
from questions import QUESTION_POOL
import random
import uuid
import qrcode
from io import BytesIO
import os
import json
from datetime import datetime
app = Flask(__name__)
app.secret_key = 'dnr_youth_parliament_secret_key_2024'
# Хранилище сессий игроков и результатов
active_games = {}
saved_results = {} # Сохраняем результаты для QR-кодов
class QuizGame:
def __init__(self):
self.game_id = str(uuid.uuid4())[:8]
self.questions_pool = QUESTION_POOL.copy()
self.selected_questions = []
self.current_question_index = 0
self.score = 0
self.is_active = True
self.user_answers = []
self.start_time = datetime.now()
self._select_random_questions()
def _select_random_questions(self):
"""Выбирает 7 случайных вопросов из пула"""
if len(self.questions_pool) >= 7:
self.selected_questions = random.sample(self.questions_pool, 7)
else:
self.selected_questions = self.questions_pool.copy()
# Добавляем тайминг к каждому вопросу
for q in self.selected_questions:
q['time_limit'] = 10
def get_current_question(self):
"""Возвращает текущий вопрос (без правильного ответа)"""
if self.current_question_index < len(self.selected_questions):
q = self.selected_questions[self.current_question_index]
return {
'id': self.current_question_index,
'text': q['text'],
'options': q['options'],
'time_limit': q.get('time_limit', 10)
}
return None
def check_answer(self, answer_index):
"""Проверяет ответ и обновляет счет"""
current_q = self.selected_questions[self.current_question_index]
is_correct = (answer_index == current_q['correct'])
# Сохраняем ответ пользователя
self.user_answers.append({
'question_text': current_q['text'],
'options': current_q['options'],
'user_answer': answer_index,
'user_answer_text': current_q['options'][answer_index] if answer_index != -1 else 'Время вышло',
'correct_answer': current_q['options'][current_q['correct']],
'correct_index': current_q['correct'],
'is_correct': is_correct,
'explanation': current_q.get('explanation', '')
})
if is_correct:
self.score += 1
self.current_question_index += 1
return {
'is_correct': is_correct,
'correct_answer': current_q['options'][current_q['correct']],
'explanation': current_q.get('explanation', ''),
'score': self.score,
'is_finished': self.current_question_index >= len(self.selected_questions),
'total_questions': len(self.selected_questions)
}
def get_result(self):
"""Возвращает результат теста со всеми вопросами"""
total = len(self.selected_questions)
percentage = (self.score / total) * 100
# Определение звания/результата
if percentage >= 90:
grade = "🏆 Депутат высшей категории!"
message = "Вы отлично знаете историю и структуру Молодёжного Парламента ДНР!"
elif percentage >= 70:
grade = "⭐ Активный парламентарий!"
message = "Хороший результат! Вы достойно показали свои знания."
elif percentage >= 50:
grade = "📚 Кандидат в парламент!"
message = "Неплохо, но есть куда расти. Рекомендуем изучить материалы о работе Парламента."
else:
grade = "🌱 Будущий лидер!"
message = "Не расстраивайтесь! Участие в викторине - первый шаг к большим достижениям."
# Сохраняем результат для QR-кода
result_data = {
'game_id': self.game_id,
'score': self.score,
'total': total,
'percentage': round(percentage, 1),
'grade': grade,
'message': message,
'questions_summary': self.user_answers,
'completed_at': self.start_time.isoformat()
}
saved_results[self.game_id] = result_data
return {
'score': self.score,
'total': total,
'percentage': round(percentage, 1),
'grade': grade,
'message': message,
'questions_summary': self.user_answers,
'result_id': self.game_id # Возвращаем ID для QR-кода
}
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/new_game', methods=['POST'])
def new_game():
game = QuizGame()
active_games[game.game_id] = game
return jsonify({
'game_id': game.game_id,
'question': game.get_current_question(),
'question_number': 1,
'total_questions': len(game.selected_questions)
})
@app.route('/api/check_answer', methods=['POST'])
def check_answer():
data = request.json
game_id = data.get('game_id')
answer = data.get('answer')
game = active_games.get(game_id)
if not game or not game.is_active:
return jsonify({'error': 'Игра не найдена'}), 404
result = game.check_answer(answer)
if result['is_finished']:
# Игра завершена
final_result = game.get_result()
return jsonify({
'is_finished': True,
'result': final_result
})
else:
# Следующий вопрос
return jsonify({
'is_finished': False,
'result': result,
'next_question': game.get_current_question(),
'question_number': game.current_question_index + 1,
'total_questions': len(game.selected_questions)
})
@app.route('/api/result/<result_id>')
def get_result_page(result_id):
"""Страница с результатами по QR-коду"""
result = saved_results.get(result_id)
if not result:
return "Результат не найден", 404
return render_template('result_page.html', result=result)
@app.route('/api/qrcode/<result_id>')
def generate_qrcode(result_id):
"""Генерация QR-кода со ссылкой на результат"""
result_url = request.host_url.rstrip('/') + f'/api/result/{result_id}'
# Создаём QR-код
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(result_url)
qr.make(fit=True)
# Создаём изображение
img = qr.make_image(fill_color="black", back_color="white")
# Сохраняем в байты
img_io = BytesIO()
img.save(img_io, 'PNG')
img_io.seek(0)
return send_file(img_io, mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
+808
View File
@@ -0,0 +1,808 @@
<!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-text {
padding: 30px 30px 20px;
font-size: 24px;
font-weight: 600;
color: #333;
line-height: 1.4;
}
.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, .restart-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);
}
.next-btn {
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 {
display: flex;
flex-direction: column;
gap: 15px;
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%;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-secondary {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
.btn-qr {
background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
color: white;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.qr-container {
margin: 20px 0;
display: none;
text-align: center;
}
.qr-container.show {
display: block;
}
.qr-code {
display: inline-block;
padding: 20px;
background: white;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.qr-code img {
max-width: 200px;
height: auto;
}
.qr-link {
margin-top: 10px;
font-size: 12px;
color: #666;
word-break: break-all;
}
.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;
padding: 20px;
}
.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;
}
}
</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-text" id="questionText">
Загрузка вопроса...
</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 btn-primary" id="restartBtn">🔄 Пройти викторину заново</button>
<button class="btn btn-qr" id="showQrBtn">📱 Показать QR-код с результатом</button>
</div>
<!-- КОНТЕЙНЕР ДЛЯ QR-КОДА -->
<div class="qr-container" id="qrContainer">
<div class="qr-code" id="qrCode">
<img id="qrImage" alt="QR-код с результатом">
</div>
<div class="qr-link" id="qrLink"></div>
<button class="btn btn-secondary" id="hideQrBtn" style="margin-top: 10px; padding: 8px 20px; width: auto;">Скрыть QR-код</button>
</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 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');
qrContainer.classList.remove('show');
isAnswered = false;
startTimer(10);
} catch (error) {
console.error('Ошибка:', error);
alert('Не удалось начать игру. Проверьте соединение.');
}
}
// Отображение вопроса
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;
}
// Таймер
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';
}
}
// Обработка timeout
async function handleTimeout() {
if (isAnswered) return;
isAnswered = true;
clearInterval(timerInterval);
// Отключаем кнопки
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];
const isCorrect = (answerIndex === currentQuestion.correct);
if (isCorrect) {
selectedBtn.classList.add('correct');
} 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';
currentScore = result.score;
updateScoreDisplay();
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);
});
}
// Показать QR-код
async function showQRCode(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>`;
qrContainer.classList.add('show');
} else {
alert('Не удалось сгенерировать QR-код');
}
} catch (error) {
console.error('Ошибка:', error);
alert('Ошибка при генерации QR-кода');
}
}
// Показать результат
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;
// Показываем разбор вопросов (после кнопок)
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();
});
document.getElementById('showQrBtn').addEventListener('click', () => {
if (currentResultId) {
showQRCode(currentResultId);
} else {
alert('Результаты ещё не готовы');
}
});
document.getElementById('hideQrBtn').addEventListener('click', () => {
qrContainer.classList.remove('show');
});
// Запуск игры
startNewGame();
</script>
</body>
</html>
+215
View File
@@ -0,0 +1,215 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.result-page {
max-width: 900px;
margin: 0 auto;
background: white;
border-radius: 25px;
padding: 30px;
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
}
.header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 2px solid #e0e0e0;
}
.header h1 {
color: #f5576c;
margin-bottom: 10px;
}
.score-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
border-radius: 15px;
text-align: center;
margin-bottom: 30px;
}
.score-number {
font-size: 48px;
font-weight: bold;
margin: 10px 0;
}
.grade {
font-size: 28px;
margin: 10px 0;
}
.message {
font-size: 16px;
opacity: 0.9;
}
.questions-review {
margin-top: 30px;
}
.questions-review h3 {
margin-bottom: 20px;
color: #333;
}
.review-item {
background: #f8f9fa;
border-radius: 10px;
padding: 15px;
margin-bottom: 15px;
border-left: 5px solid;
page-break-inside: avoid;
}
.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;
}
.footer {
text-align: center;
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #e0e0e0;
color: #999;
font-size: 12px;
}
@media print {
body {
background: white;
padding: 0;
}
.result-page {
box-shadow: none;
padding: 20px;
}
}
</style>
</head>
<body>
<div class="result-page">
<div class="header">
<h1>🇩🇬 Молодёжный Парламент ДНР</h1>
<p>Результаты викторины</p>
</div>
<div class="score-card">
<h2>Ваш результат</h2>
<div class="score-number">{{ result.score }}/{{ result.total }} ({{ result.percentage }}%)</div>
<div class="grade">{{ result.grade }}</div>
<div class="message">{{ result.message }}</div>
</div>
<div class="questions-review">
<h3>📋 Детальный разбор всех вопросов</h3>
{% for item in result.questions_summary %}
<div class="review-item {{ 'correct' if item.is_correct else 'wrong' }}">
{% if item.is_correct %}
<span class="review-status status-correct">✅ Правильно</span>
{% else %}
<span class="review-status status-wrong">❌ Неправильно</span>
{% endif %}
<div class="review-question">{{ loop.index }}. {{ item.question_text }}</div>
{% if item.user_answer_text == 'Время вышло' %}
<div class="review-answer">📝 Ваш ответ: <span class="user-answer">⏰ Время вышло!</span></div>
{% else %}
<div class="review-answer">📝 Ваш ответ: <span class="user-answer">{{ item.user_answer_text }}</span></div>
{% endif %}
<div class="review-answer">✅ Правильный ответ: <span class="correct-answer">{{ item.correct_answer }}</span></div>
{% if item.explanation %}
<div class="review-explanation">💡 Пояснение: {{ item.explanation }}</div>
{% endif %}
</div>
{% endfor %}
</div>
<div class="footer">
<p>Молодёжный Парламент Донецкой Народной Республики</p>
<p>Дата прохождения: {{ result.completed_at[:19].replace('T', ' ') }}</p>
</div>
</div>
<script>
// Автоматическая печать, если нужно (опционально)
// window.print();
</script>
</body>
</html>