-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
384 lines (327 loc) · 9.96 KB
/
Copy pathscript.js
File metadata and controls
384 lines (327 loc) · 9.96 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
// set to true if opening HTML file directly without a web server
const HOSTED_LOCALLY = true;
// questions data used when HOSTED_LOCALLY is true
EMBEDDED_QUESTIONS = [
{
"id": 1,
"question": "What's nine plus ten?",
"answer": "21"
},
{
"id": 2,
"question": "Amogus is..?",
"answer": "Sus"
},
{
"id": 3,
"question": "What is Obama's last name?",
"answer": "Obambam"
}
];
// key for storing custom questions in sessionStorage
const STORAGE_KEY = 'customQuestions';
let questionsData = [];
// load custom questions from sessionStorage
function loadCustomQuestions()
{
const stored = sessionStorage.getItem(STORAGE_KEY);
return stored ? JSON.parse(stored) : [];
}
let userMatches = {}; // user's matches: { questionId: answerId }
let selectedQuestion = null;
let selectedAnswer = null;
let isSubmitted = false;
const questionsContainer = document.getElementById('questions');
const answersContainer = document.getElementById('answers');
const submitBtn = document.getElementById('submit-btn');
const resetBtn = document.getElementById('reset-btn');
const resultMessage = document.getElementById('result-message');
const connectionsSvg = document.getElementById('connections-svg');
async function init()
{
try
{
if (HOSTED_LOCALLY)
{
// use embedded questions data for local testing
questionsData = EMBEDDED_QUESTIONS;
}
else
{
// fetch questions from JSON file (requires web server)
const response = await fetch('questions.json');
questionsData = await response.json();
}
// merge custom questions from sessionStorage
const customQuestions = loadCustomQuestions();
questionsData = [...questionsData, ...customQuestions];
setupQuiz();
}
catch (error)
{
console.error('Error loading questions:', error);
resultMessage.textContent = 'Error loading quiz data!';
resultMessage.style.background = 'rgba(245, 101, 101, 0.3)';
}
}
// setup quiz
function setupQuiz()
{
// clear containers
questionsContainer.innerHTML = '';
answersContainer.innerHTML = '';
connectionsSvg.innerHTML = '';
userMatches = {};
selectedQuestion = null;
selectedAnswer = null;
isSubmitted = false;
resultMessage.textContent = '';
submitBtn.style.display = 'inline-block';
resetBtn.style.display = 'none';
submitBtn.disabled = false;
const shuffledQuestions = shuffleArray([...questionsData]);
const shuffledAnswers = shuffleArray([...questionsData]);
// render questions
shuffledQuestions.forEach((item, index) =>
{
const questionBox = createItemBox(item.id, item.question, 'question', index + 1);
questionsContainer.appendChild(questionBox);
});
// render answers
shuffledAnswers.forEach((item, index) =>
{
const answerBox = createItemBox(item.id, item.answer, 'answer', index + 1);
answersContainer.appendChild(answerBox);
});
}
// create a question or answer box
function createItemBox(id, text, type, displayNumber)
{
const box = document.createElement('div');
box.className = 'item';
box.dataset.id = id;
box.dataset.type = type;
box.innerHTML = `<span class="item-number">${displayNumber}</span>${text}`;
box.addEventListener('click', () => handleItemClick(box, id, type));
return box;
}
// handle clicking on question or answer
function handleItemClick(element, id, type)
{
if (isSubmitted) return;
if (type === 'question')
{
// if clicking the same question, deselect it
if (selectedQuestion === id)
{
element.classList.remove('selected');
selectedQuestion = null;
return;
}
// clear previous question selection
document.querySelectorAll('.item[data-type="question"]').forEach(q =>
{
if (q.dataset.id !== id.toString()) {
q.classList.remove('selected');
}
});
// select this question
element.classList.add('selected');
selectedQuestion = id;
// check if we should create a match
if (selectedAnswer !== null)
{
createMatch(selectedQuestion, selectedAnswer);
}
}
else if (type === 'answer')
{
// if clicking the same answer, deselect it
if (selectedAnswer === id)
{
element.classList.remove('selected');
selectedAnswer = null;
return;
}
// clear previous answer selection
document.querySelectorAll('.item[data-type="answer"]').forEach(a =>
{
if (a.dataset.id !== id.toString()) {
a.classList.remove('selected');
}
});
// select this answer
element.classList.add('selected');
selectedAnswer = id;
// sheck if we should create a match
if (selectedQuestion !== null)
{
createMatch(selectedQuestion, selectedAnswer);
}
}
}
// create a match between a question and answer
function createMatch(questionId, answerId)
{
// remove previous match if question was already matched
if (userMatches[questionId])
{
const oldAnswerElement = document.querySelector(`.item[data-type="answer"][data-id="${userMatches[questionId]}"]`);
if (oldAnswerElement)
{
oldAnswerElement.classList.remove('connected');
}
}
// store the new match
userMatches[questionId] = answerId;
// update visual state
const questionElement = document.querySelector(`.item[data-type="question"][data-id="${questionId}"]`);
const answerElement = document.querySelector(`.item[data-type="answer"][data-id="${answerId}"]`);
questionElement.classList.remove('selected');
questionElement.classList.add('connected');
answerElement.classList.remove('selected');
answerElement.classList.add('connected');
// draw connection line
drawConnection(questionElement, answerElement);
// reset selections
selectedQuestion = null;
selectedAnswer = null;
// enable submit button when all questions are matched
if (Object.keys(userMatches).length === questionsData.length)
{
submitBtn.disabled = false;
}
}
// draws a visual connection line between matched items
function drawConnection(questionElement, answerElement)
{
const qRect = questionElement.getBoundingClientRect();
const aRect = answerElement.getBoundingClientRect();
const x1 = qRect.right;
const y1 = qRect.top + qRect.height / 2;
const x2 = aRect.left;
const y2 = aRect.top + aRect.height / 2;
// create SVG line
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
line.setAttribute('class', 'connection-line');
line.dataset.questionId = questionElement.dataset.id;
line.dataset.answerId = answerElement.dataset.id;
connectionsSvg.appendChild(line);
}
// redraw all connection lines (after scrolling or resizing)
function redrawConnections()
{
connectionsSvg.innerHTML = '';
for (const [questionId, answerId] of Object.entries(userMatches))
{
const questionElement = document.querySelector(`.item[data-type="question"][data-id="${questionId}"]`);
const answerElement = document.querySelector(`.item[data-type="answer"][data-id="${answerId}"]`);
if (questionElement && answerElement)
{
drawConnection(questionElement, answerElement);
}
}
}
// submit answers and align answers to questions
function submitAnswers()
{
if (Object.keys(userMatches).length !== questionsData.length)
{
resultMessage.textContent = 'Please match all questions before submitting!';
resultMessage.style.background = 'rgba(245, 101, 101, 0.3)';
return;
}
isSubmitted = true;
submitBtn.disabled = true;
connectionsSvg.innerHTML = ''; // clear connection lines
// calculate score
let correctCount = 0;
questionsData.forEach(item =>
{
if (userMatches[item.id] === item.id)
{
correctCount++;
}
});
// display result
resultMessage.textContent = `You got ${correctCount} out of ${questionsData.length} correct!`;
if (correctCount === questionsData.length)
{
resultMessage.style.background = 'rgba(72, 187, 120, 0.3)';
}
else
{
resultMessage.style.background = 'rgba(237, 137, 54, 0.3)';
}
// align the answers to match questions
alignAnswersToQuestions();
// show reset button
resetBtn.style.display = 'inline-block';
submitBtn.style.display = 'none';
}
// align answer boxes to match their corresponding questions
function alignAnswersToQuestions()
{
const questionElements = Array.from(questionsContainer.querySelectorAll('.item'));
const answerElements = Array.from(answersContainer.querySelectorAll('.item'));
// create map of answer elements by ID for quick lookup
const answerMap = {};
answerElements.forEach(el =>
{
answerMap[el.dataset.id] = el;
});
// reorder answers to match questions and add visual feedback
questionElements.forEach((questionEl, index) =>
{
const questionId = parseInt(questionEl.dataset.id);
const correctAnswer = questionsData.find(q => q.id === questionId);
const correctAnswerId = correctAnswer.id;
// find the correct answer element
const correctAnswerEl = answerMap[correctAnswerId];
// check if user's match was correct
const isCorrect = userMatches[questionId] === correctAnswerId;
// add appropriate class
questionEl.classList.remove('connected');
questionEl.classList.add('aligned');
if (isCorrect)
{
questionEl.classList.add('correct');
correctAnswerEl.classList.add('correct');
}
else
{
questionEl.classList.add('incorrect');
// mark the incorrectly matched answer
const userAnswerEl = answerMap[userMatches[questionId]];
if (userAnswerEl)
{
userAnswerEl.classList.add('incorrect');
}
}
// reorder the answer element to align with question
correctAnswerEl.classList.remove('connected');
correctAnswerEl.classList.add('aligned');
answersContainer.appendChild(correctAnswerEl);
});
}
// shuffle array using 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;
}
// event listeners
submitBtn.addEventListener('click', submitAnswers);
resetBtn.addEventListener('click', setupQuiz);
window.addEventListener('resize', redrawConnections);
window.addEventListener('scroll', redrawConnections);
init();