-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
250 lines (250 loc) · 10.2 KB
/
index.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
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
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const quiz_json_1 = __importDefault(require("./quiz.json"));
//DOM
const startButton = document.getElementById('start-button');
const questionContainerElement = document.getElementById('question-container');
const questionElement = document.getElementById('question');
const answerButtonsElement = document.getElementById('answer-buttons');
const nextButton = document.getElementById('next-button');
const previousButton = document.getElementById('previous-button');
const finishButton = document.getElementById('finish-button');
const resultContainer = document.getElementById('result-container');
const introductionElement = document.getElementById('introduction');
const quizTimerElement = document.getElementById('quiz-timer');
const questionTimerElement = document.getElementById('question-timer');
const totalQuestionsElement = document.getElementById('total-questions');
const answeredQuestionsElement = document.getElementById('answered-questions');
const remainingQuestionsElement = document.getElementById('remaining-questions');
let currentQuestionIndex = 0;
let answers = {};
let questions = shuffleQuestions(quiz_json_1.default);
let quizStartTime;
let questionStartTime;
let quizTimer;
let questionTimer;
let questionTimeSpent = {};
startButton.addEventListener('click', startGame);
nextButton.addEventListener('click', () => {
selectAnswer();
showNextQuestion();
});
previousButton.addEventListener('click', showPreviousQuestion);
finishButton.addEventListener('click', finishQuiz);
function resetQuiz() {
console.log("Resetowanie quizu");
questionContainerElement.style.display = 'none';
resultContainer.style.display = 'none';
introductionElement.style.display = 'block';
startButton.style.display = 'block';
const cancelButton = document.getElementById('cancel-button');
if (cancelButton) {
cancelButton.remove();
}
currentQuestionIndex = 0;
answers = {};
questions = shuffleQuestions(quiz_json_1.default);
localStorage.removeItem('quizResults');
}
function startGame() {
loadResultsFromLocalStorage();
startButton.style.display = 'none';
questionContainerElement.style.display = 'block';
let cancelButton = document.getElementById('cancel-button');
if (!cancelButton) {
//anuluj
cancelButton = document.createElement("button");
cancelButton.id = 'cancel-button';
cancelButton.textContent = "Anuluj i wróć";
questionContainerElement.appendChild(cancelButton);
}
cancelButton.addEventListener('click', () => {
resetQuiz();
});
quizStartTime = new Date();
questionStartTime = new Date();
startQuizTimer();
startQuestionTimer();
showQuestion(questions[currentQuestionIndex]);
updateQuestionStatus();
}
function updateQuestionStatus() {
const totalQuestions = questions.length;
const answeredQuestions = Object.keys(answers).length;
const remainingQuestions = totalQuestions - answeredQuestions;
totalQuestionsElement.textContent = `Liczba wszystkich pytań: ${totalQuestions}`;
answeredQuestionsElement.textContent = `Liczba pytań, na które odpowiedziano: ${answeredQuestions}`;
remainingQuestionsElement.textContent = `Liczba pytań, na które nie odpowiedziano: ${remainingQuestions}`;
}
function startQuizTimer() {
quizTimer = setInterval(() => {
const now = new Date();
const elapsed = now.getTime() - quizStartTime.getTime();
quizTimerElement.textContent = `Czas od rozpoczęcia quizu: ${formatTime(elapsed)}`;
}, 1000);
}
function startQuestionTimer() {
questionTimer = setInterval(() => {
const now = new Date();
const elapsed = now.getTime() - questionStartTime.getTime();
questionTimerElement.textContent = `Czas od rozpoczęcia pytania: ${formatTime(elapsed)}`;
}, 1000);
}
function formatTime(milliseconds) {
const seconds = Math.floor(milliseconds / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
}
function resetQuestionTimer() {
clearInterval(questionTimer);
questionStartTime = new Date();
startQuestionTimer();
}
function shuffleQuestions(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]];
}
return array;
}
function showQuestion(question) {
resetQuestionTimer();
const questionNumber = currentQuestionIndex + 1;
questionElement.innerHTML = `<strong>${questionNumber}. </strong> ${question.question}`;
answerButtonsElement.innerHTML = '';
question.options.forEach((option, index) => {
const container = document.createElement('div');
const radioInput = document.createElement('input');
radioInput.type = 'radio';
radioInput.id = 'answer_' + index;
radioInput.name = 'answer';
radioInput.value = option;
if (answers[currentQuestionIndex]) {
radioInput.disabled = true; //blokada odpowiedzi
}
if (answers[currentQuestionIndex] === option) {
radioInput.checked = true;
}
const label = document.createElement('label');
label.htmlFor = 'answer_' + index;
label.innerText = option;
container.appendChild(radioInput);
container.appendChild(label);
answerButtonsElement.appendChild(container);
});
updateNavigation();
}
function saveResultsToLocalStorage(score, incorrectAnswers, totalTimeElapsed, passScore, passed) {
const results = {
score,
incorrectAnswers,
questions: questions.map((question, index) => {
return {
question: question.question,
userAnswer: answers[index],
correctAnswer: question.answer,
questionScore: questions[index].answer === answers[index] ? 1 : 0,
timeSpent: questionTimeSpent[index]
};
}),
totalTimeElapsed,
passScore,
passed
};
localStorage.setItem('quizResults', JSON.stringify(results));
}
function loadResultsFromLocalStorage() {
const storedResults = localStorage.getItem('quizResults');
if (storedResults) {
const results = JSON.parse(storedResults);
console.log(results);
}
}
function selectAnswer() {
const selectedOption = answerButtonsElement.querySelector('input[name="answer"]:checked');
if (selectedOption) {
answers[currentQuestionIndex] = selectedOption.value;
questionTimeSpent[currentQuestionIndex] = new Date().getTime() - questionStartTime.getTime();
}
updateQuestionStatus();
}
function showNextQuestion() {
if (currentQuestionIndex < questions.length - 1) {
currentQuestionIndex++;
showQuestion(questions[currentQuestionIndex]);
}
}
function showPreviousQuestion() {
if (currentQuestionIndex > 0) {
currentQuestionIndex--;
showQuestion(questions[currentQuestionIndex]);
}
}
function updateNavigation() {
previousButton.style.display = currentQuestionIndex > 0 ? 'block' : 'none';
nextButton.style.display = currentQuestionIndex < questions.length - 1 ? 'block' : 'none';
finishButton.style.display = currentQuestionIndex === questions.length - 1 ? 'block' : 'none';
}
function finishQuiz() {
clearInterval(quizTimer);
clearInterval(questionTimer);
selectAnswer();
if (Object.keys(answers).length < questions.length) {
alert("Nie odpowiedziałeś na wszystkie pytania. Proszę odpowiedzieć na brakujące pytania przed zakończeniem quizu.");
return;
}
questionContainerElement.style.display = 'none';
resultContainer.style.display = 'block';
const totalTimeElapsed = new Date().getTime() - quizStartTime.getTime();
const formattedTotalTime = formatTime(totalTimeElapsed);
const score = questions.filter((_, index) => questions[index].answer === answers[index]).length;
const incorrectAnswers = questions.length - score;
const passScore = Math.ceil(questions.length * 0.5);
const passed = score >= passScore;
resultContainer.innerHTML = `
<h1>Wynik Quizu</h1>
<p>Maksymalna liczba punktów: ${questions.length}</p>
<p>Uzyskana liczba punktów: ${score}</p>
<p>Błędne odpowiedzi: ${incorrectAnswers}</p>
<p>Liczba punktów potrzebnych do zaliczenia: ${passScore} (${Math.ceil(50)}%)</p>
<p>Czy zaliczono: ${passed}</p>
<p>Całkowity czas spędzony na teście: ${formattedTotalTime}</p>
<h2>Szczegółowe Wyniki</h2>`;
const resultsTable = document.createElement('table');
resultsTable.innerHTML = `
<tr>
<th>Numer pytania</th>
<th>Treść pytania</th>
<th>Moja odpowiedź</th>
<th>Poprawna odpowiedź</th>
<th>Uzyskane punkty</th>
<th>Czas na pytaniu</th>
</tr>`;
questions.forEach((question, index) => {
const questionScore = questions[index].answer === answers[index] ? 1 : 0;
const timeSpent = formatTime(questionTimeSpent[index] || 0);
const userAnswer = answers[index] || "Nie udzielono odpowiedzi";
resultsTable.innerHTML += `
<tr>
<td>${index + 1}</td>
<td>${question.question}</td>
<td>${userAnswer}</td>
<td>${question.answer}</td>
<td>${questionScore}</td>
<td>${timeSpent}</td>
</tr>`;
});
resultContainer.appendChild(resultsTable);
//improwizowany separator
const breakLine = document.createElement("br");
resultContainer.appendChild(breakLine);
const backButtonDynamic = document.createElement("button");
backButtonDynamic.textContent = "Wróć do strony pierwszej";
backButtonDynamic.addEventListener('click', resetQuiz);
resultContainer.appendChild(backButtonDynamic);
saveResultsToLocalStorage(score, incorrectAnswers, totalTimeElapsed, passScore, passed);
}