-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetchFromFreeSound.js
323 lines (270 loc) · 11.2 KB
/
fetchFromFreeSound.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
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
import { key } from "./secret.js";
import { curatedCountries } from "./curatedCountries.js";
localStorage.clear()
// **** || MAIN FUNCTION || ****
// Load new round calls our update DOM functions, which subsequently call
// our fetch functions.
loadNewRound()
function loadNewRound() {
const previousAudio = document.querySelectorAll("audio");
const starsHTMLColl = document.getElementById('stars').children;
let stars = Array.prototype.slice.call(starsHTMLColl, 0);
for (const star of stars){
star.classList.remove("fa-regular");
star.classList.add('fa-solid');
}
for (let i = 0; i < previousAudio.length; i++) {
previousAudio[i].remove()
}
document.getElementById("correctAnswerPopup").style.display = "none";
document.getElementById("incorrectAnswerPopup").style.display = "none";
let countryOne = generateRandomCountry();
let countryTwo = generateRandomCountry();
while(countryTwo === countryOne) {
countryTwo = generateRandomCountry();
}
loadAudio(countryOne);
displayFlags(countryOne, countryTwo);
}
// **** || UPDATE DOM FUNCTIONS || ****
// These call our fetch functions and update the DOM with the data
async function loadAudio(countryOne) {
const soundObject = await getCountrySounds(countryOne);
const parentElement = document.getElementById("audioContainer");
for (let i = 0; i < 5; i++){
const soundUrl = soundObject[`preview${i}`];
const audioPlayer = document.createElement("AUDIO");
audioPlayer.id = `audioplayer${i}`
audioPlayer.src = soundUrl;
audioPlayer.setAttribute("controls", "true");
audioPlayer.style.display = "none";
parentElement.appendChild(audioPlayer);
}
document.getElementById("audioplayer0").style.display = "block"
const loadingScreen = document.getElementById("loadingScreen")
loadingScreen.classList.toggle("hidden")
}
async function displayFlags(countryOne, countryTwo) {
try {
let flagObj = await getCountryFlags(countryOne,countryTwo);
const flagsElements = document.getElementsByClassName("flag");
//copy to array so we can splice later
const flagsArr = Array.prototype.slice.call(flagsElements, 0);
//randomise flag one
let flagOnePos = Math.floor(Math.random() * 2);
//set it to that pos
flagsArr[flagOnePos].src = flagObj.flagOne;
flagsArr[flagOnePos].classList.remove("correct", "incorrect")
flagsArr[flagOnePos].classList.add("correct")
//flagsArr[flagOnePos].className = "flag correct";
flagsArr[flagOnePos].parentElement.nextElementSibling.innerHTML = capitaliseCountryName(countryOne);
//remove from array
flagsArr.splice(flagOnePos, 1);
//set flag two to remaining pos
flagsArr[0].src = flagObj.flagTwo;
flagsArr[0].classList.remove("correct", "incorrect")
flagsArr[0].classList.add("incorrect")
//flagsArr[0].className = "flag incorrect";
flagsArr[0].parentElement.nextElementSibling.innerHTML = capitaliseCountryName(countryTwo);
//add new event listeners
for (let i = 0; i < flagsElements.length; i++) {
flagsElements[i].addEventListener('click', checkAnswer);
}
} catch (error) {
console.error(error);
document.getElementById("error").classList.toggle("hidden");
}
}
// **** || FETCH FUNCTIONS || ****
// These grab the data from the APIS
async function getCountrySounds(countryOne) {
try {
const loadingScreen = document.getElementById("loadingScreen")
loadingScreen.classList.toggle("hidden")
const soundsObj = []
const response = await fetch(`https://freesound.org/apiv2/search/text/?query=${countryOne}&token=${key}`);
const sounds = await response.json();
let usedSounds = [];
for (let i = 0; i < 5; i++){
let randomSound = sounds.results[Math.floor(Math.random() * sounds.results.length)];
let soundId = randomSound.id;
while(usedSounds.includes(soundId)) {
randomSound = sounds.results[Math.floor(Math.random() * sounds.results.length)];
soundId = randomSound.id;
}
usedSounds.push(soundId)
const soundResponse = await fetch(`https://freesound.org/apiv2/sounds/${soundId}?token=${key}`);
const soundData = await soundResponse.json();
const soundPreviewUrl = soundData.previews['preview-hq-mp3'];
soundsObj[`preview${i}`] = soundPreviewUrl;
}
return soundsObj;
} catch (error) {
console.error(error);
document.getElementById("error").classList.toggle("hidden");
}
}
async function getCountryFlags(countryOne, countryTwo){
try {
const requests = [
fetch(`https://restcountries.com/v3.1/name/${countryOne}`),
fetch(`https://restcountries.com/v3.1/name/${countryTwo}`)
]
const [countryOneResponse, countryTwoResponse] = await Promise.all(requests);
const countryOneData = await countryOneResponse.json();
const countryTwoData = await countryTwoResponse.json();
const flagRequests = [
fetch(countryOneData[0].flags.png),
fetch(countryTwoData[0].flags.png)
]
const [flagOneResponse, flagTwoResponse] = await Promise.all(flagRequests);
const flagOneData = await flagOneResponse.blob();
const flagTwoData = await flagTwoResponse.blob();
const flagURLOne = URL.createObjectURL(flagOneData);
const flagURLTwo = URL.createObjectURL(flagTwoData);
return {flagOne: flagURLOne, flagTwo: flagURLTwo};
} catch (error) {
console.error(error);
document.getElementById("error").classList.toggle("hidden");
}
}
// **** || FUNCTIONS THAT HANDLE USER ANSWERS || ****
let passCount = 0
document.getElementById("btnPass").addEventListener('click', (e)=>{
passCount += 1
const audioPlayersArr = document.querySelectorAll("audio");
const starsHTMLColl = document.getElementById('stars').children;
let stars = Array.prototype.slice.call(starsHTMLColl, 0);
if (passCount < 5){
document.getElementById(`audioplayer${passCount}`).style.display = 'block';
stars.at(passCount * -1).classList.remove("fa-solid");
stars.at(passCount * -1).classList.add('fa-regular');
} if (passCount >= 5 && document.getElementById('noAudio').classList.contains('hide')){
document.getElementById('noAudio').classList.toggle('hide');
}
})
function storeData (answer) {
let gamesPlayedKey = "Games Played";
let gamesPlayedValue = localStorage.getItem("Games Played");
let fiveStarGamesKey = "Five Star Games";
let fiveStarGamesValue = localStorage.getItem("Five Star Games");
let fourStarGamesKey = "Four Star Games";
let fourStarGamesValue = localStorage.getItem("Four Star Games");
let threeStarGamesKey = "Three Star Games";
let threeStarGamesValue = localStorage.getItem("Three Star Games");
let twoStarGamesKey = "Two Star Games";
let twoStarGamesValue = localStorage.getItem("Two Star Games");
let oneStarGamesKey = "One Star Games";
let oneStarGamesValue = localStorage.getItem("One Star Games");
let zeroStarGamesKey = "Zero Star Games";
let zeroStarGamesValue = localStorage.getItem("Zero Star Games");
const gameStatsArr = [fiveStarGamesValue, fourStarGamesValue, threeStarGamesValue, twoStarGamesValue, oneStarGamesValue,zeroStarGamesValue];
const gameKeyArr = [fiveStarGamesKey, fourStarGamesKey, threeStarGamesKey, twoStarGamesKey, oneStarGamesKey, zeroStarGamesKey];
//increase gamesplayed first
addToScores(gamesPlayedKey, gamesPlayedValue)
gameStatsArr.forEach((stat, index) => {
if (answer === 'correct' && passCount === index){
//if the answer is right, update relevant key
addToScores(gameKeyArr[index], stat);
} else if (answer === 'incorrect'){
//if incorrect update zerostargames
addToScores(zeroStarGamesKey, zeroStarGamesValue);}
})
// function to add to numbers of scores for each star type
function addToScores(key, value) {
value = Number(value) + 1;
localStorage.setItem(key, value);
}
const gameArr = [
Number(localStorage['Five Star Games']),
Number(localStorage['Four Star Games']),
Number(localStorage['Three Star Games']),
Number(localStorage['Two Star Games']),
Number(localStorage['One Star Games']),
Number(localStorage['Zero Star Games'])
]
updateStatsModal(gameArr);
}
function updateStatsModal(Arr){
const bars = document.querySelectorAll('.bar')
const gamesplayedElement = document.getElementById('gamesPlayed')
const gamesplayed = Number(localStorage['Games Played'])
bars.forEach((bar, index) => {
if (!isNaN(Arr[index])){
bar.style.width = `${(Arr[index]/gamesplayed) * 100}%`
bar.innerHTML = `${Math.floor((Arr[index]/gamesplayed) * 100)}%`
}
})
gamesplayedElement.innerHTML = `Games played: ${gamesplayed}`;
}
function submitAnswer(answer) {
storeData(answer, passCount)
if(answer === "correct") {
document.getElementById("correctAnswerPopup").style.display = "block";
}
else if (answer === "incorrect") {
document.getElementById("incorrectAnswerPopup").style.display = "block";
}
const newRoundButtons = document.getElementsByClassName("new-round");
for (let i = 0; i < newRoundButtons.length; i++) {
newRoundButtons[i].addEventListener('click', loadNewRound)
}
//reset passCount and NoMoreAudio window
passCount = 0
if (!document.getElementById('noAudio').classList.contains('hide')){
document.getElementById('noAudio').classList.toggle('hide');
}
const flagsElements = document.getElementsByClassName("flag");
for (let i = 0; i < flagsElements.length; i++) {
flagsElements[i].removeEventListener('click', checkAnswer);
}
}
function checkAnswer() {
if (this.classList.contains("correct")) {
submitAnswer("correct")
} else {
submitAnswer("incorrect")
}
}
// **** || HELPER FUNCTIONS || ****
function generateRandomCountry() {
return curatedCountries[Math.floor(Math.random() * curatedCountries.length)]
}
function capitaliseCountryName(country) {
const arr = country.split(" ");
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join(" ");
}
const btns = document.querySelectorAll('.btn');
btns.forEach((btn) => {
btn.addEventListener('click', (e) => {
let elementId = e.target.name;
//check if the user clicked on the icon element, if so then target name attribute of the
//corresponding btn instead.
if (e.target.name === undefined){elementId = e.target.parentElement.name}
// display/hide modal window
const modal = document.getElementById(elementId);
modal.classList.toggle('hidden');
})
})
// Function to preview star disappearing when hovering on pass button
document.getElementById("btnPass").addEventListener("mouseover", hideOneStar)
document.getElementById("btnPass").addEventListener("mouseout", returnOneStar)
function hideOneStar() {
const starsHTMLColl = document.getElementById('stars').children;
let stars = Array.prototype.slice.call(starsHTMLColl, 0);
if (passCount < 4){
stars.at(4 - passCount).classList.remove("fa-solid");
stars.at(4 - passCount).classList.add('fa-regular');
}
}
function returnOneStar() {
const starsHTMLColl = document.getElementById('stars').children;
let stars = Array.prototype.slice.call(starsHTMLColl, 0);
if (passCount < 4){
stars.at(4 - passCount).classList.remove("fa-regular");
stars.at(4 - passCount).classList.add('fa-solid');
}
}