Skip to content

Commit

Permalink
Merge branch 'webapp_interface' of https://github.com/Arquisoft/wiq_es6c
Browse files Browse the repository at this point in the history
 into webapp_interface
  • Loading branch information
alegarman2002 committed Apr 27, 2024
2 parents 87b4817 + 277f9c9 commit 9cdf077
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 27 deletions.
10 changes: 0 additions & 10 deletions webapp/src/components/FirstGame.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,9 @@ const Quiz = () => {


console.log("Todas las preguntas", allQuestions)
// console.log(option === questions[currentQuestionIndex].correctAnswer)
isCorrect = (option === allQuestions[currentQuestionIndex].correctAnswer);

changeButtons("true")
// changeButtons(true);

const numberAnswer = allQuestions[currentQuestionIndex].options.indexOf(allQuestions[currentQuestionIndex].correctAnswer)
const botonCorrecta = document.getElementById('option-' + numberAnswer)
Expand Down Expand Up @@ -114,18 +112,10 @@ const Quiz = () => {

const botonIncorrecta = document.getElementById('option-' + allQuestions[currentQuestionIndex].options.indexOf(option))

// console.log(haveFailedQuestion)
// console.log(isCorrect)
if (!isCorrect) {
console.log("Entramos en el correct")
// console.log(isCorrect)
botonIncorrecta.style.backgroundColor = 'red'
// console.log("Entramos a cambiar")
// haveFailedQuestion = true;

// console.log("Despues de modificar los valores")
} else {
// getQuestions()
points = points += 100;
}

Expand Down
5 changes: 4 additions & 1 deletion webapp/src/components/Util.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ function shuffleArray(array) {
}

function secureRandomNumber(max) {
if (!window.crypto) {
return Math.floor(Math.random() * max);
}
const randomBytes = new Uint32Array(1);
window.crypto.getRandomValues(randomBytes);
return randomBytes[0] % max;
}

export {shuffleArray}
export {shuffleArray, secureRandomNumber}
113 changes: 113 additions & 0 deletions webapp/src/components/game/Calculator.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import React, { useState, useEffect } from 'react';
import { shuffleArray, secureRandomNumber } from '../Util';
import { Container, Typography, Box, LinearProgress} from '@mui/material';
import { Footer } from '../footer/Footer';
import { Nav } from '../nav/Nav';

const Calculator = () => {

const [question, setQuestion] = useState(null);

useEffect(() => {
const newQuestion = generateQuestion();
setQuestion(newQuestion);
}, []);


function generateQuestion() {
const num1 = secureRandomNumber(10) + 1;
const num2 = secureRandomNumber(10) + 1;
const operator = ['+', '-', 'x', '÷'][secureRandomNumber(3)];
let correctAnswer;

switch (operator) {
case '+':
correctAnswer = num1 + num2;
break;
case '-':
correctAnswer = num1 - num2;
break;
case 'x':
correctAnswer = num1 * num2;
break;
case '÷':
correctAnswer = Math.round(num1 / num2);
break;
}

const options = [correctAnswer];
while (options.length < 4) {
const option = secureRandomNumber(100) + 1;
if (!options.includes(option)) {
options.push(option);
}
}

shuffleArray(options);
return {
q: `${num1} ${operator} ${num2}`,
options: options,
correctAnswer: correctAnswer
};
}


//CAMBIAR ESTO EN FUNCIÓN DE CÓMO QUERAMOS QUE SEA EL JUEGO
const handleOptionClick = (selectedAnswer) => {
if (selectedAnswer === question.correctAnswer) {
alert('¡Respuesta correcta!');
} else {
alert('Respuesta incorrecta. ¡Inténtalo de nuevo!');
}
const newQuestion = generateQuestion();
setQuestion(newQuestion);
};


return (
<>
<Nav />
<Container component="main" maxWidth="xl" sx={{ marginTop: 4 }}>

<div className="questionStructure">

<div class="questionCalculator">

<Typography class="questionText" component="h1" variant="h5" sx={{ textAlign: 'center' }}>
{setQuestion(generateQuestion())}
{question.q}
</Typography>

</div>

<div class="allAnswers">
{question.options.map((option, index) => (
<div key={index} >
<Button
id={`option-${index}`}
value={option}
onClick={() => handleOptionClick(option)}
text={option}
/>
</div>
)
)}
</div>
</div>

{/*
<Box sx={{
width: '100%',
padding: 3}}>
<LinearProgress id='progress'color="secondary" variant={"determinate"} value={remTime} />
</Box>
*/}

</Container>
<Footer />
</>
);
};

export default Calculator;
47 changes: 47 additions & 0 deletions webapp/src/components/game/Calculator.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { render, screen, fireEvent } from '@testing-library/react';
import { ContextFun } from '../Context';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { BrowserRouter as Router } from 'react-router-dom';
import Calculator from './Calculator';

const mockAxios = new MockAdapter(axios);

describe("Calculator game", () => {

beforeEach(() => {
mockAxios.reset();
});

test("renders Calculator",async () => {
render(
<ContextFun>
<Router>
<Calculator/>
</Router>
</ContextFun>
);

// Comprobamos que el número de elementos sea 3
let operation = document.getElementsByClassName('questionStructure')[0][0];
const separatedText = operation.split(' ');
expect(separatedText.length).toBeGreaterThan(3);
// Comprobamos que el número de respuestas posibles sea 4
let answers = document.getElementsByClassName('questionStructure')[1];
expect(answers).toHaveLength(4);
// Tratamos de hacer la operación
let number1 = separatedText[0];
let number2 = separatedText[2];
let op = separatedText[1];
let result;
switch (op) {
case '+': result = number1 + number2; break;
case '-': result = number1 - number2; break;
case 'x': result = number1 * number2; break;
case '÷': result = Math.round(number1 / number2); break;
}
expect(screen.getByText(result)).toBeInTheDocument();
});

});

20 changes: 10 additions & 10 deletions webapp/src/components/game/GameConfiguration.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ const GameConfiguration = () => {
}

function formatearTopics() {
var topicsFormated = ''
let topicsFormated = '';

for (var i = 0; i < tematicasSeleccionadas.length; i++) {
topicsFormated += ("&tema=" + tematicasSeleccionadas[i])
for (const tema of tematicasSeleccionadas) {
topicsFormated += `&tema=${tema}`;
}

return topicsFormated
Expand All @@ -95,18 +95,18 @@ const GameConfiguration = () => {
try {
const topicsFormated = formatearTopics()
const response = await axios.get(`${apiEndpoint}/questions?n_preguntas=${numPreguntas}&n_respuestas=${numRes}${topicsFormated}`);
for (var i = 0; i < response.data.length; i++) {
var possibleAnswers = [response.data[i].respuesta_correcta]
for (var j = 0; j < response.data[i].respuestas_incorrectas.length; j++) {
possibleAnswers.push(response.data[i].respuestas_incorrectas[j])
for (const pregunta of response.data) {
let possibleAnswers = [pregunta.respuesta_correcta]
for (const respuestaIncorrecta of pregunta.respuestas_incorrectas) {
possibleAnswers.push(respuestaIncorrecta)
}
possibleAnswers = shuffleArray(possibleAnswers)
questions.push({
question: response.data[i].pregunta,
question: pregunta.pregunta,
options: possibleAnswers,
correctAnswer: response.data[i].respuesta_correcta
correctAnswer: pregunta.respuesta_correcta
})
}
}
} catch (error) {
console.error(error);
}
Expand Down
4 changes: 2 additions & 2 deletions webapp/src/components/game/GameConfiguration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import MockAdapter from 'axios-mock-adapter';
import { BrowserRouter as Router } from 'react-router-dom';
import GameConfiguration from './GameConfiguration';

const request = require('supertest');
//const request = require('supertest');
const mockAxios = new MockAdapter(axios);

describe("Game Configuration", () => {
Expand Down Expand Up @@ -51,7 +51,7 @@ describe("Game Configuration", () => {
);

//NUMBER OF QUESTIONS
const input = getByLabelText('Número de preguntas:');
let input = getByLabelText('Número de preguntas:');
fireEvent.change(input, { target: { value: '5' } });
expect(input.value).toBe('5');
// try to put number of questions = 0
Expand Down
4 changes: 0 additions & 4 deletions webapp/src/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,6 @@ code {
flex-wrap: wrap;
}

#root{

}

#root > main > h1{
text-align: center;
}
Expand Down

0 comments on commit 9cdf077

Please sign in to comment.