Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
498 lines (426 loc) · 18.1 KB
/
Copy pathscript.js
File metadata and controls
498 lines (426 loc) · 18.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
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
class TriviaGame {
constructor() {
this.currentScreen = 'topic-screen';
this.questions = [];
this.currentQuestionIndex = 0;
this.scores = { player1: 0, player2: 0 };
this.playerSelections = { player1: null, player2: null };
this.timer = null;
this.timeLeft = 15;
this.gameInProgress = false;
this.questionAnswered = false;
this.initializeEventListeners();
this.bindKeyboardEvents();
}
initializeEventListeners() {
// Start game button
document.getElementById('start-game-btn').addEventListener('click', () => {
const topic = document.getElementById('topic-input').value.trim();
if (topic) {
this.startGame(topic);
} else {
alert('Please enter a topic!');
}
});
// Play again button
document.getElementById('play-again-btn').addEventListener('click', () => {
this.resetGame();
});
// Enter key on topic input
document.getElementById('topic-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
document.getElementById('start-game-btn').click();
}
});
}
bindKeyboardEvents() {
document.addEventListener('keydown', (e) => {
if (!this.gameInProgress || this.questionAnswered) return;
const key = e.key.toLowerCase();
let selectedIndex = null;
let player = null;
// Player 1 controls (WASD)
switch(key) {
case 'w': selectedIndex = 0; player = 'player1'; break;
case 'a': selectedIndex = 1; player = 'player1'; break;
case 's': selectedIndex = 2; player = 'player1'; break;
case 'd': selectedIndex = 3; player = 'player1'; break;
}
// Player 2 controls (Arrow keys)
switch(key) {
case 'arrowup': selectedIndex = 0; player = 'player2'; break;
case 'arrowleft': selectedIndex = 1; player = 'player2'; break;
case 'arrowdown': selectedIndex = 2; player = 'player2'; break;
case 'arrowright': selectedIndex = 3; player = 'player2'; break;
}
if (selectedIndex !== null && player) {
e.preventDefault();
this.selectAnswer(player, selectedIndex);
}
});
}
async startGame(topic) {
this.showScreen('loading-screen');
document.getElementById('loading-topic').textContent = topic;
try {
await this.generateQuestions(topic);
this.showScreen('game-screen');
this.gameInProgress = true;
this.currentQuestionIndex = 0;
this.scores = { player1: 0, player2: 0 };
this.updateScoreDisplay();
this.showQuestion();
} catch (error) {
console.error('Error generating questions:', error);
alert('Sorry, there was an error generating questions. Please try again.');
this.showScreen('topic-screen');
}
}
async generateQuestions(topic) {
try {
// Try to fetch from API first
const response = await fetch('/api/generate-questions', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ topic })
});
if (response.ok) {
const data = await response.json();
this.questions = data.questions;
// Update loading message based on source
const loadingTopic = document.getElementById('loading-topic');
if (data.source === 'openai') {
loadingTopic.innerHTML = `<strong>${topic}</strong> trivia with AI-generated questions! 🤖`;
} else {
loadingTopic.innerHTML = `<strong>${topic}</strong> trivia with curated questions! 📝`;
}
if (data.warning) {
console.warn('API Warning:', data.warning);
}
} else {
throw new Error('API request failed');
}
} catch (error) {
console.warn('API unavailable, using fallback questions:', error);
// Fallback to local questions if API is unavailable
this.questions = await this.getFallbackQuestions(topic);
}
}
async getFallbackQuestions(topic) {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1500));
// Fallback questions for when API is unavailable
const fallbackQuestions = {
science: [
{
question: "What is the chemical symbol for gold?",
answers: ["Au", "Ag", "Go", "Gd"],
correct: 0
},
{
question: "How many bones are in the adult human body?",
answers: ["206", "208", "204", "210"],
correct: 0
},
{
question: "What planet is known as the Red Planet?",
answers: ["Mars", "Venus", "Jupiter", "Saturn"],
correct: 0
},
{
question: "What gas makes up about 78% of Earth's atmosphere?",
answers: ["Nitrogen", "Oxygen", "Carbon Dioxide", "Argon"],
correct: 0
},
{
question: "What is the speed of light in a vacuum?",
answers: ["299,792,458 m/s", "300,000,000 m/s", "299,000,000 m/s", "298,792,458 m/s"],
correct: 0
}
],
history: [
{
question: "In which year did World War II end?",
answers: ["1945", "1944", "1946", "1943"],
correct: 0
},
{
question: "Who was the first person to walk on the moon?",
answers: ["Neil Armstrong", "Buzz Aldrin", "John Glenn", "Alan Shepard"],
correct: 0
},
{
question: "Which ancient wonder of the world was located in Alexandria?",
answers: ["Lighthouse of Alexandria", "Hanging Gardens", "Colossus of Rhodes", "Temple of Artemis"],
correct: 0
},
{
question: "What year did the Berlin Wall fall?",
answers: ["1989", "1987", "1991", "1985"],
correct: 0
},
{
question: "Who was the first President of the United States?",
answers: ["George Washington", "Thomas Jefferson", "John Adams", "Benjamin Franklin"],
correct: 0
}
],
movies: [
{
question: "Who directed the movie 'Jaws'?",
answers: ["Steven Spielberg", "George Lucas", "Martin Scorsese", "Francis Ford Coppola"],
correct: 0
},
{
question: "Which movie won the Academy Award for Best Picture in 1994?",
answers: ["Forrest Gump", "Pulp Fiction", "The Lion King", "The Shawshank Redemption"],
correct: 0
},
{
question: "What is the highest-grossing film of all time?",
answers: ["Avatar", "Avengers: Endgame", "Titanic", "Star Wars: The Force Awakens"],
correct: 0
},
{
question: "Who played the character of Jack Sparrow?",
answers: ["Johnny Depp", "Orlando Bloom", "Geoffrey Rush", "Keira Knightley"],
correct: 0
},
{
question: "In which year was the first Star Wars movie released?",
answers: ["1977", "1975", "1979", "1980"],
correct: 0
}
]
};
// Try to match topic to existing categories
const topicKey = topic.toLowerCase();
if (fallbackQuestions[topicKey]) {
return fallbackQuestions[topicKey];
}
// Generate generic questions for any topic
return this.generateGenericQuestions(topic);
}
generateGenericQuestions(topic) {
return [
{
question: `What is a key characteristic of ${topic}?`,
answers: ["Complexity", "Simplicity", "Rarity", "Abundance"],
correct: 0
},
{
question: `When did ${topic} first become popular?`,
answers: ["20th century", "19th century", "18th century", "21st century"],
correct: 0
},
{
question: `Which field is most associated with ${topic}?`,
answers: ["General knowledge", "Specialized study", "Entertainment", "Sports"],
correct: 0
},
{
question: `What makes ${topic} interesting to study?`,
answers: ["Its depth", "Its simplicity", "Its age", "Its novelty"],
correct: 0
},
{
question: `How would you describe ${topic} to a beginner?`,
answers: ["Fascinating subject", "Boring topic", "Too complex", "Very simple"],
correct: 0
}
];
}
showQuestion() {
if (this.currentQuestionIndex >= this.questions.length) {
this.endGame();
return;
}
const question = this.questions[this.currentQuestionIndex];
this.questionAnswered = false;
this.playerSelections = { player1: null, player2: null };
// Update question counter
document.getElementById('current-question').textContent = this.currentQuestionIndex + 1;
document.getElementById('total-questions').textContent = this.questions.length;
// Hide answers initially
const answersGrid = document.getElementById('answers-grid');
answersGrid.classList.remove('visible');
// Show question
document.getElementById('question-text').textContent = question.question;
// Reset answer options styling and hide player icons
document.querySelectorAll('.answer-option').forEach(option => {
option.className = 'answer-option';
});
// Hide all player icons
document.querySelectorAll('.player-icon').forEach(icon => {
icon.style.display = 'none';
});
// Hide player icon containers
document.querySelectorAll('.player-icons').forEach(container => {
container.classList.remove('visible');
});
// Reset player selections display
this.updatePlayerSelections();
// Show answers after 2.5 seconds
setTimeout(() => {
// Show answers
question.answers.forEach((answer, index) => {
document.getElementById(`answer-${index}`).textContent = answer;
});
// Make answers visible with animation
answersGrid.classList.add('visible');
// Start timer after answers are shown
setTimeout(() => {
this.startTimer();
}, 500); // Small delay for animation to complete
}, 2500);
}
selectAnswer(player, answerIndex) {
if (this.questionAnswered) return;
// Only allow selection if answers are visible
const answersGrid = document.getElementById('answers-grid');
if (!answersGrid.classList.contains('visible')) return;
this.playerSelections[player] = answerIndex;
this.updatePlayerSelections();
// Don't show selection visually until reveal
// Check if both players have answered
if (this.playerSelections.player1 !== null && this.playerSelections.player2 !== null) {
this.processAnswers();
}
}
updatePlayerSelections() {
// const getAnswerText = (index) => {
// if (index === null) return 'No selection';
// const letters = ['A', 'B', 'C', 'D'];
// return `${letters[index]} - ${this.questions[this.currentQuestionIndex].answers[index]}`;
// };
const getIsSelected = (index) => {
if (index === null) return 'No selection';
return 'Answer Selected'
};
document.getElementById('player1-selection').textContent = getIsSelected(this.playerSelections.player1);
document.getElementById('player2-selection').textContent = getIsSelected(this.playerSelections.player2);
}
startTimer() {
this.timeLeft = 15;
this.updateTimerDisplay();
this.timer = setInterval(() => {
this.timeLeft--;
this.updateTimerDisplay();
if (this.timeLeft <= 0) {
this.processAnswers();
}
}, 1000);
}
updateTimerDisplay() {
document.getElementById('timer-text').textContent = this.timeLeft;
const percentage = (this.timeLeft / 15) * 100;
document.getElementById('timer-fill').style.width = percentage + '%';
}
processAnswers() {
if (this.questionAnswered) return;
this.questionAnswered = true;
clearInterval(this.timer);
const question = this.questions[this.currentQuestionIndex];
const correctIndex = question.correct;
// Show player selections with icons
this.revealPlayerSelections();
// Highlight correct answer
document.querySelector(`[data-index="${correctIndex}"]`).classList.add('correct');
// Check player answers and update scores
if (this.playerSelections.player1 === correctIndex) {
this.scores.player1++;
} else if (this.playerSelections.player1 !== null) {
document.querySelector(`[data-index="${this.playerSelections.player1}"]`).classList.add('incorrect');
}
if (this.playerSelections.player2 === correctIndex) {
this.scores.player2++;
} else if (this.playerSelections.player2 !== null) {
document.querySelector(`[data-index="${this.playerSelections.player2}"]`).classList.add('incorrect');
}
this.updateScoreDisplay();
// Move to next question after delay
setTimeout(() => {
this.currentQuestionIndex++;
this.showQuestion();
}, 3000);
}
revealPlayerSelections() {
// Show player icons for their selections
if (this.playerSelections.player1 !== null) {
const player1Icon = document.getElementById(`player1-icon-${this.playerSelections.player1}`);
const iconContainer = document.getElementById(`player-icons-${this.playerSelections.player1}`);
player1Icon.style.display = 'flex';
iconContainer.classList.add('visible');
}
if (this.playerSelections.player2 !== null) {
const player2Icon = document.getElementById(`player2-icon-${this.playerSelections.player2}`);
const iconContainer = document.getElementById(`player-icons-${this.playerSelections.player2}`);
player2Icon.style.display = 'flex';
iconContainer.classList.add('visible');
}
}
updateScoreDisplay() {
document.getElementById('player1-score').textContent = this.scores.player1;
document.getElementById('player2-score').textContent = this.scores.player2;
}
endGame() {
this.gameInProgress = false;
this.showScreen('results-screen');
// Update final scores
document.getElementById('final-player1-score').textContent = this.scores.player1;
document.getElementById('final-player2-score').textContent = this.scores.player2;
// Determine winner
const winnerAnnouncement = document.getElementById('winner-announcement');
if (this.scores.player1 > this.scores.player2) {
winnerAnnouncement.innerHTML = '<h2>Player 1 Wins! 🎉</h2>';
} else if (this.scores.player2 > this.scores.player1) {
winnerAnnouncement.innerHTML = '<h2>Player 2 Wins! 🎉</h2>';
} else {
winnerAnnouncement.innerHTML = '<h2>It\'s a Tie! 🤝</h2>';
}
}
resetGame() {
this.currentQuestionIndex = 0;
this.scores = { player1: 0, player2: 0 };
this.playerSelections = { player1: null, player2: null };
this.gameInProgress = false;
this.questionAnswered = false;
clearInterval(this.timer);
// Clear topic input
document.getElementById('topic-input').value = '';
this.showScreen('topic-screen');
}
showScreen(screenId) {
// Hide all screens
document.querySelectorAll('.screen').forEach(screen => {
screen.classList.remove('active');
});
// Show target screen
document.getElementById(screenId).classList.add('active');
this.currentScreen = screenId;
}
}
// Initialize the game when the page loads
document.addEventListener('DOMContentLoaded', () => {
new TriviaGame();
});
// Add some visual feedback for key presses
document.addEventListener('keydown', (e) => {
const key = e.key.toLowerCase();
const wasd = new Set(['w', 'a', 's', 'd']);
// Decide which selection element to pulse
const targetEl = key.startsWith('arrow')
? document.getElementById('player2-selection')
: (wasd.has(key) ? document.getElementById('player1-selection') : null);
if (!targetEl) return;
// Apply both transform + background shade
targetEl.style.transition = 'transform 120ms ease, background-color 120ms ease';
targetEl.style.transform = 'scale(0.95)';
targetEl.style.backgroundColor = '#e0e0e0'; // light gray shade
setTimeout(() => {
targetEl.style.transform = '';
targetEl.style.backgroundColor = ''; // revert back
}, 120);
});