forked from vgarri/QuizProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
527 lines (421 loc) · 18.7 KB
/
script.js
File metadata and controls
527 lines (421 loc) · 18.7 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
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
//-------------------------------FIREBASE FORM-------------------------------------
// Configuración de Firebase
// let firebaseConfig = {
// apiKey: "AIzaSyBazEJwCXDWQZdhWN3JWyN6JDcaxOGp4mI",
// authDomain: "quiztrivia-32d83.firebaseapp.com",
// projectId: "quiztrivia-32d83",
// storageBucket: "quiztrivia-32d83.appspot.com",
// messagingSenderId: "5093975636",
// appId: "1:5093975636:web:42c36e4af7e22e01716fc1"
// };
// firebase.initializeApp(firebaseConfig);
// const formdb = firebase.firestore();
// const addData = (user) => {
// formdb.collection("users")
// .add(user)
// .then((docRef) => {
// console.log("Document written with ID: ", docRef.id)
// readAll();
// })
// .catch((error) => console.error("Error adding document: ", error));
// };
// const readAll = () => {
// // Limpia el album para mostrar el resultado
// cleanformdb();
// //Petición a Firestore para leer todos los documentos de la colección album
// formdb.collection("users")
// .get()
// .then((querySnapshot) => {
// querySnapshot.forEach((doc) => {
// printForm(doc.data().nombre, doc.data().url, doc.id)
// });
// })
// .catch(() => console.log('Error reading documents'));;
// };
// const cleanformdb = () => {
// document.getElementById('formdb').innerHTML = "";
// };
// document.addEventListener("DOMContentLoaded", function() {
// // Obtener referencias a los elementos en HTML
// let formularioDeContacto = document.getElementById("formdb");
// // let listaDeContactos = document.getElementById("contactList");
// // let botonBorrarTodos = document.getElementById("clearAll");
// mostrarContactos(); // llamar para mostrar los contactos guardados al cargar la página
// // cuando el formulario se envía
// formularioDeContacto.addEventListener("submit", function(evento) {
// evento.preventDefault(); // evitar que la página se recargue
// // obtener los valores que el usuario escribió
// let nombre = document.getElementById("name").value;
// let username = document.getElementById("username").value;
// let age = document.getElementById("age").value;
// let email = document.getElementById("email").value;
// let password= document.getElementById("password").value;
// addData({
// name,
// username,
// age,
// email,
// password,
// });
// //Función auxiliar para pintar una foto en el album
// // const printForm = (nombre, email, mensaje, urlImagen, docId) => {
// // let card = document.createElement('article');
// // card.setAttribute('class', 'card');
// // let picture = document.createElement('img');
// // picture.setAttribute('src', url);
// // picture.setAttribute('style', 'max-width:250px');
// // let caption = document.createElement('p');
// // caption.innerHTML = nombre;
// // let id = document.createElement('p');
// // id.innerHTML = docId;
// // const users = document.getElementById('usuarios');
// // card.appendChild(picture);
// // card.appendChild(caption);
// // card.appendChild(id);
// // usuarios.appendChild(card);
// });
// /*
// // crear un objeto con los datos del contacto
// let contacto = {
// nombre: nombre,
// email: email,
// mensaje: mensaje,
// urlImagen: urlImagen
// };
// */
// //// array con los objetos
// // const contacto = { nombre, email, mensaje, urlImagen };
// // guardarContacto(contacto);
// formularioDeContacto.reset(); // reiniciar el formulario
// mostrarContactos(); // actualizar la lista
// });
// // // función para guardar el contacto en el almacenamiento local
// // function guardarContacto(contacto) {
// // let contactosGuardados = obtenerContactos();
// // contactosGuardados.push(contacto); // añadir el nuevo contacto al array
// // localStorage.setItem("contactos", JSON.stringify(contactosGuardados)); // guardar el array en localStorage
// // }
// // función para obtener los contactos guardados del almacenamiento local
// function obtenerContactos() {
// let contactosEnStorage = localStorage.getItem("contactos");
// if (contactosEnStorage === null) {
// return []; // Si no hay contactos, devolver un array vacío
// } else {
// return JSON.parse(contactosEnStorage); // convertir los contactos de texto a un array
// }
// }
// // función para mostrar los contactos guardados
// function mostrarContactos() {
// let contactos = obtenerContactos();
// // listaDeContactos.innerHTML = ""; // limpiar la lista de contactos antes de mostrar los nuevos
// // recorrer todos los contactos y mostrarlos
// for (let i = 0; i < contactos.length; i++) {
// let contacto = contactos[i];
// let elementoLista = document.createElement("li");
// let contenidoContacto = "<strong>" + contacto.nombre + "</strong> (" + contacto.email + ")<br>" + contacto.mensaje; // crear el contenido del contacto
// // // mostrar la imagen si hay una URL
// // if (contacto.urlImagen !== "") {
// // contenidoContacto += "<br><img src='" + contacto.urlImagen + "' alt='Imagen de contacto' width='50'>";
// // }
// elementoLista.innerHTML = contenidoContacto;
// // este es el botón para borrar
// let botonBorrar = document.createElement("button");
// botonBorrar.textContent = "Borrar";
// botonBorrar.dataset.indice = i; // guardar el índice del contacto en el botón
// // cuando se hace clic en el botón de borrar
// botonBorrar.addEventListener("click", function() {
// let indice = this.dataset.indice;
// borrarContacto(indice);
// });
// // añadir el botón al elemento de la lista
// elementoLista.appendChild(botonBorrar);
// // añadir el contacto a la lista
// listaDeContactos.appendChild(elementoLista);
// }
// }
// // función para borrar un contacto
// function borrarContacto(indice) {
// let contactos = obtenerContactos();
// contactos.splice(indice, 1); // quitar el contacto de la lista
// localStorage.setItem("contactos", JSON.stringify(contactos)); // guardar la nueva lista en el almacenamiento local
// mostrarContactos(); // volver a mostrar la lista de contactos actualizada
// }
// evento para borrar todos los contactos
// botonBorrarTodos.addEventListener("click", function() {
// localStorage.removeItem("contactos"); // quitar todos los contactos del almacenamiento local
// mostrarContactos(); // limpiar la lista en la pantalla
// });
//-------------------------------FIN----------------------------------
// // ----------------VALIDACION DE FORMULARIO---------------------------
// const showPasswordCheckbox = document.getElementById('showPassword');
// const passwordInput = document.getElementById('password');
// showPasswordCheckbox.addEventListener('change', function() {
// passwordInput.type = this.checked ? 'text' : 'password'; // Muestra u oculta la contraseña
// });
// // Función para simular la conexión con Google
// document.getElementById('googleLogin').addEventListener('click', function() {
// alert('Conectando con Google...');
// });
// document.getElementById("registrationForm").addEventListener("submit", function(event) {
// const name = document.getElementById("name").value.trim();
// const username = document.getElementById("username").value.trim();
// const age = parseInt(document.getElementById("age").value);
// const email = document.getElementById("email").value.trim();
// const password = document.getElementById("password").value;
// // Validación de nombre y usuario
// if (!name || !username) {
// alert("Por favor, completa tu nombre y usuario.");
// event.preventDefault(); // Evita el envío del formulario
// return;
// }
// // Validación de edad
// if (age < 1 || age > 120) {
// alert("Por favor, ingresa una edad válida.");
// event.preventDefault();
// return;
// }
// // Validación de correo
// const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// if (!emailPattern.test(email)) {
// alert("Por favor, ingresa un correo electrónico válido.");
// event.preventDefault();
// return;
// }
// // Validación de contraseña
// if (password.length < 6) {
// alert("La contraseña debe tener al menos 6 caracteres.");
// event.preventDefault();
// return;
// }
// });
// // Mostrar/ocultar contraseña
// document.getElementById("showPassword").addEventListener("change", function() {
// const passwordField = document.getElementById("password");
// passwordField.type = this.checked ? "text" : "password";
// });
// ----------------------------------------------------------------------
//-------------------GUARDAR FORM EN LOCALSTORAGE-----------------------
document.addEventListener("DOMContentLoaded", function() {
const form = document.getElementById("registrationForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); // Prevenir el envío del formulario
// Obtener valores de los campos
const name = document.getElementById("name").value.trim();
const username = document.getElementById("username").value.trim();
const age = document.getElementById("age").value;
const email = document.getElementById("email").value.trim();
const password = document.getElementById("password").value;
// Crear un objeto de usuario
const user = { name, username, age, email, password };
// Guardar en localStorage
localStorage.setItem('user', JSON.stringify(user));
alert("Usuario registrado en localStorage.");
// Reiniciar el formulario si es necesario
form.reset();
});
});
let preguntas = []; //array pregutas obtenidas api
let preguntaActual = 0; //índice de preguntas
let puntuacion = 0; //se guarda la puntutación de las preguntas (pocentaje)
JSON.parse(localStorage.getItem("Partidas"));
if ( localStorage.getItem("Partidas") === null){
let games = []
localStorage.setItem("Partidas", JSON.stringify(games))
}
async function obtenerPreguntas() {
try {
let respuesta = await fetch('https://opentdb.com/api.php?amount=10&category=12&difficulty=easy&type=multiple');
if (!respuesta.ok) {
throw new Error('Error al obtener las preguntas');
}
let datos = await respuesta.json();
return datos.results;
} catch (error) {
console.error('Hubo un problema con la solicitud:', error);
}
}
async function iniciarQuiz() {
//obtenemos las preguntas de la api
preguntas = await obtenerPreguntas();
//mostramos la primera pregunta
mostrarPregunta();
}
//respuestas mezcladas
//recibe un array de opciones
//sort = método para ordenar un array con el criterio que le demos
function mezclarOpciones(opciones) {
return opciones.sort(() => Math.random() - 0.5);
}
function mostrarPregunta() {
//10 pregutnas
if (preguntaActual < preguntas.length) {
let pregunta = preguntas[preguntaActual];
//muestra la pregunta en el HTML
document.getElementById('pregunta-texto').textContent = pregunta.question;
// 4 OPCIONES
let opcionesLista = document.getElementById('opciones-lista');
opcionesLista.innerHTML = '';
// Crear un array para las opciones
let opciones = [];
// Respuestas incorrectas
for (let i = 0; i < pregunta.incorrect_answers.length; i++) {
opciones.push(pregunta.incorrect_answers[i]);
}
// Respuesta correcta
opciones.push(pregunta.correct_answer);
opciones = mezclarOpciones(opciones);
//iteramos sobre cada opción
opciones.forEach((opcion) => {
let li = document.createElement('li');
//asignamos texto a cada opción
li.textContent = opcion;
li.addEventListener('click', () => verificarRespuesta(opcion === pregunta.correct_answer));
opcionesLista.appendChild(li);
});
} else {
mostrarResultados();
}
}
function verificarRespuesta(esCorrecta) {
if (esCorrecta) {
puntuacion++;
}
//pasar a la siguiente pregunta y mostrarla
preguntaActual++;
mostrarPregunta();
}
// Muestra los resultaods al final
function mostrarResultados() {
document.getElementById('pregunta-texto').textContent = `¡Quiz terminado! Tu puntuación es ${puntuacion} de ${preguntas.length}.`;
document.getElementById('opciones-lista').innerHTML = '';
//-------------------MOSTRAR BOTONES EN PAGINA RESULTADOS----------------------
document.getElementById("botonera").style.display = "block";
document.getElementById("graficaContainer").style.display = "block";
// document.getElementById("borrarTodo").style.display = "block";
}
iniciarQuiz();
// ------------------------------------------------------------------------
//-------------------GUARDAR PARTIDAS EN LOCALSTORAGE--------------------
/*Almacenar la puntuación de cada partida en un array de objetos [{..},{..},{..}...{..}]
en Local Storage. Guardar puntuación y fecha en cada objeto del array
*/
document.getElementById("guardarPartida").addEventListener("click", function (event) {
event.preventDefault();
// Obtener valores
const puntos = puntuacion;
const fecha = Date.now();
const fechaConv = Date(fecha*1000).toString();
//aqui convertir mes dia anio con new date etc
// Crear un objeto de usuario
let game = {
puntuacion: puntos,
fecha: fechaConv
};
// Guardar en localStorage
localStorage.setItem('game', JSON.stringify(game));
alert("Partida guardada con éxito");
saveAndupdateGames(game);
});
function saveAndupdateGames(game) {
games = JSON.parse(localStorage.getItem("Partidas"));
games.push(game);
localStorage.setItem("Partidas", JSON.stringify(games));
}
// ------------------------------------------------------------------------
//-------------------REPRESENTAR GRAFICA LOCALSTORAGE----------------------
/* Mostrar en la Home con una gráfica los resultados de las últimas partidas
jugadas (leer puntuaciones de LocalStorage). Representar Fecha(eje X) vs Puntuación(eje Y) */
document.getElementById("estadisticas").addEventListener("click", function (event) {
event.preventDefault();
games = JSON.parse(localStorage.getItem("Partidas"));
let arrPuntuaciones =[];
let arrFechas =[];
games.forEach(item => {
arrPuntuaciones.push(item.puntuacion);
arrFechas.push(item.fecha);
//console.log(arrPuntuaciones) // push un array de datos
});
new Chartist.Line('.ct-chart', {
labels: arrFechas,
series: [
arrPuntuaciones
]
}, {
fullWidth: true,
chartPadding: {
right: 40
}
});
document.getElementById("graficaContainer").style.opacity = "100";
document.getElementById("graficaContainer").style.display = "block";
});
// document.getElementById("borrarTodo").addEventListener("click", function (event) {
// event.preventDefault();
// let confirmacion = confirm("Estás seguro?")
// if (confirmacion) {
// localStorage.clear();
// alert("Todos los datos han sido borrados");
// localStorage.setItem("Partidas");
// }
// });
document.getElementById("jugarAgain").addEventListener("click", function (event) {
event.preventDefault();
window.location.href = "./quiz.html"
games = JSON.parse(localStorage.getItem("Partidas"))
});
//--Giancarlo
document.addEventListener("DOMContentLoaded", function() {
// Botón de inicio de sesión
let buttonLogin = document.getElementById('toLogin');
if (buttonLogin) {
buttonLogin.addEventListener('click', function() {
console.log('Botón de login clicado!');
location.href = './login.html'; // Cambia la ruta si es necesario
});
} else {
console.error('No se encontró el botón con ID toLogin');
}
// Botón "Entrar"
let buttonQuiz = document.getElementById('toQuiz');
if (buttonQuiz) {
buttonQuiz.addEventListener('click', function(event) {
event.preventDefault(); // Evita el envío del formulario
console.log('Botón de quiz clicado!');
window.location.href = './quiz.html'; // Cambia la ruta si es necesario
});
} else {
console.error('No se encontró el botón con ID toQuiz');
}
// Función para borrar un contacto
function borrarContacto(indice) {
let contactos = obtenerContactos();
contactos.splice(indice, 1); // quitar el contacto de la lista
localStorage.setItem("contactos", JSON.stringify(contactos)); // guardar la nueva lista en el almacenamiento local
mostrarContactos(); // volver a mostrar la lista de contactos actualizada
}
// Evento para borrar todos los contactos
let botonBorrarTodos = document.getElementById('botonBorrarTodos'); // Asegúrate de que este ID esté correcto
if (botonBorrarTodos) {
botonBorrarTodos.addEventListener("click", function() {
localStorage.removeItem("contactos"); // quitar todos los contactos del almacenamiento local
mostrarContactos(); // limpiar la lista en la pantalla
});
}
});
//c espacio 17/10
//----------MUSICA MAESTRO----------------
const musicaFondo = new Audio('/media/loopquizproject.mp3');
musicaFondo.loop = true; // Opcional: para que la música se repita
if (window.location.href.includes('quiz.html')) {
function iniciarMusica() {
musicaFondo.play().catch(error => {
console.error("No se pudo reproducir la música:", error);
});
}
iniciarMusica();
// Detener la música si se navega a otra página (opcional)
window.addEventListener('beforeunload', () => {
musicaFondo.pause();
musicaFondo.currentTime = 0; // Reiniciar la música al inicio
});
}