-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.js
211 lines (179 loc) · 5.11 KB
/
logic.js
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
/**
* @fileOverview Quiz Application
* @description This file contains the JavaScript code for a quiz application.
* It includes functions to handle the quiz timer, render questions, check answers,
* manage scores, and store high scores in local storage.
* The application also allows users to start the quiz, submit their scores, and view high scores.
*
* @version 1.0.0
* @license MIT
*/
/**
* Description - Timer used for the quiz.
* @type {number}
*/
let timer;
/**
* Description - Index of the current question in the quiz.
* @type {number}
*/
let questionIndex = 0;
/**
* Description - Score for the user.
* @type {number}
*/
let score = 0;
/**
* Description - Total time available for the quiz. Is calculated based
* on the number of questions and time per question.
* @type {number}
*/
let time = quizQuestionsData.length * timePerQuestion;
/**
* Description - Starts timer for quiz.
* @function
*/
function startTimer() {
timer = setInterval(() => {
time--;
timeEl.textContent = time;
if (time <= 0) {
endQuiz();
}
}, 1000);
}
/**
* Description - Starts quiz by showing questions, and starting the timer.
* @function
*/
function startQuiz() {
startScrnEl.setAttribute("class", "hide");
questionsEl.removeAttribute("class");
startTimer();
renderQuestion();
}
/**
* Description - Take given array and returned it shuffled.
* @function
* @param {Array} array - The array to be shuffled.
* @returns {Array} - The shuffled array.
*/
function shuffleArr(array) {
let arr = [...array];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
/**
* Description - Update UI to render current question on the screen.
* @function
*/
function renderQuestion() {
const data = quizQuestionsData[questionIndex];
let currentQuestions = [data.correctAnswer];
currentQuestions.push(...data.incorrectAnswers);
currentQuestions = shuffleArr(currentQuestions);
questionTitleEl.textContent = data.questionTitle;
for (let i = 0; i < currentQuestions.length; i++) {
const btnText = i + 1 + ". " + currentQuestions[i];
const choiceBtn = document.createElement("button");
choiceBtn.textContent = btnText;
choiceBtn.addEventListener("click", checkAnswer);
choicesEl.appendChild(choiceBtn);
}
}
/**
* Description - Renders the next quiz question (recursive to renderQuestion()
* function) and validate if the quiz needs to ne ended.
* @function
*/
function renderNextQuestion() {
if (questionIndex < quizQuestionsData.length) {
choicesEl.innerHTML = null;
renderQuestion();
} else {
endQuiz();
}
}
/**
* Description - Update UI to show feedback on the user's answer.
* @function
* @param {String} message - The feedback message to be displayed.
*/
function renderFeedback(message) {
feedbackEl.classList.remove("hide");
feedbackEl.textContent = message;
setTimeout(() => {
feedbackEl.classList.add("hide");
}, 1000);
}
/**
* Description - Checks the user's answer, updates the score and time,
* and renders feedback.
* @function
* @param {Event} event - The event object containing the user's selection
*/
function checkAnswer(event) {
const userSelection = event.target.textContent.substr(3);
const correctAnswer = quizQuestionsData[questionIndex].correctAnswer;
if (userSelection === correctAnswer) {
time = time - timePerQuestion;
score = score + quizQuestionsData[questionIndex].points;
correctSound.play();
renderFeedback(correctMsg);
} else {
time = time - timePerQuestion;
incorrectSound.play();
renderFeedback(wrongMsg);
}
questionIndex++;
renderNextQuestion();
}
/**
* Description - Ends the quiz, clears the timer, and displays the end
* screen with the final score.
* @function
*/
function endQuiz() {
clearInterval(timer);
questionsEl.setAttribute("class", "hide");
endScrnEl.removeAttribute("class");
finalScoreEl.textContent = score;
}
/**
* Description - Saves the user's high score in the local storage.
* @function
* @param {Object} userDetails - The details of the user, including user name
* and user score.
*/
function saveHighScoreList(userDetails) {
let highScoresList = JSON.parse(localStorage.getItem(highScoresKey)) || [];
if (!Array.isArray(highScoresList)) {
highScoresList = [];
}
highScoresList.push(userDetails);
highScoresList.sort((a, b) => b.score - a.score);
localStorage.setItem(highScoresKey, JSON.stringify(highScoresList));
}
/**
* Description - Submits the user's score, including initials if provided
* (if not set initials to N/A). Redirects to the highscores page (to avoid
* submitting user score more than once).
* @function
*/
function submitScore() {
const userInitials = initialsInput.value;
let userDetails = {
name: "N/A",
score: 0,
};
if (userInitials !== "") userDetails.name = userInitials;
userDetails.score = score;
saveHighScoreList(userDetails);
// Redirect to the highscores page
window.location.href = "highscores.html";
}
startBtn.onclick = startQuiz;
submitScoreBtn.addEventListener("click", submitScore);