forked from WhalenSITHS/Create-TaskQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGabe.js
89 lines (78 loc) · 2.52 KB
/
Gabe.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
const DOMSelectors = {
input: document.querySelector("#input"),
form: document.querySelector('#form'),
question: document.querySelector('#question'),
true: document.querySelector('#true'),
false: document.querySelector('#false')
}
async function main() {
const api = 'https://opentdb.com/api.php?amount=50&type=boolean'
const response = await fetch(api)
const data = await response.json()
const qa = data.results.map(question =>
({
question: question.question,
correct: question.correct_answer,
incorrect: question.incorrect_answers
})
)
game(qa)
}
function game(qa) {
let i = 0
const used = []
DOMSelectors.form.addEventListener('submit', function(event) {
event.preventDefault()
const input = DOMSelectors.input.value;
displayQuestion(input)
});
function displayQuestion(input) {
if (i < input) {
let q = qa[i]
console.log(q)
clear()
DOMSelectors.question.insertAdjacentHTML("beforeend", `<h1>${q.question}</h1>`)
}
}
DOMSelectors.true.addEventListener('click', function(event) {
event.preventDefault()
let answer = "True"
checkAnswer(answer)
displayQuestion(DOMSelectors.input.value)
console.log(DOMSelectors.input.value)
});
DOMSelectors.false.addEventListener('click', function(event) {
event.preventDefault()
let answer = "False"
checkAnswer(answer)
displayQuestion(DOMSelectors.input.value)
console.log(DOMSelectors.input.value)
}
);
function checkAnswer(answer) {
let q = qa[i]
if (q.correct.includes(answer)) {
used.push("Correct")
}
else {
used.push("Incorrect")
}
i++
if (i === Number(DOMSelectors.input.value)){final(used)}
}
function final(array){
let a = 0
let b = 0
for (let i = 0; i < array.length; i++){
if (array[i].includes("Correct")) {a++}
if (array[i].includes("Incorrect")) {b++}}
clear()
const correct = a * 100/DOMSelectors.input.value
const incorrect = b * 100/DOMSelectors.input.value
DOMSelectors.question.insertAdjacentHTML("beforeend", `<h1>You got ${correct}% of them right and ${incorrect}% of them wrong!</h1>`)
}
}
function clear() {
DOMSelectors.question.innerHTML = ''
}
main()