Skip to content

Commit

Permalink
Merge pull request #53 from Arquisoft/carlos
Browse files Browse the repository at this point in the history
Basic funcionality of the game done (generation of questions and check if the selected anser is correct or no)
  • Loading branch information
baraganio authored Mar 5, 2024
2 parents 3ae88c6 + dce4899 commit 19b8584
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 115 deletions.
14 changes: 5 additions & 9 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ app.get('/health', (_req, res) => {

app.post('/login', async (req, res) => {
try {
// Crea una peticion a la url (le llegará a auth-service.js) con la opcion /login
// y los parametros req.body
const authResponse = await axios.post(authServiceUrl+'/login', req.body);
// Almacena en un Json la respuesta de la anterior peticion
res.json(authResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand All @@ -36,10 +33,7 @@ app.post('/login', async (req, res) => {

app.post('/adduser', async (req, res) => {
try {
// Crea una peticion a la url (le llegará a user-service.js) con la opcion /login
// y los parametros req.body
const userResponse = await axios.post(userServiceUrl+'/adduser', req.body);
// Almacena en un Json la respuesta de la anterior peticion
res.json(userResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand All @@ -48,10 +42,12 @@ app.post('/adduser', async (req, res) => {

app.post('/createquestion', async (req, res) => {
try {
// Crea una peticion a la url (le llegará a creation-service.js) con la opcion /login
// y los parametros req.body
// Create a petition to the URL (le llegará a creation-service.js) with the option /createquestion and the req.body params
console.log("salgo de gateway hacia creation");
const questionResponse = await axios.post(creationServiceUrl+'/createquestion', req.body);
// Almacena en un Json la respuesta de la anterior peticion
console.log("vengo de creation y estoy en gateway");
console.log(questionResponse.status);
// Return a json response with what we obtained on the petition
res.json(questionResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
Expand Down
107 changes: 54 additions & 53 deletions questions/creationservice/creation-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,67 +7,68 @@ const port = 8005;

app.use(express.json());

const query = async (SPARQL) => {
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(SPARQL)}&format=json`;

const response = await fetch(apiUrl, {
headers: {
'Accept': 'application/json'
}
});

if (!response.ok) {
console.error('Error al realizar la consulta a Wikidata:', response.statusText);
return;
// It will be the country of the question
var country= "";
// It will be the correct capital of the question
var capitalCorrect = "";
// It will be the different options for the answers
var capitalOptions = [];

// Recieves the information of the query and select wich data use on the question (country and capitals)
function getQuestionInfo(info){
capitalOptions = [];
fourRows = [];
const numEles = info.length;

// Select 4 random rows of the data
for (let i = 0; i<4; i++){
var indexRow = Math.floor(Math.random() * numEles);
fourRows.push(info[indexRow]);
// Store the 4 posible answers
capitalOptions.push(info[indexRow].capitalLabel.value);
}

const datos = await response.json();

const resultados = datos.results.bindings.map((resultado) => {
const resultadoFormateado = {};
Object.keys(resultado).forEach((clave) => {
resultadoFormateado[clave] = resultado[clave].value;
});

return resultadoFormateado;
});

return resultados;
};

const surroundWithCache = (func) => {
let cache = {};

return async (param) => {
if (param in cache) {
return cache[param];
}

let res = await func(param);

cache[param] = res;

return res;
};
};

const cachedQuery = surroundWithCache(query);

// Select the row where it will extract the country and capital
const indexQuestion = Math.floor(Math.random() * 4);
// Store the country choosen and its capital
country=fourRows[indexQuestion].countryLabel.value;
capitalCorrect = fourRows[indexQuestion].capitalLabel.value;
}

app.post('/createquestion', async (req, res) => {
const sparqlQuery = 'SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel WHERE { ?country wdt:P31 wd:Q6256. ?country wdt:P36 ?capital. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}';
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}&format=json`;

try {
const data = await cachedQuery(sparqlQuery);
const numEles = data.length;

if (numEles > 0) {
const index = Math.floor(Math.random() * numEles);
const result = data[index];
res.json(result);
} else {
console.log('No se encontraron resultados en Wikidata.');
res.status(404).json({ error: 'No se encontraron resultados en Wikidata.' });
// Makes the petition to the url
const response = await fetch(apiUrl, {
headers: {
'Accept': 'application/json'
}
});

// Check if everything was good on the petition
if (!response.ok) {
console.error('Error al realizar la consulta a Wikidata:', response.statusText);
return;
}

// Parse the response
const data = await response.json();

// Send the parsed response to be selected
getQuestionInfo(data.results.bindings);

// Declare what will be return
solution = {
responseCountry : country,
responseCapitalCorrect : capitalCorrect,
responseCapitalOptions : capitalOptions
};

// Return the resoult with a 200 status
res.status(200).json(solution);
} catch (error) {
console.error('Error al realizar la consulta:', error);
res.status(500).json({ error: 'Internal Server Error' });
Expand Down
83 changes: 30 additions & 53 deletions webapp/src/components/Game.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,39 @@

import React, { useState } from 'react';
import axios from 'axios';
import { Container, Typography, Button, Paper } from '@mui/material';

const Game = () => {
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const [pais, setpais] = useState('');
const [capitalCorrecta, setcapital] = useState('');
const [capitalIcnorrecta1, setcapitalIcnorrecta1] = useState('');
const [capitalIcnorrecta2, setcapitalIcnorrecta2] = useState('');
const [capitalIcnorrecta3, setcapitalIcnorrecta3] = useState('');
const [country, setCountry] = useState('');
const [capitalCorrect, setCapitalCorrect] = useState('');
const [capitalOptions, setcapitalOptions] = useState([]);

// Esta es la llamada al servicio de generar las preguntas
// This method will call the create question service
const handleShowQuestion = async () => {
try{
// Se declara esta variable unicamente para probar cosas con ella en la peticion
const eyou = "aa"
// Se hace una peticion a la api (llega a gateway-service.js) con la opcion createquestion
// y los parametros de entrada aa, aa
const response = await axios.post(`${apiEndpoint}/createquestion`, { eyou, eyou });
console.log(response);
// It makes a petition to the api and store the response
const response = await axios.post(`${apiEndpoint}/createquestion`, { });
// Extract all the info of the response and store it
setCountry(response.data.responseCountry);
setCapitalCorrect(response.data.responseCapitalCorrect);
setcapitalOptions(response.data.responseCapitalOptions);
}catch (error){
console.error('Error:', error);
}
}

// TODO ESTO ES LO QUE ESTA COMENTADO EN CREATION-SERVICE.JS
// CREO QUE DEBERIA IR ALLI PERO COMO NO FUNCIONA LO PROBE AQUI
const deberiaIrEnelServicio = async () => {
const sparqlQuery = 'SELECT DISTINCT ?country ?countryLabel ?capital ?capitalLabel WHERE { ?country wdt:P31 wd:Q6256. ?country wdt:P36 ?capital. SERVICE wikibase:label {bd:serviceParam wikibase:language "[AUTO_LANGUAGE],es".}}';
const apiUrl = `https://query.wikidata.org/sparql?query=${encodeURIComponent(sparqlQuery)}`;
const headers = { "Accept": "application/json" }
const respuestaWikidata = await fetch(apiUrl, {headers});
if (respuestaWikidata.ok) {
const data = await respuestaWikidata.json();
const numEles = data.results.bindings.length;
const indexCapCorre = Math.floor(Math.random() * numEles);
const result = data.results.bindings[indexCapCorre];
setpais(result.countryLabel.value);
setcapital(result.capitalLabel.value);

const indexCapIncorre1 = Math.floor(Math.random() * numEles);
const indexCapIncorre2 = Math.floor(Math.random() * numEles);
const indexCapIncorre3 = Math.floor(Math.random() * numEles);
setcapitalIcnorrecta1(data.results.bindings[indexCapIncorre1].capitalLabel.value);
setcapitalIcnorrecta2(data.results.bindings[indexCapIncorre2].capitalLabel.value);
setcapitalIcnorrecta3(data.results.bindings[indexCapIncorre3].capitalLabel.value);
} else {
console.error("Error al realizar la consulta en Wikidata. Estado de respuesta:", respuestaWikidata.status);
// Method that checks if the answer clicked is the correct one
const handleAnswerClick = (option, index) => {
// Get what component is the button to change its color later
//const button = document.getElementById(`button_${index}`);
if(option === capitalCorrect){
//button.style.backgroundColor = "green";
alert("CORRECTO");
}else{
//button.style.backgroundColor = "red";
alert("INCORRECTO");
}
}

Expand All @@ -58,27 +44,18 @@ const Game = () => {
Saber y Ganar Juego
</Typography>
<Typography variant="body1" paragraph>
Pregunta: ¿Cuál es la capital de {pais}?
Pregunta: ¿Cuál es la capital de {country}?
</Typography>
{/* Botones de opción */}
<Button variant="outlined" style={{ margin: '0.5rem' }}>
{capitalCorrecta}
</Button>
<Button variant="outlined" style={{ margin: '0.5rem' }}>
{capitalIcnorrecta1}
</Button>
<Button variant="outlined" style={{ margin: '0.5rem' }}>
{capitalIcnorrecta2}
</Button>
<Button variant="outlined" style={{ margin: '0.5rem' }}>
{capitalIcnorrecta3}
</Button>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', marginTop: '20px' }}>
{capitalOptions.map((option, index) => (
<Button id={`button_${index}`} key={index} variant="contained" color="primary" onClick={() => handleAnswerClick(option,index)} >
{option}
</Button>
))}
</div>
</Paper>
<Button variant="contained" color="primary" onClick={handleShowQuestion}>
Genera pregunta NO FUNCIONA AUNQUE DEBERIA
</Button>
<Button variant="contained" color="primary" onClick={deberiaIrEnelServicio}>
Genera pregunta FUNCIONA
Genera pregunta
</Button>
</Container>
);
Expand Down

0 comments on commit 19b8584

Please sign in to comment.