File size: 13,983 Bytes
1cf7e83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0a6b4f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
{% extends "Test-layout.html" %}


{% block content %}<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Dynamic General Knowledge Quiz</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
  <style>
    body { font-family: 'Inter', sans-serif; }
    .quiz-option { transition: all 0.2s ease-in-out; }
    .quiz-option:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    .quiz-option input:checked + label { background-color: #3b82f6; color: white; border-color: #2563eb; }
    .correct { border-left: 5px solid #22c55e; }
    .incorrect { border-left: 5px solid #ef4444; }
    .progress-bar { transition: width 0.3s ease-in-out; }
    #timer { transition: color 0.3s ease-in-out; }
    kbd { background-color: #f3f4f6; border: 1px solid #d1d5db; border-radius: 0.25rem; padding: 0.25rem 0.5rem; font-family: monospace; font-weight: 600; }
  </style>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen p-4">

<!-- Start Screen -->
<div id="start-container" class="w-full max-w-2xl bg-white p-6 sm:p-8 rounded-2xl shadow-lg text-center">
  <h1 class="text-3xl sm:text-4xl font-bold text-gray-800 mb-4">General Knowledge Challenge</h1>
  <p class="text-gray-600 mb-8">Test your knowledge with these quick-fire questions!</p>
  <div class="text-left bg-gray-50 p-4 rounded-lg border border-gray-200 mb-8">
    <h3 class="font-bold text-lg mb-3 text-gray-700">📜 Instructions</h3>
    <ul class="list-disc list-inside space-y-2 text-gray-600">
      <li>There are <strong id="instruction-q-count">0</strong> questions in total.</li>
      <li>You will have <strong id="instruction-time">15</strong> seconds to answer each question.</li>
      <li>You have a total of <strong id="instruction-attempts">3</strong> attempts to take this quiz.</li>
      <li class="font-semibold text-yellow-700">Once the quiz starts, do not switch tabs or windows.</li>
      <li class="font-semibold text-yellow-700">Emergency exit: <kbd>Esc</kbd>, <kbd>Space</kbd>, <kbd>A</kbd>, <kbd>M</kbd>.</li>
    </ul>
  </div>
  <button id="start-btn" class="w-full bg-blue-600 text-white font-bold py-3 px-4 rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition-transform transform hover:scale-105">
    Start Quiz
  </button>
</div>

<!-- Quiz View -->
<div id="quiz-container" class="hidden w-full max-w-2xl bg-white p-6 sm:p-8 rounded-2xl shadow-lg">
  <div class="flex justify-between items-center mb-4">
    <div id="progress-container" class="text-gray-500 font-semibold">
      Question <span id="current-question-num">1</span> of <span id="total-question-num">0</span>
    </div>
    <div id="timer-container" class="font-bold text-lg text-gray-700">
      Time: <span id="timer">15</span>s
    </div>
  </div>
  <div class="w-full bg-gray-200 rounded-full h-2.5 mb-6">
    <div id="progress-bar" class="bg-blue-600 h-2.5 rounded-full progress-bar" style="width: 0%"></div>
  </div>
  <div id="question-text" class="text-lg sm:text-xl font-semibold text-gray-800 mb-6 text-center"></div>
  <div id="options-container" class="space-y-4"></div>
  <div id="feedback" class="text-red-500 text-center font-medium mt-4 h-6"></div>
  <button id="next-btn" class="w-full bg-blue-600 text-white font-bold py-3 px-4 rounded-lg mt-6 hover:bg-blue-700 focus:outline-none focus:ring-4 focus:ring-blue-300 transition-transform transform hover:scale-105">
    Next Question
  </button>
</div>

<!-- Results View -->
<div id="score-container" class="hidden w-full max-w-3xl bg-white p-6 sm:p-8 rounded-2xl shadow-lg">
  <div id="results-content">
    <h2 class="text-2xl sm:text-3xl font-bold text-gray-800 mb-2 text-center">Quiz Complete!</h2>
    <p class="text-gray-600 mb-6 text-center">You scored <span id="final-score" class="font-bold text-blue-600 text-xl">0</span> out of <span id="total-questions" class="font-bold text-blue-600 text-xl">0</span></p>
    <div id="results-breakdown" class="space-y-4 text-left mt-8"></div>
  </div>
  <div class="w-full max-w-md mx-auto mt-8 flex flex-col sm:flex-row gap-4">
    <button id="retry-btn" class="w-full bg-gray-700 text-white font-bold py-3 px-4 rounded-lg hover:bg-gray-800 focus:outline-none focus:ring-4 focus:ring-gray-300 transition-transform transform hover:scale-105">
      Try Again
    </button>
    <button id="save-btn" class="w-full bg-green-600 text-white font-bold py-3 px-4 rounded-lg hover:bg-green-700 focus:outline-none focus:ring-4 focus:ring-green-300 transition-transform transform hover:scale-105">
      Save Results
    </button>
  </div>
  <p id="attempts-left-msg" class="text-center text-sm text-gray-500 mt-4"></p>
</div>

<!-- Limit View -->
<div id="limit-container" class="hidden w-full max-w-xl bg-white p-6 sm:p-8 rounded-2xl shadow-lg text-center">
  <h2 class="text-2xl sm:text-3xl font-bold text-gray-800 mb-4">🚫 Attempt Limit Reached</h2>
  <p class="text-gray-600 text-lg">You have already taken the <span id="topic-name-limit" class="font-semibold text-blue-600"></span> quiz 3 times.</p>
</div>

<script>
let quizData = [];
let currentQuestionIndex = 0;
let userAnswers = [];
let shuffledQuizData = [];
let quizInProgress = false;
let timerInterval;

// ✅ Topic-based attempt tracking
const params = new URLSearchParams(window.location.search);
const topic = params.get("topic") || "general";
const ATTEMPT_LIMIT = 60;
const ATTEMPT_KEY = `quizAttempts_${topic}`;
let quizAttempts = parseInt(localStorage.getItem(ATTEMPT_KEY)) || 0;

const QUESTION_TIME = 15;

// DOM references
const startContainer = document.getElementById('start-container');
const quizContainer = document.getElementById('quiz-container');
const scoreContainer = document.getElementById('score-container');
const limitContainer = document.getElementById('limit-container');
const startBtn = document.getElementById('start-btn');
const instructionQCount = document.getElementById('instruction-q-count');
const instructionTime = document.getElementById('instruction-time');
const instructionAttempts = document.getElementById('instruction-attempts');
const currentQNumEl = document.getElementById('current-question-num');
const totalQNumEl = document.getElementById('total-question-num');
const questionTextEl = document.getElementById('question-text');
const optionsContainerEl = document.getElementById('options-container');
const feedbackEl = document.getElementById('feedback');
const nextBtn = document.getElementById('next-btn');
const progressBar = document.getElementById('progress-bar');
const timerEl = document.getElementById('timer');
const finalScoreEl = document.getElementById('final-score');
const totalQuestionsEl = document.getElementById('total-questions');
const resultsBreakdownEl = document.getElementById('results-breakdown');
const retryBtn = document.getElementById('retry-btn');
const saveBtn = document.getElementById('save-btn');

// 🧩 Emergency Exit Key Listener
document.addEventListener('keydown', (e) => {
  const emergencyKeys = ['Escape', ' ', 'a', 'A', 'm', 'M'];
  if (quizInProgress && emergencyKeys.includes(e.key)) {
    e.preventDefault();
    terminateQuiz('⚠️ Emergency exit triggered!');
  }
});

// 🧩 Emergency Exit Handler
function terminateQuiz(message) {
  quizInProgress = false;
  clearInterval(timerInterval);

  // Hide quiz, show alert, save attempt
  quizContainer.classList.add('hidden');
  startContainer.classList.remove('hidden');

  alert(message);

  // Count as one attempt
  quizAttempts++;
  localStorage.setItem(ATTEMPT_KEY, quizAttempts);
  initializeQuiz();
}

// Utility
function shuffleArray(array){for(let i=array.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[array[i],array[j]]=[array[j],array[i]];}}

function startTimer(){
  let timeLeft=QUESTION_TIME;
  timerEl.textContent=timeLeft;
  timerEl.classList.remove('text-red-500');
  timerInterval=setInterval(()=>{
    timeLeft--;
    timerEl.textContent=timeLeft;
    if(timeLeft<=5) timerEl.classList.add('text-red-500');
    if(timeLeft<=0){clearInterval(timerInterval);handleNextQuestion(true);}
  },1000);
}

function showQuestion(){
  clearInterval(timerInterval);
  feedbackEl.textContent='';
  const q=shuffledQuizData[currentQuestionIndex];
  currentQNumEl.textContent=currentQuestionIndex+1;
  totalQNumEl.textContent=shuffledQuizData.length;
  progressBar.style.width=`${((currentQuestionIndex+1)/shuffledQuizData.length)*100}%`;
  questionTextEl.textContent=q.questionText;
  optionsContainerEl.innerHTML='';
  const opts=[...q.options]; shuffleArray(opts);
  opts.forEach(opt=>{
    const id=`q${currentQuestionIndex}-${opt.replace(/\s+/g,'-')}`;
    const div=document.createElement('div');div.classList.add('quiz-option');
    const input=document.createElement('input');input.type='radio';input.name=`question${currentQuestionIndex}`;input.id=id;input.value=opt;input.classList.add('hidden');
    const label=document.createElement('label');label.htmlFor=id;label.textContent=opt;label.classList.add('block','w-full','p-4','border-2','border-gray-200','rounded-lg','cursor-pointer','text-gray-700','font-medium','hover:border-blue-400');
    div.appendChild(input);div.appendChild(label);optionsContainerEl.appendChild(div);
  });
  nextBtn.textContent=currentQuestionIndex===shuffledQuizData.length-1?'Finish Quiz':'Next Question';
  startTimer();
}

function handleNextQuestion(timedOut=false){
  clearInterval(timerInterval);
  const sel=document.querySelector(`input[name="question${currentQuestionIndex}"]:checked`);
  if(timedOut) userAnswers.push(null);
  else{
    if(!sel){feedbackEl.textContent='Please select an answer!';startTimer();return;}
    userAnswers.push(sel.value);
  }
  currentQuestionIndex++;
  currentQuestionIndex<shuffledQuizData.length?showQuestion():showResults();
}

function showResults(){
  quizInProgress=false;clearInterval(timerInterval);
  quizContainer.classList.add('hidden');scoreContainer.classList.remove('hidden');
  quizAttempts++;localStorage.setItem(ATTEMPT_KEY,quizAttempts);
  resultsBreakdownEl.innerHTML='';
  let score=0;
  shuffledQuizData.forEach((q,i)=>{
    const ua=userAnswers[i];const correct=ua===q.answer;if(correct)score++;
    const div=document.createElement('div');div.classList.add('p-4','rounded-lg','bg-gray-50',correct?'correct':'incorrect');
    div.innerHTML=`<p class="font-bold text-gray-800">${i+1}. ${q.question}</p>
    <p class="mt-2 text-sm ${correct?'text-green-700':'text-red-700'}">Your answer: <span class="font-semibold">${ua||"Time's up!"}</span></p>
    ${!correct?`<p class="mt-1 text-sm text-green-700">Correct: <span class="font-semibold">${q.answer}</span></p>`:''}
    <p class="mt-2 text-sm text-gray-600 bg-gray-100 p-2 rounded"><span class="font-semibold">Explanation:</span> ${q.explanation}</p>`;
    resultsBreakdownEl.appendChild(div);
  });
  finalScoreEl.textContent=score;totalQuestionsEl.textContent=shuffledQuizData.length;
  if(score/shuffledQuizData.length>=0.8) confetti({particleCount:150,spread:90,origin:{y:0.6}});
  const left=ATTEMPT_LIMIT-quizAttempts;
  const msg=document.getElementById('attempts-left-msg');
  if(left<=0){retryBtn.disabled=true;retryBtn.textContent='No Attempts Left';retryBtn.classList.add('bg-gray-400','cursor-not-allowed');msg.textContent='You have used all your attempts.';}
  else{msg.textContent=`You have ${left} attempt${left>1?'s':''} left.`;}
}

function initializeQuiz(){
  if(quizAttempts>=ATTEMPT_LIMIT){
    document.getElementById('topic-name-limit').textContent=topic.replace(/_/g,' ');
    startContainer.classList.add('hidden');quizContainer.classList.add('hidden');scoreContainer.classList.add('hidden');limitContainer.classList.remove('hidden');
  } else {
    startContainer.classList.remove('hidden');quizContainer.classList.add('hidden');scoreContainer.classList.add('hidden');limitContainer.classList.add('hidden');
  }
}

startBtn.addEventListener('click',()=>{
  if(quizData.length===0){alert("Quiz data not loaded!");return;}
  shuffledQuizData=[...quizData];
  // shuffleArray(shuffledQuizData);
  startContainer.classList.add('hidden');
  quizContainer.classList.remove('hidden');quizInProgress=true;
  currentQuestionIndex=0;userAnswers=[];
  showQuestion();
});
nextBtn.addEventListener('click',()=>handleNextQuestion(false));
retryBtn.addEventListener('click',()=>{currentQuestionIndex=0;userAnswers=[];scoreContainer.classList.add('hidden');initializeQuiz();});
saveBtn.addEventListener('click',()=>{html2pdf().from(document.getElementById('results-content')).set({margin:1,filename:`${topic}-results.pdf`,image:{type:'jpeg',quality:0.98},html2canvas:{scale:2},jsPDF:{unit:'in',format:'letter',orientation:'portrait'}}).save();});

async function loadQuizData(){
  const count=parseInt(params.get("count"))||5;
  try{
    const res=await fetch(`/api/quiz/${topic}?count=${count}`);
    // const res = await fetch(`./data/${topic}.json`);

    if(!res.ok) throw new Error("Could not load quiz file!");
    const rawData = await res.json();
    quizData = rawData.questions.map(q => ({
      questionText: q.questionText,
      options: q.options,
      answer: q.options[q.correctAnswerIndex],  // convert index to string
      explanation: q.explanation
    }));
  }catch(e){alert("Failed to load quiz data.");quizData=[];}
  
  instructionQCount.textContent=quizData.length;
  instructionTime.textContent=QUESTION_TIME;
  instructionAttempts.textContent=ATTEMPT_LIMIT-quizAttempts;
  initializeQuiz();
}

window.addEventListener('load',loadQuizData);
</script>
</body>
</html>
 {% endblock %}