Skip to content

Commit

Permalink
Updated the game so we can have unlimited questions
Browse files Browse the repository at this point in the history
  • Loading branch information
alegarman2002 committed Mar 13, 2024
1 parent 420ef2b commit b3f302a
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions webapp/src/components/FirstGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);

Expand All @@ -39,6 +80,8 @@ const Quiz = () => {
if (questions.length-1 !== currentQuestionIndex) {
setCurrentQuestionIndex((prevIndex) => prevIndex + 1);
}
setIsCorrect(false)


};

Expand Down

0 comments on commit b3f302a

Please sign in to comment.