diff --git a/webapp/src/components/FirstGame.js b/webapp/src/components/FirstGame.js index 003a5be6..d3789cf6 100644 --- a/webapp/src/components/FirstGame.js +++ b/webapp/src/components/FirstGame.js @@ -7,9 +7,9 @@ import axios from 'axios'; import { json } from 'react-router-dom'; import { useLocation } from 'react-router-dom'; - +const apiEndpoint = 'http://localhost:8007'; const Quiz = () => { - const questions = useLocation().state.questions; + var questions = useLocation().state.questions; const [currentQuestionIndex, setCurrentQuestionIndex] = React.useState(0); const [selectedOption, setSelectedOption] = React.useState(null); @@ -19,7 +19,48 @@ const Quiz = () => { return new Promise(resolve => setTimeout(resolve, ms)); }; + + function shuffleArray(array) { + // Crea una copia del array original + const shuffledArray = [...array]; + + // Recorre el array desde el último elemento hasta el primero + for (let i = shuffledArray.length - 1; i > 0; i--) { + // Genera un índice aleatorio entre 0 y el índice actual + const randomIndex = Math.floor(Math.random() * (i + 1)); + + // Intercambia el elemento actual con el elemento del índice aleatorio + const temp = shuffledArray[i]; + shuffledArray[i] = shuffledArray[randomIndex]; + shuffledArray[randomIndex] = temp; + } + + // Devuelve el array barajado + return shuffledArray; + } + + + const getQuestions = async () => { + try { + const response = await axios.get(`${apiEndpoint}/questions?n_preguntas=${1}`); + console.log(response.data.length) + for (var i = 0; i < response.data.length; i++) { + var possibleAnswers = [response.data[i].respuesta_correcta, response.data[i].respuestas_incorrectas[0], response.data[i].respuestas_incorrectas[1], response.data[i].respuestas_incorrectas[2]] + possibleAnswers = shuffleArray(possibleAnswers) + questions.push({ + question: response.data[i].pregunta, + options: possibleAnswers, + correctAnswer: response.data[i].respuesta_correcta + }) + } + } catch (error) { + console.error(error); + } + console.log(questions) +}; + const checkAnswer = async (option) => { + getQuestions() setIsCorrect(option === questions[currentQuestionIndex].correctAnswer); setSelectedOption(option); @@ -39,6 +80,8 @@ const Quiz = () => { if (questions.length-1 !== currentQuestionIndex) { setCurrentQuestionIndex((prevIndex) => prevIndex + 1); } + setIsCorrect(false) + };