//this would be the object shape for storing the questions //you can change the questions to your own taste or even add more questions.. var numpreguntas = 2 var questions = [] var erradas = [] let shuffledQuestions = [] //empty array to hold shuffled selected questions out of all available questions function usuario() { document.getElementById('quiz').style.display = "none"; document.getElementById('login-modal').style.display = "flex"; } function evaluar() { document.getElementById('quiz').style.display = "flex"; NextQuestion(0); } function Login() { const Susuario = document.getElementById("username").value; const Sclave = document.getElementById("password").value; fetch('http://186.118.170.98:1000/mensaje', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ accion: 'LOGIN', username: Susuario, password: Sclave }) }) .then(response => response.json()) .then(data => { // Extraer cada valor del objeto JSON const respuesta = data['reply']; if (respuesta === 'false') { alert('Clave incorrecta!'); } if (respuesta === 'true') { document.getElementById('login-modal').style.display = "none"; document.getElementById('mainmenu-modal').style.display = "flex"; } }) .catch(error => { console.error('Error:', error); }); } function handleQuestions() { //function to shuffle and push 10 questions to shuffledQuestions array //app would be dealing with 10questions per session while (shuffledQuestions.length <= numpreguntas-1) { const random = questions[Math.floor(Math.random() * questions.length)] if (!shuffledQuestions.includes(random)) { shuffledQuestions.push(random) } } } let questionNumber = 1 //holds the current question number let playerScore = 0 //holds the player score let wrongAttempt = 0 //amount of wrong answers picked by player let indexNumber = 0 //will be used in displaying next question // function for displaying next question in the array to dom //also handles displaying players and quiz information to dom function NextQuestion(index) { handleQuestions() const currentQuestion = shuffledQuestions[index] document.getElementById("question-number").innerHTML = questionNumber document.getElementById("player-score").innerHTML = playerScore document.getElementById("display-question").innerHTML = currentQuestion.question; document.getElementById("option-one-label").innerHTML = currentQuestion.optionA; document.getElementById("option-two-label").innerHTML = currentQuestion.optionB; document.getElementById("option-three-label").innerHTML = currentQuestion.optionC; document.getElementById("option-four-label").innerHTML = currentQuestion.optionD; } function checkForAnswer() { const currentQuestion = shuffledQuestions[indexNumber] //gets current Question const currentQuestionAnswer = currentQuestion.correctOption //gets current Question's answer const options = document.getElementsByName("option"); //gets all elements in dom with name of 'option' (in this the radio inputs) let correctOption = null options.forEach((option) => { if (option.value === currentQuestionAnswer) { //get's correct's radio input with correct answer correctOption = option.labels[0].id } }) //checking to make sure a radio input has been checked or an option being chosen if (options[0].checked === false && options[1].checked === false && options[2].checked === false && options[3].checked == false) { document.getElementById('option-modal').style.display = "flex" } //checking if checked radio button is same as answer options.forEach((option) => { if (option.checked === true && option.value === currentQuestionAnswer) { document.getElementById(correctOption).style.backgroundColor = "green" playerScore++ //adding to player's score indexNumber++ //adding 1 to index so has to display next question.. //set to delay question number till when next question loads setTimeout(() => { questionNumber++ }, 1000) } else if (option.checked && option.value !== currentQuestionAnswer) { //registrar Id de la pregunta mal contestada erradas.push(currentQuestion.idpregunta); const wrongLabelId = option.labels[0].id document.getElementById(wrongLabelId).style.backgroundColor = "red" document.getElementById(correctOption).style.backgroundColor = "green" wrongAttempt++ //adds 1 to wrong attempts indexNumber++ //set to delay question number till when next question loads setTimeout(() => { questionNumber++ }, 1000) } }) } //called when the next button is called function handleNextQuestion() { checkForAnswer() //check if player picked right or wrong option unCheckRadioButtons() //delays next question displaying for a second just for some effects so questions don't rush in on player setTimeout(() => { if (indexNumber <= numpreguntas-1) { //displays next question as long as index number isn't greater than 9, remember index number starts from 0, so index 9 is question 10 NextQuestion(indexNumber) } else { handleEndGame()//ends game if index number greater than 9 meaning we're already at the 10th question } resetOptionBackground() }, 1000); } //sets options background back to null after display the right/wrong colors function resetOptionBackground() { const options = document.getElementsByName("option"); options.forEach((option) => { document.getElementById(option.labels[0].id).style.backgroundColor = "" }) } // unchecking all radio buttons for next question(can be done with map or foreach loop also) function unCheckRadioButtons() { const options = document.getElementsByName("option"); for (let i = 0; i < options.length; i++) { options[i].checked = false; } } // function for when all questions being answered function handleEndGame() { let remark = null let remarkColor = null // condition check for player remark and remark color if (playerScore <= 3) { remark = "Bad Grades, Keep Practicing." remarkColor = "red" } else if (playerScore >= 4 && playerScore < 7) { remark = "Average Grades, You can do better." remarkColor = "orange" } else if (playerScore >= 7) { remark = "Excellent, Keep the good work going." remarkColor = "green" } const playerGrade = (playerScore / numpreguntas) * 100 //data to display to score board document.getElementById('remarks').innerHTML = remark document.getElementById('remarks').style.color = remarkColor document.getElementById('grade-percentage').innerHTML = playerGrade document.getElementById('wrong-answers').innerHTML = wrongAttempt document.getElementById('right-answers').innerHTML = playerScore document.getElementById('score-modal').style.display = "flex" } //closes score modal, resets game and reshuffles questions function closeScoreModal() { //Enviar resultado de la evaluacion al servidor const Susuario = document.getElementById("username").value; const Stema = document.getElementById("listadotemas").options[document.getElementById("listadotemas").selectedIndex].text; fetch('http://186.118.170.98:1000/mensaje', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ tema : Stema, accion : 'REGISTRARRESULTADOEVALUACION', username: Susuario, nrespcorrectas: playerScore, nresperradas: wrongAttempt, resperradas: erradas }) }) .then(response => response.json()) .then(data => { // Extraer cada valor del objeto JSON const respuesta = data['reply']; alert('Respuestas registradas!'); }) .catch(error => { console.error('Error:', error); }); questionNumber = 1 playerScore = 0 wrongAttempt = 0 indexNumber = 0 shuffledQuestions = [] ERRADAS = [] document.getElementById('quiz').style.display = "none"; document.getElementById('score-modal').style.display = "none"; document.getElementById('mainmenu-modal').style.display = "flex"; } function escogertemaevaluacion() { // consultar los temas disponibles const Susuario = document.getElementById("username").value; fetch('http://186.118.170.98:1000/mensaje', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ accion: 'TEMASEVALUACION', username: Susuario }) }) .then(response => response.json()) .then(data => { // Extraer cada valor del objeto JSON const respuesta = data['temas']; //limpia el select actual document.getElementById('listadotemas').innerHTML = ""; // Agregar temas al select respuesta.forEach((op) => { let newOption = new Option(op,'Option Value'); const select = document.getElementById('listadotemas'); select.add(newOption,undefined); }) }) .catch(error => { console.error('Error:', error); }); document.getElementById('mainmenu-modal').style.display = "none"; document.getElementById('temasevaluacion-modal').style.display = "flex"; } function cargarevaluacion(){ const Susuario = document.getElementById("username").value; const Stema = document.getElementById("listadotemas").options[document.getElementById("listadotemas").selectedIndex].text; //cargar cuestionario fetch('http://186.118.170.98:1000/mensaje', { method: 'POST', headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: new URLSearchParams({ accion: 'CUESTIONARIO', tema: Stema, username: Susuario }) }) .then(response => response.json()) .then(data => { questions = data['preguntas']; numpreguntas = data['npreguntas']; if ( numpreguntas > 10 ){ numpreguntas = 10; } document.getElementById('nquestion-number').innerHTML = numpreguntas; document.getElementById('temasevaluacion-modal').style.display = "none"; evaluar(); }) .catch(error => { console.error('Error:', error); }); } function descargarmaterialestudio(){ const currentQuestion = shuffledQuestions[indexNumber]; //gets current Question const url = currentQuestion.materialdeestudio; //gets current Question's answer window.open(url); } //function to close warning modal function closeOptionModal() { document.getElementById('option-modal').style.display = "none" }