-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
154 lines (129 loc) · 3.97 KB
/
Copy pathscript.js
File metadata and controls
154 lines (129 loc) · 3.97 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
// DOM Elements (assuming you have these in your HTML)
const questionContainer = document.getElementById('question-container');
const scoreEl = document.getElementById('score');
const timerEl = document.getElementById('timer');
const nextButton = document.getElementById('next-button');
const restartButton = document.getElementById('restart-button');
const highScoreEl = document.getElementById('high-score'); // An element to display high score
// Game Variables
let questions = [];
let currentQuestionIndex = 0;
let score = 0;
let timeLeft = 10;
let timerId = null;
// On page load
document.addEventListener('DOMContentLoaded', () => {
loadQuestions();
restartButton.addEventListener('click', startGame);
// Display any previously saved high score
const savedHighScore = localStorage.getItem('highScore') || 0;
highScoreEl.textContent = `High Score: ${savedHighScore}`;
});
async function loadQuestions() {
try {
// Use a RAW GitHub link or any public URL that returns JSON
const response = await fetch('fetch('https://jtb21091.github.io/PittsburghTrivia/questions_converted.json');
if (!response.ok) throw new Error('Network response was not OK');
const data = await response.json();
questions = shuffleArray(data);
startGame();
} catch (error) {
console.error('Error loading questions:', error);
// Could display an error message to the user
}
}
function startGame() {
currentQuestionIndex = 0;
score = 0;
updateScore();
nextButton.style.display = 'none';
showQuestion();
}
function showQuestion() {
if (currentQuestionIndex >= questions.length) {
endGame();
return;
}
clearInterval(timerId);
timeLeft = 10;
updateTimer();
const questionObj = questions[currentQuestionIndex];
questionContainer.innerHTML = `<h2>${questionObj.Question}</h2>`;
const choices = [
questionObj['Choice 1'],
questionObj['Choice 2'],
questionObj['Choice 3']
].filter(Boolean); // Just in case a choice is missing
const shuffledChoices = shuffleArray(choices);
const choicesDiv = document.createElement('div');
shuffledChoices.forEach(choiceText => {
const button = document.createElement('button');
button.textContent = choiceText;
button.classList.add('choice');
button.addEventListener('click', () => checkAnswer(choiceText, questionObj.Answer));
choicesDiv.appendChild(button);
});
questionContainer.appendChild(choicesDiv);
timerId = setInterval(() => {
timeLeft--;
updateTimer();
if (timeLeft <= 0) {
clearInterval(timerId);
nextQuestion();
}
}, 1000);
}
function checkAnswer(selected, correct) {
clearInterval(timerId);
document.querySelectorAll('.choice').forEach(button => {
button.disabled = true;
if (button.textContent === correct) {
button.classList.add('correct');
} else {
button.classList.add('incorrect');
}
});
if (selected === correct) {
score++;
updateScore();
}
setTimeout(nextQuestion, 2000);
}
function nextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex < questions.length) {
showQuestion();
} else {
endGame();
}
}
// END GAME
function endGame() {
clearInterval(timerId);
questionContainer.innerHTML = `
<h2>Game Over!</h2>
<p>Your final score: ${score}</p>
`;
// Check if we have a new high score
const savedHighScore = Number(localStorage.getItem('highScore')) || 0;
if (score > savedHighScore) {
// We have a new high score - update localStorage
localStorage.setItem('highScore', score);
}
// Display updated high score
const updatedHighScore = localStorage.getItem('highScore');
highScoreEl.textContent = `High Score: ${updatedHighScore}`;
nextButton.style.display = 'none';
}
// Update score
function updateScore() {
scoreEl.textContent = `Score: ${score}`;
}
// Update timer
function updateTimer() {
timerEl.textContent = `Time Left: ${timeLeft}s`;
}
// Shuffle helper
function shuffleArray(array) {
return array.sort(() => Math.random() - 0.5);
}