forked from ElenaDRFS/quiz-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
732 lines (530 loc) · 22.1 KB
/
script.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
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-auth.js";
import { getFirestore, collection, where, getDocs, doc, setDoc, updateDoc, query, orderBy, limit, getDoc } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-firestore.js";
import { getStorage, ref, uploadBytes, getDownloadURL } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-storage.js";
//TODO: Add SDKs for Firebase products that you want to use
//https://firebase.google.com/docs/web/setup#available-libraries
//CONECTAR FIREBASE
const firebaseConfig = {
apiKey: "AIzaSyBBySJ7kyqqwkhoo2dJFZDPa0XAgh4QoY8",
authDomain: "quiz-2-cea59.firebaseapp.com",
projectId: "quiz-2-cea59",
storageBucket: "quiz-2-cea59.appspot.com",
messagingSenderId: "812092197244",
appId: "1:812092197244:web:a0490411e36860e77ebcf9",
measurementId: "G-82J05KL4T3"
};
//Initialize Firebase
const app = initializeApp(firebaseConfig);
//Initialize Auth
const auth = getAuth();
const user = auth.currentUser;
//Initialize DDBB
const db = getFirestore(app);
//Initialize cloudstore
const storage = getStorage();
//VARIABLES
let preguntas = [];
let correctas = [];
let userName = "";
let page = 0;
let score = 0;
let fecha = new Date();
let dia = String(fecha.getDate()).padStart(2, '0');
let mes = String(fecha.getMonth() + 1).padStart(2, '0'); // Los meses en JavaScript empiezan en 0
let ano = fecha.getFullYear();
fecha = dia + '/' + mes + '/' + ano;
//// ______________ REGISTO LOGIN Y AUTENTICATION _____________________
const signUpForm = document.getElementById('signup-form');
const loginForm = document.getElementById('login-form');
const userData = document.getElementById('user-data');
const bienvenida = document.getElementById("bienvenida");
const scoresBox = document.getElementById("scoresBox");
const logout = document.getElementById('logout');
let loginEmail;
if (document.title == "Jukebox Quiz - Home") {
//SignUp function
signUpForm.addEventListener('submit', async (e) => {
e.preventDefault();
let signUpEmail = document.getElementById('signup-email').value;
let signUpUserName = document.getElementById('signup-user').value;
// //almacenamos ese email en LOCALSTORAGE
let guardar = JSON.parse(localStorage.getItem("mails"));
let mail = { email: signUpEmail, username: signUpUserName };
if (guardar === null) {
localStorage.setItem("mails", JSON.stringify(mail));
guardar.push(mail);
localStorage.setItem("mails", JSON.stringify(guardar));
} else {
guardar.push(mail);
localStorage.setItem("mails", JSON.stringify(guardar));
};
const signUpPassword = document.getElementById('signup-pass').value;
const signUpUser = document.getElementById('signup-user').value;
const usersRef = collection(db, "users");
try {
//Create auth user
await createUserWithEmailAndPassword(auth, signUpEmail, signUpPassword)
.then((userCredential) => {
console.log('User Signed In!')
const user = userCredential.user;
signUpForm.reset();
userData.style.cssText = 'display:block; background-color: #73AB84;width: 50%;margin: 2rem auto;padding: 1rem;border-radius: 5px;display: flex;flex-direction: column;align-items: center';
userData.innerHTML = `<h3>Welcome!</h3>
<p>Username: ${signUpUser}</p>
<p>Now you are ready to play!</p>
<button id="startQuiz"class="quizbutton" type="click"><a href="./question.html">Play!</a></button>`
document.getElementById("signup-form").style.display = "none";
document.getElementById("user-data").style.cssText = 'display: block; background-color: #ffcfd2; width: 75%; margin: auto; padding: 5px;';
})
//Create document in DB
await setDoc(doc(usersRef, signUpEmail), {
username: signUpUser,
email: signUpEmail,
})
} catch (error) {
console.log('Error: ', error)
}
});
//Login function
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
loginEmail = document.getElementById('login-email').value;
const loginPassword = document.getElementById('login-pass').value;
let userData = document.getElementById('user-data');
//Call the collection in the DB
const docRef = doc(db, "users", loginEmail);
//Search a document that matches with our ref
const docSnap = await getDoc(docRef);
signInWithEmailAndPassword(auth, loginEmail, loginPassword)
.then(() => {
console.log('User Signed In!')
loginForm.reset();
})
.then(() => {
if (docSnap.exists()) {
userName = docSnap.data().username;
userData.style.cssText = 'display: block; background-color: #ffcfd2; width: 75%; margin: auto; padding: 5px;';
userData.innerHTML = `<h3>Welcome!</h3>
<p>Username: ${docSnap.data().username}</p>
<p>Email: ${docSnap.data().email}</p>
<p>Now you are ready to play!</p>
<button id="startQuiz"class="quizbutton" type="click"><a href="./question.html">Play!</a></button>
`
userData.style.display = "block";
document.getElementById("playAsGuest").style.display = "none";
document.getElementById("login-form").style.display = "none";
document.getElementById("scoresBox").style.display = "block";
//almacenamos ese mail en LOCAL STORAGE
let guardar = JSON.parse(localStorage.getItem("mails"));
let mail = [{ email: loginEmail, username: userName }];
if (guardar === null) {
localStorage.setItem("mails", JSON.stringify(mail));
} else {
let newEmail = { email: loginEmail, username: userName };
guardar.push(newEmail);
localStorage.setItem("mails", JSON.stringify(guardar));
}
//GRAFICA USUARIO LOGUEADO
let fechasGrafica = [];
let scoreGrafica = [];
// Initialize Firestore
const db = getFirestore();
// Reference to the "partidas" collection
let partidasRef = collection(db, "partidas");
// Query to get documents where "email" is equal to the logged in user's email
let q = query(partidasRef, where("email", "==", loginEmail), orderBy("date", "asc"));
// Execute the query
getDocs(q).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// Extract date and score and add them to fechasGrafica and scoreGrafica
fechasGrafica.push(doc.data().date);
scoreGrafica.push(doc.data().scores);
});
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: [`${fechasGrafica[0]}`, `${fechasGrafica[1]}`, `${fechasGrafica[2]}`, `${fechasGrafica[3]}`],
datasets: [{
label: 'Correct Answers',
data: [`${scoreGrafica[0]}`, `${scoreGrafica[1]}`, `${scoreGrafica[2]}`, `${scoreGrafica[3]}`],
borderWidth: 1
}]
},
options: {
responsive: true,
aspectRatio: 1 | 1,
scales: {
y: {
beginAtZero: true
}
}
}
});
});
} else {
console.log("No such document!");
}
})
.catch((error) => {
document.getElementById('msgerr').innerHTML = 'Invalid user or password';
const errorCode = error.code;
const errorMessage = error.message;
console.log('Código del error: ' + errorCode);
console.log('Mensaje del error: ' + errorMessage);
});
})
// Check if user is logged in
auth.onAuthStateChanged(user => {
if (user) {
let mails = JSON.parse(localStorage.getItem('mails'));
let currentUser = mails[mails.length - 1];
userData.style.cssText = 'display: block; background-color: #ffcfd2; width: 75%; margin: auto; padding: 5px;';
userData.innerHTML = `<h3>Take another round!</h3>
<p>Username: ${currentUser.username}</p>
<p>Email: ${currentUser.email}</p>
<p>Are you ready?</p>
<button id="startQuiz"class="quizbutton" type="click"><a href="./question.html">Play!</a></button>`
userData.style.display = "block";
document.getElementById("playAsGuest").style.display = "none";
document.getElementById("login-form").style.display = "none";
document.getElementById("scoresBox").style.display = "block";
console.log('User Signed In!');
//GRAFICA USUARIO LOGUEADO
let fechasGrafica = [];
let scoreGrafica = [];
// Initialize Firestore
const db = getFirestore();
// Reference to the "partidas" collection
let partidasRef = collection(db, "partidas");
// Query to get documents where "email" is equal to the logged in user's email
let q = query(partidasRef, where("email", "==", user.email), orderBy("date", "asc"));
// Execute the query
getDocs(q).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// Extract date and score and add them to fechasGrafica and scoreGrafica
fechasGrafica.push(doc.data().date);
scoreGrafica.push(doc.data().scores);
});
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: [`${fechasGrafica[0]}`, `${fechasGrafica[1]}`, `${fechasGrafica[2]}`, `${fechasGrafica[3]}`],
datasets: [{
label: 'Correct Answers',
data: [`${scoreGrafica[0]}`, `${scoreGrafica[1]}`, `${scoreGrafica[2]}`, `${scoreGrafica[3]}`],
borderWidth: 1
}]
},
options: {
responsive: true,
aspectRatio: 1 | 1,
scales: {
y: {
beginAtZero: true
}
}
}
});
});
} else {
bienvenida.style.display = "block";
scoresBox.style.display = "none";
console.log('No logged user');
}
})
}
//// ______________ FUNCIONES _____________________
//VALIDA PREGUNTAS Y MANDA A FIRESTORE
function submitForm() {
document.getElementById("check").addEventListener('click', async function (event) {
event.preventDefault();
let respuesta = document.querySelector(`input[name=answer]:checked`).value;
if (respuesta == "r3") {
score++
}
let playersMails = JSON.parse(localStorage.getItem("mails"));
let ultimo = playersMails[playersMails.length - 1];
let playerUserName = [];
const user = auth.currentUser;
const userRef = doc(db, 'users', user.email);
const userDoc = await getDoc(userRef);
if (userDoc.exists()) {
playerUserName.push(userDoc.data().username);
}
let fechaScore = {
fecha: fecha,
score: score
}
const character = Object.assign(ultimo, fechaScore);
playersMails[playersMails.length - 1] = character;
localStorage.setItem("mails", JSON.stringify(playersMails));
//info a FIREBASE
const id = Math.random().toString(36).substring(7);
const docRef = doc(db, "partidas", id);
const data = {
email: ultimo.email,
username: ultimo.username,
date: fecha,
scores: score
};
setDoc(docRef, data)
.then(docRef => {
console.log("A New Document Field has been added to an existing document");
window.location.href = './results.html';
})
.catch(error => {
console.log(error);
});
});
};
// LLAMADA FETH A LA API
async function questionsGenerator() {
let response = await fetch(
"https://opentdb.com/api.php?amount=10&category=12&difficulty=easy&type=multiple"
);
let data = await response.json();
preguntas = data.results;
preguntas.forEach(element => {
correctas.push(element.correct_answer);
});
}
// PINTAR PREGUNTAS
function pintarQuiz() {
let title = preguntas[page].question;
let correct = preguntas[page].correct_answer;
let incorrect = preguntas[page].incorrect_answers;
incorrect.push(correct);
function randomizar(indicesRespuestas) {
indicesRespuestas.sort(() => Math.random() - 0.5);
}
let i = [0, 1, 2, 3];
randomizar(i);
//template string para generar formulario, dentro de la función porque cuando haga el fetch es cuando se pintan
let form = document.getElementById("formulario");
form.innerHTML = `<section id="container">
<h1>${title}</h1>
<input class = "radio" type="radio" name='answer' id="ans1" value=r${i[0]}>
<label for="ans1" id="opt1" class="answers"><img class="iconLabel" src="./assets/images/icon09.png" alt="">${incorrect[(i[0])]}</label>
<input class = "radio" type="radio" name='answer' id="ans2" value = r${i[1]}>
<label for="ans2" id="opt2" class="answers"><img class="iconLabel" src="./assets/images/icon05.png" alt="">${incorrect[(i[1])]}</label>
<input class = "radio" type="radio" name= 'answer' id="ans3" value = r${i[2]}>
<label for="ans3" id="opt3" class="answers"><img class="iconLabel" src="./assets/images/icon04.png" alt="">${incorrect[(i[2])]}</label>
<input class = "radio" type="radio" name= 'answer' " id="ans4" value = r${i[3]}>
<label for="ans4" id="opt4" class="answers"><input type="radio" name="answer" id="ans4"><img class="iconLabel" src="./assets/images/icon11.png" alt="">${incorrect[(i[3])]}</label>
<input type="submit" value="Checked results!" class="quizbutton notshow" id="check"></input>
</section>`
}
if (document.title === 'Quiz') {
questionsGenerator().then(() => {
pintarQuiz();
})
}
if (document.title === 'Jukebox Quiz - Results') {
let local = JSON.parse(localStorage.getItem("mails"));
let lastround = local[local.length - 1].score;
for (let x = 0; x < local.length; x++) {
if (local[x].score == undefined) {
local.splice(x, 1)
}
}
let meterPuntuacion = document.getElementById("meterPuntuacion");
meterPuntuacion.innerHTML = `You have answered ${lastround} questions correctly`
const points = document.getElementById('hallOfFame');
points.innerHTML = `<img class="iconLabel" src="./assets/images/icon01.png" alt="">
<h2 class="fontResult">Hall of Fame: </h2>`
const partidasRef = collection(db, 'partidas');
const peticion = query(partidasRef, orderBy('scores', 'desc'), limit(5));
getDocs(peticion).then((querySnapshot) => {
const table = document.getElementById('table');
table.innerHTML = `
<table>
<thead>
<tr>
<th>Player</th>
<th>Date</th>
<th>Result</th>
</tr>
</thead>
<tbody>
${querySnapshot.docs.map((doc) => `
<tr>
<td>${doc.data().username}</td>
<td>${doc.data().date}</td>
<td>${doc.data().scores} of 10</td>
</tr>
`).join('')}
</tbody>
</table>
`;
});
}
//// ______________ BOTONES _____________________
//BOTON REGISTRAR
if (document.title === "Jukebox Quiz - Home") {
const cuadroLogin = document.querySelector("#login-form");
const cuadroRegistrar = document.querySelector("#signup-form");
const botonRegistrar = document.querySelector("#registrar");
botonRegistrar.addEventListener("click", function () {
cuadroLogin.style.display = "none";
botonRegistrar.style.display = "none";
cuadroRegistrar.style.display = "block";
});
}
//BOTON PLAY AS GUEST
if (document.title === "Jukebox Quiz - Home") {
const playAsGuestButton = document.getElementById("playAsGuest");
playAsGuestButton.addEventListener("click", async () => {
const loginEmail ="invitado@juqueboxquiz.com" ;
const loginPassword = "invitado";
let userData = document.getElementById('user-data');
//Call the collection in the DB
const docRef = doc(db, "users", loginEmail);
//Search a document that matches with our ref
const docSnap = await getDoc(docRef);
signInWithEmailAndPassword(auth, loginEmail, loginPassword)
.then(() => {
console.log('User Signed In!')
loginForm.reset();
})
.then(() => {
if (docSnap.exists()) {
userName = docSnap.data().username;
userData.style.cssText = 'display: block; background-color: #ffcfd2; width: 75%; margin: auto; padding: 5px;';
userData.innerHTML = `<h3>Welcome!</h3>
<p>Username: ${docSnap.data().username}</p>
<p>Email: ${docSnap.data().email}</p>
<p>Now you are ready to play!</p>
<button id="startQuiz"class="quizbutton" type="click"><a href="./question.html">Play!</a></button>
`
userData.style.display = "block";
document.getElementById("playAsGuest").style.display = "none";
document.getElementById("login-form").style.display = "none";
document.getElementById("scoresBox").style.display = "block";
//almacenamos ese mail en LOCAL STORAGE
let guardar = JSON.parse(localStorage.getItem("mails"));
let mail = [{ email: loginEmail, username: userName }];
if (guardar === null) {
localStorage.setItem("mails", JSON.stringify(mail));
} else {
let newEmail = { email: loginEmail, username: userName };
guardar.push(newEmail);
localStorage.setItem("mails", JSON.stringify(guardar));
}
//GRAFICA USUARIO LOGUEADO
let fechasGrafica = [];
let scoreGrafica = [];
// Initialize Firestore
const db = getFirestore();
// Reference to the "partidas" collection
let partidasRef = collection(db, "partidas");
// Query to get documents where "email" is equal to the logged in user's email
let q = query(partidasRef, where("email", "==", loginEmail), orderBy("date", "asc"));
// Execute the query
getDocs(q).then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// Extract date and score and add them to fechasGrafica and scoreGrafica
fechasGrafica.push(doc.data().date);
scoreGrafica.push(doc.data().scores);
});
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'bar',
data: {
labels: [`${fechasGrafica[0]}`, `${fechasGrafica[1]}`, `${fechasGrafica[2]}`, `${fechasGrafica[3]}`],
datasets: [{
label: 'Correct Answers',
data: [`${scoreGrafica[0]}`, `${scoreGrafica[1]}`, `${scoreGrafica[2]}`, `${scoreGrafica[3]}`],
borderWidth: 1
}]
},
options: {
responsive: true,
aspectRatio: 1 | 1,
scales: {
y: {
beginAtZero: true
}
}
}
});
});
} else {
console.log("No such document!");
}
})
.catch((error) => {
document.getElementById('msgerr').innerHTML = 'Invalid user or password';
const errorCode = error.code;
const errorMessage = error.message;
console.log('Código del error: ' + errorCode);
console.log('Mensaje del error: ' + errorMessage);
});
});
}
//BOTON LOGOUT NAVBAR
if (document.title === "Quiz" || document.title === 'Jukebox Quiz - Results') {
const logout = document.getElementById("logoutButton");
logout.addEventListener('click', () => {
signOut(auth).then(() => {
console.log('Logout user')
alert("Hope to see you soon!")
window.location.href = './index.html';
}).catch((error) => {
console.log('Error: ', error)
});
})
}
// FUNCIONALIDAD BOTON MUTE
if (document.title === 'Quiz' || document.title === 'Jukebox Quiz - Results') {
let audio = document.getElementsByClassName("audio");
let mute = document.getElementsByClassName("muteButton");
mute[0].addEventListener("click", function () {
if (audio[0].muted == true) {
audio[0].muted = false;
} else {
audio[0].muted = true;
};
});
}
// botón back
if (document.title === 'Quiz') {
document.getElementById('back').addEventListener('click', function () {
if (page > 0) {
page--;
}
if (score > 0) {
score--;
};
pintarQuiz();
}
)
};
//boton next
if (document.title === 'Quiz') {
document.getElementById('next').addEventListener('click', function () {
let respuesta = document.querySelector(`input[name=answer]:checked`).value
if (respuesta == "r3") {
score++
console.log(score);
}
page++
pintarQuiz();
if (page === 9) {
document.getElementById('back').style.display = 'none';
document.getElementById('next').style.display = 'none';
document.getElementById('check').classList.remove('notshow');
page = 0;
submitForm();
}
});
}
//botón play again
if (document.title === 'Jukebox Quiz - Results') {
document.getElementById('again').addEventListener('click', function () {
window.location.href = './question.html'
})
}