-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
98 lines (83 loc) · 2.9 KB
/
game.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
const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progressText");
const scoreText = document.getElementById("score");
const progressBarFull = document.getElementById("progressBarFull");
let currentQuestion = {}
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuestions = [];
let questions = [];
fetch("questions.json")
.then(res => {
return res.json();
})
.then(loadedQuestions => {
questions = loadedQuestions;
startGame();
})
.catch(err => {
console.log(err);
})
//CONSTANTS
const CORRECT_BONUS = 10;
const MAX_QUESTIONS = 17;
startGame = () => {
questionCounter = 0;
score = 0;
availableQuestions = [...questions];
getNewQuestion();
}
getNewQuestion = () => {
if (availableQuestions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem('mostRecentScore', score);
// Go to end page
return window.location.assign("/end.html");
}
questionCounter++;
progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`;
// Update the progress bar
progressBarFull.style.width = `${(questionCounter / MAX_QUESTIONS) * 100}%`;
const questionIndex = Math.floor(Math.random() * availableQuestions.length);
currentQuestion = availableQuestions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach( choice => {
const number = choice.dataset['number'];
choice.innerText = currentQuestion['choice' + number];
})
availableQuestions.splice(questionIndex, 1);
acceptingAnswers = true;
}
choices.forEach( choice => {
choice.addEventListener('click', e => {
if(!acceptingAnswers) return;
acceptingAnswers = false;
const selectedChoice = e.target;
const selectedAnswer = selectedChoice.dataset['number'];
const classToApply = selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
if (classToApply === "correct") {
incrementScore(CORRECT_BONUS);
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout( () => {
selectedChoice.parentElement.classList.remove(classToApply);
if (classToApply === "incorrect") {
// Show the correct answer
const correctAnswerId = `q${currentQuestion.answer}`;
const correctAnswer = document.getElementById(correctAnswerId);
correctAnswer.classList.add("correct");
setTimeout( () => {
correctAnswer.classList.remove("correct");
getNewQuestion();
}, 3000);
}
else
getNewQuestion();
}, 1000);
});
});
incrementScore = num => {
score += num;
scoreText.innerText = score;
}