-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
360 lines (306 loc) · 10.1 KB
/
Copy pathmain.js
File metadata and controls
360 lines (306 loc) · 10.1 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import './style.css';
import confetti from 'canvas-confetti';
// App Configuration
const SETTINGS = {
timePerQuestion: 30, // seconds
storageKey: 'icd11_study_progress',
};
// Application State
let state = {
allQuestions: [], // Every parsed question from the file
sessionQuestions: [], // The current active set (Sub-set or Full)
incorrectAnswers: [], // Tracking failures for Review Mode
currentIndex: 0,
score: 0,
timerInterval: null,
timeLeft: 0,
canAnswer: true,
mode: 'marathon', // 'marathon', 'quick', or 'review'
};
// UI Elements
const screens = {
loader: document.getElementById('loader-screen'),
start: document.getElementById('start-screen'),
quiz: document.getElementById('quiz-panel'),
result: document.getElementById('result-screen'),
};
const elements = {
questionText: document.getElementById('question-text'),
optionsContainer: document.getElementById('options-container'),
nextBtn: document.getElementById('next-btn'),
timer: document.getElementById('timer'),
progressBar: document.getElementById('progress-bar'),
currentQNum: document.getElementById('current-q-num'),
totalQNum: document.getElementById('total-q-num'),
scoreVal: document.getElementById('score-val'),
resultMsg: document.getElementById('result-msg'),
restartBtn: document.getElementById('restart-btn'),
feedbackOverlay: document.getElementById('feedback-overlay'),
explanationText: document.getElementById('explanation-text'),
// New Session Buttons
marathonBtn: document.getElementById('marathon-btn'),
quickBtn: document.getElementById('quick-btn'),
continueBtn: document.getElementById('continue-btn'),
reviewBtn: document.getElementById('review-btn'),
// Progress Dashboard
progressText: document.getElementById('progress-text'),
miniProgress: document.getElementById('mini-progress'),
};
/**
* INITIALIZATION
* Fetches the master file and setups the dashboard
*/
async function init() {
try {
const response = await fetch('./icd11-quiz.txt');
if (!response.ok) throw new Error("File not found");
const text = await response.text();
state.allQuestions = parseTxtData(text);
if (state.allQuestions.length === 0) {
alert("Critical Error: No questions parsed from icd11-quiz.txt");
return;
}
loadSavedProgress();
updateDashboard();
showScreen('start');
} catch (error) {
console.error("Initialization Failed:", error);
alert("Please ensure icd11-quiz.txt is in the project root.");
}
}
/**
* PARSER
* Specifically tuned for the 'Question: / Option: / Answer: / ---' format
*/
function parseTxtData(text) {
const questions = [];
const blocks = text.split('---');
blocks.forEach(block => {
const lines = block.split('\n').map(l => l.trim()).filter(l => l);
if (lines.length < 5) return;
let q = { options: [] };
lines.forEach(line => {
const lower = line.toLowerCase();
if (lower.startsWith('question:')) q.question = line.substring(9).trim();
else if (lower.startsWith('option:')) q.options.push(line.substring(7).trim());
else if (lower.startsWith('answer:')) q.answer = line.substring(7).trim();
else if (lower.startsWith('explanation:')) q.explanation = line.substring(12).trim();
});
if (q.question && q.options.length >= 2 && q.answer) {
questions.push(q);
}
});
return questions;
}
/**
* SESSION MANAGEMENT
*/
function loadSavedProgress() {
const saved = localStorage.getItem(SETTINGS.storageKey);
if (saved) {
const data = JSON.parse(saved);
state.currentIndex = data.index || 0;
state.score = data.score || 0;
state.incorrectAnswers = data.incorrect || [];
if (state.currentIndex > 0) {
elements.continueBtn.classList.remove('hidden');
}
}
}
function saveSession() {
const data = {
index: state.currentIndex,
score: state.score,
incorrect: state.incorrectAnswers,
total: state.allQuestions.length
};
localStorage.setItem(SETTINGS.storageKey, JSON.stringify(data));
}
function updateDashboard() {
const total = state.allQuestions.length;
const current = state.currentIndex;
elements.progressText.textContent = `${current} / ${total} Mastered`;
const percent = (current / total) * 100;
elements.miniProgress.style.width = `${percent}%`;
}
/**
* START MODES
*/
function startMarathon() {
state.mode = 'marathon';
state.sessionQuestions = [...state.allQuestions]; // Original Order
state.currentIndex = 0;
state.score = 0;
state.incorrectAnswers = [];
launchQuiz();
}
function startQuick() {
state.mode = 'quick';
// Shuffle and Pick 20
state.sessionQuestions = [...state.allQuestions]
.sort(() => Math.random() - 0.5)
.slice(0, 20);
state.currentIndex = 0;
state.score = 0;
launchQuiz();
}
function continueSession() {
state.mode = 'marathon';
state.sessionQuestions = [...state.allQuestions];
// Index and Score already loaded from storage
launchQuiz();
}
function startReview() {
if (state.incorrectAnswers.length === 0) return;
state.mode = 'review';
state.sessionQuestions = [...state.incorrectAnswers];
state.currentIndex = 0;
state.score = 0;
launchQuiz();
}
function launchQuiz() {
elements.totalQNum.textContent = state.sessionQuestions.length;
showScreen('quiz');
loadQuestion();
}
/**
* QUIZ LOOP
*/
function loadQuestion() {
const currentQuestion = state.sessionQuestions[state.currentIndex];
state.canAnswer = true;
elements.nextBtn.classList.add('hidden');
elements.feedbackOverlay.classList.add('hidden');
elements.optionsContainer.innerHTML = '';
elements.questionText.textContent = currentQuestion.question;
elements.currentQNum.textContent = state.currentIndex + 1;
const progress = (state.currentIndex / state.sessionQuestions.length) * 100;
elements.progressBar.style.width = `${progress}%`;
currentQuestion.options.forEach((option) => {
const btn = document.createElement('button');
btn.className = 'option-btn';
btn.textContent = option;
btn.addEventListener('click', () => handleSelectOption(btn, option));
elements.optionsContainer.appendChild(btn);
});
startTimer();
}
function handleSelectOption(btn, selectedOption) {
if (!state.canAnswer) return;
clearInterval(state.timerInterval);
state.canAnswer = false;
const currentQuestion = state.sessionQuestions[state.currentIndex];
const isCorrect = selectedOption === currentQuestion.answer;
if (isCorrect) {
state.score++;
btn.classList.add('correct');
triggerMiniConfetti();
} else {
btn.classList.add('wrong');
// Store for review later (don't add duplicates)
if (!state.incorrectAnswers.some(q => q.question === currentQuestion.question)) {
state.incorrectAnswers.push(currentQuestion);
}
Array.from(elements.optionsContainer.children).forEach((child) => {
if (child.textContent === currentQuestion.answer) {
child.classList.add('correct');
}
});
}
if (currentQuestion.explanation) {
elements.explanationText.textContent = currentQuestion.explanation;
elements.feedbackOverlay.classList.remove('hidden');
}
elements.nextBtn.classList.remove('hidden');
// Save progress automatically after every question in marathon
if (state.mode === 'marathon') saveSession();
}
/**
* HELPERS
*/
function startTimer() {
clearInterval(state.timerInterval);
state.timeLeft = SETTINGS.timePerQuestion;
elements.timer.textContent = `${state.timeLeft}s`;
state.timerInterval = setInterval(() => {
state.timeLeft--;
elements.timer.textContent = `${state.timeLeft}s`;
if (state.timeLeft <= 0) {
clearInterval(state.timerInterval);
if (state.canAnswer) handleTimeOut();
}
}, 1000);
}
function handleTimeOut() {
state.canAnswer = false;
const currentQuestion = state.sessionQuestions[state.currentIndex];
Array.from(elements.optionsContainer.children).forEach((child) => {
if (child.textContent === currentQuestion.answer) {
child.classList.add('correct');
}
});
elements.explanationText.textContent = "Time's up! " + (currentQuestion.explanation || "");
elements.feedbackOverlay.classList.remove('hidden');
elements.nextBtn.classList.remove('hidden');
}
function handleNext() {
state.currentIndex++;
if (state.currentIndex < state.sessionQuestions.length) {
loadQuestion();
} else {
finishQuiz();
}
}
function finishQuiz() {
elements.progressBar.style.width = '100%';
elements.scoreVal.textContent = state.score;
const percentage = (state.score / state.sessionQuestions.length) * 100;
if (percentage >= 70) {
elements.resultMsg.textContent = "Excellent Work!";
triggerBigConfetti();
} else {
elements.resultMsg.textContent = "Keep Practicing!";
}
// Show review button if there are mistakes
if (state.incorrectAnswers.length > 0) {
elements.reviewBtn.classList.remove('hidden');
} else {
elements.reviewBtn.classList.add('hidden');
}
showScreen('result');
updateDashboard();
}
function showScreen(screenId) {
Object.values(screens).forEach((screen) => screen.classList.add('hidden'));
screens[screenId].classList.remove('hidden');
}
/**
* FX
*/
function triggerMiniConfetti() {
confetti({ particleCount: 15, spread: 50, origin: { y: 0.7 }, colors: ['#6366f1', '#22d3ee'] });
}
function triggerBigConfetti() {
const end = Date.now() + 2 * 1000;
const colors = ['#6366f1', '#a855f7'];
(function frame() {
confetti({ particleCount: 3, angle: 60, spread: 55, origin: { x: 0 }, colors: colors });
confetti({ particleCount: 3, angle: 120, spread: 55, origin: { x: 1 }, colors: colors });
if (Date.now() < end) requestAnimationFrame(frame);
}());
}
// Event Listeners
elements.marathonBtn.addEventListener('click', startMarathon);
elements.quickBtn.addEventListener('click', startQuick);
elements.continueBtn.addEventListener('click', continueSession);
elements.reviewBtn.addEventListener('click', startReview);
elements.nextBtn.addEventListener('click', handleNext);
elements.restartBtn.addEventListener('click', () => {
if (confirm("Reset Marathon progress?")) {
state.currentIndex = 0;
state.score = 0;
saveSession();
startMarathon();
}
});
init();