-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1658 lines (1471 loc) · 61.4 KB
/
script.js
File metadata and controls
1658 lines (1471 loc) · 61.4 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Application state
const AppState = {
WELCOME: 'welcome',
QUIZ: 'quiz',
RESULTS: 'results',
REVIEW: 'review',
HISTORY: 'history'
};
// Current application state
let currentState = AppState.WELCOME;
let selectedTopic = null;
let selectedDifficulty = null;
let selectedQuestionCount = 10; // Default to 10 questions
let selectedQuestionType = 'any'; // 'any', 'multiple', 'boolean'
let currentQuestionIndex = 0;
let userAnswers = [];
let quizStartTime = null;
let timerInterval = null;
let timeElapsed = 0;
let streakCount = 0;
let totalQuizzesTaken = 0;
let totalLearningTime = 0;
let totalCorrectAnswers = 0;
let totalQuestionsAnswered = 0;
let userXP = 0;
let userLevel = 1;
let isLoadingQuestions = false;
let apiQuestionsCache = {}; // Cache API responses
// Question bank with more engaging questions
const questions = [
// Science questions
{
id: 1,
topic: "Science 🔬",
difficulty: "easy",
type: "multiple_choice",
question: "What is the chemical symbol for Gold? 💰",
options: ["Go", "Gd", "Au", "Ag"],
correctAnswer: "Au",
explanation: "Gold's chemical symbol is Au from Latin 'aurum'. It's one of the least reactive chemical elements!",
points: 10,
timeLimit: 30
},
{
id: 2,
topic: "Science 🔬",
difficulty: "medium",
type: "multiple_choice",
question: "Which planet is known as the Red Planet? 🪐",
options: ["Venus", "Mars", "Jupiter", "Saturn"],
correctAnswer: "Mars",
explanation: "Mars is called the Red Planet due to iron oxide (rust) on its surface. It has the largest volcano in the solar system!",
points: 15,
timeLimit: 25
},
{
id: 3,
topic: "Science 🔬",
difficulty: "hard",
type: "true_false",
question: "Mitochondria are known as the powerhouse of the cell. ⚡",
options: ["True", "False"],
correctAnswer: "True",
explanation: "Mitochondria generate most of the cell's supply of adenosine triphosphate (ATP), used as a source of chemical energy.",
points: 20,
timeLimit: 20
},
// History questions
{
id: 4,
topic: "History 📜",
difficulty: "medium",
type: "multiple_choice",
question: "Who was the first President of the United States? 🇺🇸",
options: ["Thomas Jefferson", "Abraham Lincoln", "George Washington", "John Adams"],
correctAnswer: "George Washington",
explanation: "George Washington served as the first U.S. President from 1789 to 1797. He's on the one-dollar bill!",
points: 15,
timeLimit: 25
},
{
id: 5,
topic: "History 📜",
difficulty: "hard",
type: "multiple_choice",
question: "In which year did World War II end? ⚔️",
options: ["1943", "1945", "1947", "1950"],
correctAnswer: "1945",
explanation: "World War II ended in 1945 with the surrender of Germany and Japan. The war lasted 6 years!",
points: 20,
timeLimit: 30
},
// Mathematics questions
{
id: 6,
topic: "Mathematics 🧮",
difficulty: "easy",
type: "multiple_choice",
question: "What is 15 × 6? ✖️",
options: ["80", "90", "100", "110"],
correctAnswer: "90",
explanation: "15 multiplied by 6 equals 90. Multiplication is repeated addition!",
points: 10,
timeLimit: 20
},
{
id: 7,
topic: "Mathematics 🧮",
difficulty: "hard",
type: "multiple_choice",
question: "What is the value of π (pi) rounded to two decimal places? 🥧",
options: ["3.14", "3.16", "3.12", "3.18"],
correctAnswer: "3.14",
explanation: "π is approximately 3.14159, which rounds to 3.14 to two decimal places. Pi is infinite and non-repeating!",
points: 20,
timeLimit: 25
},
// Literature questions
{
id: 8,
topic: "Literature 📚",
difficulty: "medium",
type: "multiple_choice",
question: "Who wrote 'Romeo and Juliet'? 🎭",
options: ["Charles Dickens", "William Shakespeare", "Jane Austen", "Mark Twain"],
correctAnswer: "William Shakespeare",
explanation: "'Romeo and Juliet' is a tragedy written by William Shakespeare early in his career. It's one of his most popular plays!",
points: 15,
timeLimit: 25
},
// Technology questions
{
id: 9,
topic: "Technology 💻",
difficulty: "easy",
type: "multiple_choice",
question: "What does 'HTML' stand for? 🌐",
options: ["Hyper Text Markup Language", "High Tech Modern Language", "Hyper Transfer Markup Language", "Home Tool Markup Language"],
correctAnswer: "Hyper Text Markup Language",
explanation: "HTML stands for Hyper Text Markup Language, the standard markup language for web pages. It structures content on the web!",
points: 10,
timeLimit: 25
},
{
id: 10,
topic: "Technology 💻",
difficulty: "hard",
type: "multiple_choice",
question: "Which programming language is known as the 'language of the web'? 🕸️",
options: ["Python", "Java", "JavaScript", "C++"],
correctAnswer: "JavaScript",
explanation: "JavaScript is the primary language for interactive web content and runs in all modern web browsers. It brings websites to life!",
points: 20,
timeLimit: 30
},
// Geography questions
{
id: 11,
topic: "Geography 🌍",
difficulty: "easy",
type: "multiple_choice",
question: "What is the capital of France? 🇫🇷",
options: ["London", "Berlin", "Paris", "Madrid"],
correctAnswer: "Paris",
explanation: "Paris is the capital and most populous city of France, known for the Eiffel Tower!",
points: 10,
timeLimit: 20
},
{
id: 12,
topic: "Geography 🌍",
difficulty: "medium",
type: "multiple_choice",
question: "Which is the longest river in the world? 🌊",
options: ["Amazon River", "Nile River", "Yangtze River", "Mississippi River"],
correctAnswer: "Nile River",
explanation: "The Nile River is approximately 6,650 km long, flowing through northeastern Africa!",
points: 15,
timeLimit: 25
},
{
id: 13,
topic: "Geography 🌍",
difficulty: "hard",
type: "multiple_choice",
question: "Which country has the most time zones? ⏰",
options: ["USA", "Russia", "France", "China"],
correctAnswer: "France",
explanation: "France has 12 time zones due to its overseas territories, more than any other country!",
points: 20,
timeLimit: 30
},
// Sports questions
{
id: 14,
topic: "Sports ⚽",
difficulty: "easy",
type: "multiple_choice",
question: "How many players are on a soccer team? ⚽",
options: ["9", "10", "11", "12"],
correctAnswer: "11",
explanation: "A soccer team has 11 players on the field at one time, including the goalkeeper!",
points: 10,
timeLimit: 20
},
{
id: 15,
topic: "Sports ⚽",
difficulty: "medium",
type: "multiple_choice",
question: "In which sport would you perform a slam dunk? 🏀",
options: ["Tennis", "Basketball", "Volleyball", "Baseball"],
correctAnswer: "Basketball",
explanation: "A slam dunk is a basketball shot where a player jumps and scores by putting the ball directly through the hoop!",
points: 15,
timeLimit: 25
},
{
id: 16,
topic: "Sports ⚽",
difficulty: "hard",
type: "multiple_choice",
question: "Which country has won the most FIFA World Cups? 🏆",
options: ["Germany", "Argentina", "Brazil", "Italy"],
correctAnswer: "Brazil",
explanation: "Brazil has won the FIFA World Cup 5 times (1958, 1962, 1970, 1994, 2002)!",
points: 20,
timeLimit: 30
},
// More Science questions
{
id: 17,
topic: "Science 🔬",
difficulty: "easy",
type: "multiple_choice",
question: "What is H2O commonly known as? 💧",
options: ["Oxygen", "Water", "Hydrogen", "Carbon Dioxide"],
correctAnswer: "Water",
explanation: "H2O is the chemical formula for water - 2 hydrogen atoms and 1 oxygen atom!",
points: 10,
timeLimit: 20
},
{
id: 18,
topic: "Science 🔬",
difficulty: "medium",
type: "multiple_choice",
question: "What is the speed of light? ⚡",
options: ["299,792 km/s", "150,000 km/s", "500,000 km/s", "100,000 km/s"],
correctAnswer: "299,792 km/s",
explanation: "Light travels at approximately 299,792 kilometers per second in a vacuum!",
points: 15,
timeLimit: 25
},
// More History questions
{
id: 19,
topic: "History 📜",
difficulty: "easy",
type: "multiple_choice",
question: "Who discovered America in 1492? ⛵",
options: ["Marco Polo", "Christopher Columbus", "Vasco da Gama", "Ferdinand Magellan"],
correctAnswer: "Christopher Columbus",
explanation: "Christopher Columbus reached the Americas in 1492, though Vikings had arrived earlier!",
points: 10,
timeLimit: 25
},
{
id: 20,
topic: "History 📜",
difficulty: "medium",
type: "multiple_choice",
question: "Which ancient wonder of the world still exists today? 🏛️",
options: ["Hanging Gardens", "Colossus of Rhodes", "Great Pyramid of Giza", "Lighthouse of Alexandria"],
correctAnswer: "Great Pyramid of Giza",
explanation: "The Great Pyramid of Giza is the only ancient wonder still standing today!",
points: 15,
timeLimit: 30
},
// More Mathematics questions
{
id: 21,
topic: "Mathematics 🧮",
difficulty: "medium",
type: "multiple_choice",
question: "What is the square root of 144? 📐",
options: ["10", "11", "12", "13"],
correctAnswer: "12",
explanation: "The square root of 144 is 12, because 12 × 12 = 144!",
points: 15,
timeLimit: 25
},
{
id: 22,
topic: "Mathematics 🧮",
difficulty: "hard",
type: "multiple_choice",
question: "What is 25% of 200? 🔢",
options: ["25", "50", "75", "100"],
correctAnswer: "50",
explanation: "25% of 200 is 50. To calculate: (25/100) × 200 = 50!",
points: 20,
timeLimit: 30
},
// More Literature questions
{
id: 23,
topic: "Literature 📚",
difficulty: "easy",
type: "multiple_choice",
question: "Who wrote 'Harry Potter'? 🪄",
options: ["J.R.R. Tolkien", "J.K. Rowling", "C.S. Lewis", "Roald Dahl"],
correctAnswer: "J.K. Rowling",
explanation: "J.K. Rowling wrote the Harry Potter series, one of the best-selling book series in history!",
points: 10,
timeLimit: 20
},
{
id: 24,
topic: "Literature 📚",
difficulty: "hard",
type: "multiple_choice",
question: "In which year was '1984' by George Orwell published? 📖",
options: ["1948", "1949", "1950", "1984"],
correctAnswer: "1949",
explanation: "George Orwell's dystopian novel '1984' was published in 1949, not 1984!",
points: 20,
timeLimit: 30
},
// More Technology questions
{
id: 25,
topic: "Technology 💻",
difficulty: "medium",
type: "multiple_choice",
question: "Who is the founder of Microsoft? 🖥️",
options: ["Steve Jobs", "Bill Gates", "Mark Zuckerberg", "Elon Musk"],
correctAnswer: "Bill Gates",
explanation: "Bill Gates co-founded Microsoft with Paul Allen in 1975!",
points: 15,
timeLimit: 25
},
{
id: 26,
topic: "Technology 💻",
difficulty: "easy",
type: "multiple_choice",
question: "What does 'WWW' stand for? 🌐",
options: ["World Wide Web", "World Web Wide", "Web World Wide", "Wide World Web"],
correctAnswer: "World Wide Web",
explanation: "WWW stands for World Wide Web, invented by Tim Berners-Lee in 1989!",
points: 10,
timeLimit: 20
}
];
// Available topics and difficulties with icons
const topics = [
{ name: "General Knowledge 🧠", icon: "🧠", apiId: 9 },
{ name: "Science 🔬", icon: "🔬", apiId: 17 },
{ name: "History 📜", icon: "📜", apiId: 23 },
{ name: "Mathematics 🧮", icon: "🧮", apiId: 19 },
{ name: "Literature 📚", icon: "📚", apiId: 10 },
{ name: "Technology 💻", icon: "💻", apiId: 18 },
{ name: "Geography 🌍", icon: "🌍", apiId: 22 },
{ name: "Sports ⚽", icon: "⚽", apiId: 21 },
{ name: "Movies 🎬", icon: "🎬", apiId: 11 },
{ name: "Music 🎵", icon: "🎵", apiId: 12 },
{ name: "Mixed 🎲", icon: "🎲", apiId: null }
];
const difficulties = [
{ name: "Easy 😊", icon: "😊", apiValue: "easy" },
{ name: "Medium 🤔", icon: "🤔", apiValue: "medium" },
{ name: "Hard 🧠", icon: "🧠", apiValue: "hard" },
{ name: "Mixed 🎯", icon: "🎯", apiValue: null }
];
const questionCounts = [5, 10, 15, 20];
const questionTypes = [
{ name: "All Types 🎲", value: "any" },
{ name: "Multiple Choice 📝", value: "multiple" },
{ name: "True/False ✓✗", value: "boolean" }
];
// DOM elements
const contentCard = document.getElementById('content-card');
const footerNav = document.getElementById('footer-nav');
const timerElement = document.getElementById('timer');
const overallScoreElement = document.getElementById('overall-score');
const quizzesTakenElement = document.getElementById('quizzes-taken');
const totalTimeElement = document.getElementById('total-time');
const userLevelElement = document.getElementById('user-level');
const statAccuracyElement = document.getElementById('stat-accuracy');
const statStreakElement = document.getElementById('stat-streak');
const statMasteryElement = document.getElementById('stat-mastery');
const statXPElement = document.getElementById('stat-xp');
const streakFireElement = document.getElementById('streak-fire');
const streakCountElement = document.getElementById('streak-count');
const xpProgressElement = document.getElementById('xp-progress');
const xpProgressTextElement = document.getElementById('xp-progress-text');
const notificationElement = document.getElementById('notification');
const notificationTitleElement = document.getElementById('notification-title');
const notificationMessageElement = document.getElementById('notification-message');
// Load user data from localStorage
function loadUserData() {
const savedData = localStorage.getItem('knowledgeQuestData');
if (savedData) {
const data = JSON.parse(savedData);
totalQuizzesTaken = data.totalQuizzesTaken || 0;
totalLearningTime = data.totalLearningTime || 0;
totalCorrectAnswers = data.totalCorrectAnswers || 0;
totalQuestionsAnswered = data.totalQuestionsAnswered || 0;
userXP = data.userXP || 0;
userLevel = data.userLevel || 1;
streakCount = data.streakCount || 0;
// Update UI with loaded data
updateUserProgress();
}
}
// Save quiz history to localStorage
function saveQuizHistory(quizData) {
let history = JSON.parse(localStorage.getItem('knowledgeQuestHistory') || '[]');
// Add new quiz to history
history.unshift({
id: Date.now(),
date: new Date().toISOString(),
topic: selectedTopic,
difficulty: selectedDifficulty,
score: quizData.score,
totalQuestions: quizData.totalQuestions,
correctAnswers: quizData.correctAnswers,
timeSpent: quizData.timeSpent,
xpEarned: quizData.xpEarned
});
// Keep only last 50 quizzes
if (history.length > 50) {
history = history.slice(0, 50);
}
localStorage.setItem('knowledgeQuestHistory', JSON.stringify(history));
}
// Get quiz history from localStorage
function getQuizHistory() {
return JSON.parse(localStorage.getItem('knowledgeQuestHistory') || '[]');
}
// Save user data to localStorage
function saveUserData() {
const data = {
totalQuizzesTaken,
totalLearningTime,
totalCorrectAnswers,
totalQuestionsAnswered,
userXP,
userLevel,
streakCount
};
localStorage.setItem('knowledgeQuestData', JSON.stringify(data));
}
// Show notification
function showNotification(title, message, type = 'success') {
notificationTitleElement.textContent = title;
notificationMessageElement.textContent = message;
// Set color based on type
if (type === 'success') {
notificationElement.style.borderLeftColor = 'var(--success)';
notificationElement.querySelector('.notification-icon').style.background = 'var(--gradient-success)';
} else if (type === 'error') {
notificationElement.style.borderLeftColor = 'var(--danger)';
notificationElement.querySelector('.notification-icon').style.background = 'var(--gradient-danger)';
} else if (type === 'warning') {
notificationElement.style.borderLeftColor = 'var(--warning)';
notificationElement.querySelector('.notification-icon').style.background = 'var(--gradient-warning)';
}
notificationElement.classList.add('show');
// Hide after 3 seconds
setTimeout(() => {
notificationElement.classList.remove('show');
}, 3000);
}
// Add XP to user
function addXP(amount, reason) {
const oldXP = userXP;
userXP += amount;
// Check for level up
const xpForNextLevel = userLevel * 100;
if (userXP >= xpForNextLevel) {
userLevel++;
userXP = userXP - xpForNextLevel;
showNotification(`Level Up! 🎉`, `You've reached Level ${userLevel}! Keep going!`, 'success');
// Create confetti for level up
createConfetti();
}
// Update UI
updateUserProgress();
// Show XP notification
if (reason) {
showNotification(`+${amount} XP!`, reason, 'success');
}
// Save data
saveUserData();
}
// Update user progress indicators
function updateUserProgress() {
quizzesTakenElement.textContent = totalQuizzesTaken;
userLevelElement.textContent = userLevel;
// Calculate overall score
const overallScore = totalQuestionsAnswered > 0
? Math.round((totalCorrectAnswers / totalQuestionsAnswered) * 100)
: 0;
overallScoreElement.textContent = `${overallScore}%`;
// Update learning time
const hours = Math.floor(totalLearningTime / 3600);
const minutes = Math.floor((totalLearningTime % 3600) / 60);
if (hours > 0) {
totalTimeElement.textContent = `${hours}h ${minutes}m`;
} else {
totalTimeElement.textContent = `${minutes}m`;
}
// Update stats
const accuracy = totalQuestionsAnswered > 0
? Math.round((totalCorrectAnswers / totalQuestionsAnswered) * 100)
: 0;
statAccuracyElement.textContent = `${accuracy}%`;
statStreakElement.textContent = `${streakCount} 🔥`;
statXPElement.textContent = userXP;
// Update mastery level based on accuracy
let mastery = "Beginner 🐣";
if (accuracy >= 90) mastery = "Expert 🦉";
else if (accuracy >= 75) mastery = "Advanced 🚀";
else if (accuracy >= 50) mastery = "Intermediate 📈";
statMasteryElement.textContent = mastery;
// Update XP progress bar
const xpForNextLevel = userLevel * 100;
const xpProgress = Math.min((userXP / xpForNextLevel) * 100, 100);
xpProgressElement.style.width = `${xpProgress}%`;
xpProgressTextElement.textContent = `${userXP}/${xpForNextLevel}`;
// Update achievements
updateAchievements();
}
// Update achievements based on user progress
function updateAchievements() {
// First quiz achievement
if (totalQuizzesTaken > 0) {
document.getElementById('achievement-1').classList.add('unlocked');
}
// Streak achievement
if (streakCount >= 5) {
document.getElementById('achievement-2').classList.add('unlocked');
}
// Accuracy achievement
const accuracy = totalQuestionsAnswered > 0
? (totalCorrectAnswers / totalQuestionsAnswered) * 100
: 0;
if (accuracy >= 90) {
document.getElementById('achievement-3').classList.add('unlocked');
}
}
// Start the timer
function startTimer() {
quizStartTime = Date.now();
timeElapsed = 0;
if (timerInterval) clearInterval(timerInterval);
timerInterval = setInterval(() => {
timeElapsed++;
const minutes = Math.floor(timeElapsed / 60);
const seconds = timeElapsed % 60;
timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
// Change color when time is running out
if (timeElapsed > 120) {
timerElement.style.color = 'var(--danger)';
} else if (timeElapsed > 60) {
timerElement.style.color = 'var(--warning)';
}
}, 1000);
}
// Stop the timer
function stopTimer() {
if (timerInterval) {
clearInterval(timerInterval);
timerInterval = null;
}
// Reset timer color
timerElement.style.color = 'var(--primary)';
}
// Shuffle array (Fisher-Yates algorithm)
function shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// Current quiz data
let currentQuizQuestions = [];
let quizTimeLimit = 0;
// ==================== API INTEGRATION ====================
// Open Trivia Database API Integration
async function fetchQuestionsFromAPI(count, categoryId, difficulty, type) {
// Create cache key
const cacheKey = `${count}_${categoryId}_${difficulty}_${type}`;
// Check cache first (valid for 5 minutes)
const cachedData = apiQuestionsCache[cacheKey];
if (cachedData && Date.now() - cachedData.timestamp < 300000) {
console.log('Using cached API data');
return cachedData.questions;
}
// Build API URL
let apiUrl = `https://opentdb.com/api.php?amount=${count}`;
if (categoryId) {
apiUrl += `&category=${categoryId}`;
}
if (difficulty) {
apiUrl += `&difficulty=${difficulty}`;
}
if (type && type !== 'any') {
apiUrl += `&type=${type}`;
}
apiUrl += '&encode=url3986'; // URL encoding to handle special characters
try {
console.log('Fetching from API:', apiUrl);
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
const data = await response.json();
if (data.response_code !== 0) {
// Response codes: 0 = Success, 1 = No Results, 2 = Invalid Parameter, 3 = Token Not Found, 4 = Token Empty
if (data.response_code === 1) {
throw new Error('No questions available for this combination. Please try different settings.');
} else {
throw new Error(`API Error: Response code ${data.response_code}`);
}
}
// Transform API questions to our format
const transformedQuestions = data.results.map((q, index) => {
const isMultipleChoice = q.type === 'multiple';
const options = isMultipleChoice
? [...q.incorrect_answers, q.correct_answer].sort(() => Math.random() - 0.5)
: ['True', 'False'];
// Decode URL-encoded strings
const question = decodeURIComponent(q.question);
const correctAnswer = decodeURIComponent(q.correct_answer);
const decodedOptions = options.map(opt => decodeURIComponent(opt));
const category = decodeURIComponent(q.category);
// Calculate points based on difficulty
let points = 10;
if (q.difficulty === 'medium') points = 15;
else if (q.difficulty === 'hard') points = 20;
return {
id: `api_${Date.now()}_${index}`,
topic: category,
difficulty: q.difficulty,
type: isMultipleChoice ? 'multiple_choice' : 'true_false',
question: question,
options: decodedOptions,
correctAnswer: correctAnswer,
explanation: `This is a ${q.difficulty} level question from ${category}.`,
points: points,
timeLimit: isMultipleChoice ? 30 : 20
};
});
// Cache the results
apiQuestionsCache[cacheKey] = {
questions: transformedQuestions,
timestamp: Date.now()
};
return transformedQuestions;
} catch (error) {
console.error('API Error:', error);
throw error;
}
}
// Fetch questions with fallback to local bank
async function getQuestions(count, categoryId, difficulty, type) {
try {
isLoadingQuestions = true;
const apiQuestions = await fetchQuestionsFromAPI(count, categoryId, difficulty, type);
isLoadingQuestions = false;
// If we got fewer questions than requested, pad with local questions
if (apiQuestions.length < count) {
console.log(`API returned ${apiQuestions.length} questions, padding with local questions`);
const localQuestions = getFilteredLocalQuestions(count - apiQuestions.length);
return [...apiQuestions, ...localQuestions];
}
return apiQuestions;
} catch (error) {
console.error('Failed to fetch from API, falling back to local questions:', error);
isLoadingQuestions = false;
// Show error notification
showNotification(
'Using Local Questions ℹ️',
'Could not fetch from API. Using local question bank instead.',
'warning'
);
// Fallback to local questions
return getFilteredLocalQuestions(count);
}
}
// Get filtered questions from local bank (fallback)
function getFilteredLocalQuestions(count) {
let filtered = questions;
// Filter by topic if not "Mixed"
if (selectedTopic && selectedTopic !== "Mixed 🎲") {
const topicName = selectedTopic.split(' ')[0]; // Remove emoji
filtered = filtered.filter(q => q.topic.startsWith(topicName));
}
// Filter by difficulty if not "Mixed"
if (selectedDifficulty && selectedDifficulty !== "Mixed 🎯") {
const difficultyName = selectedDifficulty.split(' ')[0].toLowerCase(); // Remove emoji
filtered = filtered.filter(q => q.difficulty === difficultyName);
}
// Filter by type if specified
if (selectedQuestionType && selectedQuestionType !== 'any') {
const typeMap = {
'multiple': 'multiple_choice',
'boolean': 'true_false'
};
filtered = filtered.filter(q => q.type === typeMap[selectedQuestionType]);
}
// Shuffle and return requested count
const shuffled = shuffleArray(filtered);
return shuffled.slice(0, Math.min(count, shuffled.length));
}
// ==================== END API INTEGRATION ====================
// Render the current state
function renderState() {
// Clear previous content
contentCard.innerHTML = '';
footerNav.innerHTML = '';
// Add fade-in animation
contentCard.classList.remove('fade-in');
void contentCard.offsetWidth; // Trigger reflow
contentCard.classList.add('fade-in');
// Show/hide timer based on state
const timerContainer = document.querySelector('.timer-container');
if (timerContainer) {
if (currentState === AppState.QUIZ) {
timerContainer.style.display = 'block';
} else {
timerContainer.style.display = 'none';
}
}
// Render based on current state
switch(currentState) {
case AppState.WELCOME:
renderWelcomeState();
break;
case AppState.QUIZ:
renderQuizState();
break;
case AppState.RESULTS:
renderResultsState();
break;
case AppState.REVIEW:
renderReviewState();
break;
case AppState.HISTORY:
renderHistoryState();
break;
}
// Update user progress
updateUserProgress();
}
// Render welcome state
function renderWelcomeState() {
contentCard.classList.add('welcome-state');
contentCard.innerHTML = `
<div class="welcome-header">
<div class="welcome-icon">
<i class="fas fa-graduation-cap"></i>
</div>
<h1 class="card-title">Welcome to Knowledge Quest! 🚀</h1>
</div>
<p class="welcome-text">
🎯 <strong>Test your knowledge</strong> across various topics and track your learning progress!<br>
📈 <strong>Earn XP and level up</strong> as you answer questions correctly.<br>
🏆 <strong>Unlock achievements</strong> and build your knowledge streak!<br>
🔥 <strong>Compete with yourself</strong> and become a knowledge master!
</p>
<h3 class="card-title"><i class="fas fa-hashtag"></i> Number of Questions 🔢</h3>
<div class="question-count-selection" id="question-count-selection">
${questionCounts.map(count => `
<div class="count-btn ${selectedQuestionCount === count ? 'selected' : ''}" data-count="${count}">
<div class="count-number">${count}</div>
<div class="count-label">Questions</div>
</div>
`).join('')}
</div>
<h3 class="card-title"><i class="fas fa-book-open"></i> Select a Topic 📚</h3>
<div class="topic-selection" id="topic-selection">
${topics.map(topic => `
<div class="topic-btn ${selectedTopic === topic.name ? 'selected' : ''}" data-topic="${topic.name}">
<div class="topic-icon">${topic.icon}</div>
<div>${topic.name}</div>
</div>
`).join('')}
</div>
<h3 class="card-title"><i class="fas fa-chart-bar"></i> Select Difficulty 🎯</h3>
<div class="difficulty-selection" id="difficulty-selection">
${difficulties.map(difficulty => `
<div class="difficulty-btn ${selectedDifficulty === difficulty.name ? 'selected' : ''}" data-difficulty="${difficulty.name}">
<div class="difficulty-icon">${difficulty.icon}</div>
<div>${difficulty.name}</div>
</div>
`).join('')}
</div>
<h3 class="card-title"><i class="fas fa-clipboard-question"></i> Question Type 📋</h3>
<div class="type-selection" id="type-selection">
${questionTypes.map(type => `
<div class="type-btn ${selectedQuestionType === type.value ? 'selected' : ''}" data-type="${type.value}">
<div>${type.name}</div>
</div>
`).join('')}
</div>
`;
// Add event listeners for question count selection
document.querySelectorAll('.count-btn').forEach(btn => {
btn.addEventListener('click', function() {
selectedQuestionCount = parseInt(this.dataset.count);
document.querySelectorAll('.count-btn').forEach(b => b.classList.remove('selected'));
this.classList.add('selected');
this.classList.add('bounce');
setTimeout(() => this.classList.remove('bounce'), 1000);
});
});
// Add event listeners for topic selection
document.querySelectorAll('.topic-btn').forEach(btn => {
btn.addEventListener('click', function() {
selectedTopic = this.dataset.topic;
document.querySelectorAll('.topic-btn').forEach(b => b.classList.remove('selected'));
this.classList.add('selected');
this.classList.add('bounce');
setTimeout(() => this.classList.remove('bounce'), 1000);
});
});
// Add event listeners for difficulty selection
document.querySelectorAll('.difficulty-btn').forEach(btn => {
btn.addEventListener('click', function() {
selectedDifficulty = this.dataset.difficulty;
document.querySelectorAll('.difficulty-btn').forEach(b => b.classList.remove('selected'));
this.classList.add('selected');
this.classList.add('bounce');
setTimeout(() => this.classList.remove('bounce'), 1000);
});
});
// Add event listeners for question type selection
document.querySelectorAll('.type-btn').forEach(btn => {
btn.addEventListener('click', function() {
selectedQuestionType = this.dataset.type;
document.querySelectorAll('.type-btn').forEach(b => b.classList.remove('selected'));
this.classList.add('selected');
this.classList.add('bounce');
setTimeout(() => this.classList.remove('bounce'), 1000);
});
});
// Footer navigation for welcome state
footerNav.innerHTML = `
<button class="btn btn-secondary" id="view-history-btn">
<i class="fas fa-history"></i> View History 📜
</button>
<button class="btn btn-primary" id="start-quiz-btn">
<i class="fas fa-play-circle"></i> Start Quiz 🚀
</button>
`;
document.getElementById('start-quiz-btn').addEventListener('click', startQuiz);
document.getElementById('view-history-btn').addEventListener('click', () => {
currentState = AppState.HISTORY;
renderState();
});
}
// Start the quiz
async function startQuiz() {
if (!selectedTopic || !selectedDifficulty) {
showNotification('Selection Required ⚠️', 'Please select both a topic and difficulty level.', 'warning');
return;
}
// Show loading state
const startBtn = document.getElementById('start-quiz-btn');
const originalBtnText = startBtn.innerHTML;
startBtn.disabled = true;
startBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Loading Questions...';
try {
// Get category ID from selected topic
const selectedTopicObj = topics.find(t => t.name === selectedTopic);
const categoryId = selectedTopicObj?.apiId;
// Get difficulty value
const selectedDiffObj = difficulties.find(d => d.name === selectedDifficulty);
const difficultyValue = selectedDiffObj?.apiValue;
// Fetch questions from API (with fallback to local)
currentQuizQuestions = await getQuestions(
selectedQuestionCount,
categoryId,
difficultyValue,
selectedQuestionType
);
if (currentQuizQuestions.length === 0) {
showNotification('No Questions Found ⚠️', 'Please try different topic/difficulty selections.', 'warning');
startBtn.disabled = false;
startBtn.innerHTML = originalBtnText;
return;
}
// Validate if we got fewer questions than requested
if (currentQuizQuestions.length < selectedQuestionCount) {
showNotification(