Skip to content

Commit

Permalink
Merge pull request #89 from Arquisoft/stats-calculadora
Browse files Browse the repository at this point in the history
Stats modo Calculadora humana
  • Loading branch information
CANCI0 authored Apr 5, 2024
2 parents a573e15 + 07935ce commit 417d562
Show file tree
Hide file tree
Showing 7 changed files with 123 additions and 48 deletions.
2 changes: 1 addition & 1 deletion statsservice/model/stats-getter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ class StatsForUser {

async getStatsForUser(username,gamemode){
var statsJSON=null;
if(gamemode=="clasico" || gamemode=="bateria"){
if(gamemode=="clasico" || gamemode=="bateria" || gamemode=="calculadora"){
statsJSON = await this.getStats(username,gamemode);
}
return statsJSON;
Expand Down
10 changes: 6 additions & 4 deletions statsservice/stats-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,14 @@ app.post("/saveGame", async (req, res) => {
const gamemode = req.body.gameMode;
const gameData = req.body.gameData;

if (gamemode == "clasico" || gamemode == "bateria") {
if (gamemode == "clasico" || gamemode == "bateria" || gamemode =="calculadora") {
// Buscar las estadísticas existentes del usuario y modo de juego
let stats = await Stats.findOne({ username: username, gamemode: gamemode });

if (!stats) {
var ratioCorrect=0;
if(gameData.incorrectAnswers + gameData.correctAnswers>0){
ratioCorrect=(gameData.correctAnswers / (gameData.incorrectAnswers + gameData.correctAnswers)) * 100;
}
// Si no existen estadísticas, crear un nuevo documento
stats = new Stats({
username: username,
Expand All @@ -41,10 +44,9 @@ app.post("/saveGame", async (req, res) => {
totalPoints: gameData.points,
totalCorrectQuestions: gameData.correctAnswers,
totalIncorrectQuestions: gameData.incorrectAnswers,
ratioCorrect: (gameData.correctAnswers / (gameData.incorrectAnswers + gameData.correctAnswers)) * 100,
ratioCorrect: ratioCorrect,
avgTime: gameData.avgTime,
});

await stats.save();
} else {

Expand Down
2 changes: 1 addition & 1 deletion webapp/src/pages/Bateria/Bateria.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ const JuegoPreguntas = () => {
}, 1000);
return () => clearInterval(timer);
// eslint-disable-next-line
}, [tiempoRestante]);
}, [tiempoRestante, preguntasCorrectas, preguntasFalladas]);

useEffect(() => {
if (juegoTerminado && tiempoMedio !== 0) {
Expand Down
49 changes: 48 additions & 1 deletion webapp/src/pages/Calculadora/Calculadora.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Nav from "../../components/Nav/Nav.js";
import Footer from "../../components/Footer/Footer.js";
import { Link } from "react-router-dom";
import { Box, Flex, Heading, Button, Input } from "@chakra-ui/react";
import axios from 'axios';

const generateRandomOperation = () => {
let operators = ["+", "-", "*", "/"];
Expand Down Expand Up @@ -36,6 +37,7 @@ function findDivisors(num) {

const CalculadoraHumana = () => {
const TIME = 60;
const URL = process.env.REACT_APP_API_ENDPOINT || "http://localhost:8000";

const [valSubmit, setValSubmit] = useState("");
const [puntuacion, setPuntuacion] = useState(0);
Expand All @@ -44,16 +46,22 @@ const CalculadoraHumana = () => {
const [juegoTerminado, setJuegoTerminado] = useState(false);
const [progressPercent, setProgressPercent] = useState(100);

const [tiempoMedio, setTiempoMedio] = useState(0);

useEffect(() => {
if (tiempoRestante === 0) {
setJuegoTerminado(true);
if(puntuacion>0){
const tMedio=TIME/puntuacion;
setTiempoMedio(tMedio);
}
}
const timer = setInterval(() => {
setTiempoRestante((prevTiempo) => (prevTiempo <= 0 ? 0 : prevTiempo - 1));
}, 1000);
return () => clearInterval(timer);
// eslint-disable-next-line
}, [tiempoRestante]);
}, [tiempoRestante, puntuacion]);

useEffect(() => {
setProgressPercent((tiempoRestante / TIME) * 100);
Expand All @@ -68,6 +76,41 @@ const CalculadoraHumana = () => {
// eslint-disable-next-line
}, [tiempoRestante]);

useEffect(() => {
if (juegoTerminado && tiempoMedio !== 0) {
guardarPartida();
}
// eslint-disable-next-line
}, [juegoTerminado, tiempoMedio]);

const guardarPartida = async () => {

const username = localStorage.getItem("username");
const newGame = {
username: username,
gameMode: "calculadora",
gameData: {
correctAnswers: 0,
incorrectAnswers: 0,
points: puntuacion,
avgTime: tiempoMedio,
},
};
try {
const response = await axios.post(URL + '/saveGame', newGame);
console.log("Solicitud exitosa:", response.data);

} catch (error) {
console.error('Error al guardar el juego:', error);
}
try {
const response = await axios.post(URL + "/saveGameList", newGame);
console.log("Solicitud exitosa:", response.data);
} catch (error) {
console.error("Error al guardar el juego:", error);
}
}

const handleAnswer = (valSubmit) => {
setValSubmit("");
valSubmit = Number(valSubmit);
Expand All @@ -78,6 +121,10 @@ const CalculadoraHumana = () => {
let newOperation = generateOperation(valSubmit);
setOperation(newOperation);
} else {
if(puntuacion>0){
const tMedio=(TIME-tiempoRestante)/puntuacion;
setTiempoMedio(tMedio);
}
setJuegoTerminado(true);
}
};
Expand Down
14 changes: 7 additions & 7 deletions webapp/src/pages/Perfil/Perfil.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ const Perfil = () => {
</Thead>
<Tbody>
{userData.games.slice(0, 10).map((game, index) => (
<Tr key={index}>
<Td>{game.gamemode}</Td>
<Td>{game.correctAnswers}</Td>
<Td>{game.incorrectAnswers}</Td>
<Td>{game.points}</Td>
<Td>{parseFloat(game.avgTime).toFixed(2)} segundos</Td>
</Tr>
<Tr key={index}>
<Td>{game.gamemode}</Td>
<Td>{game.gamemode === 'calculadora' ? '-' : game.correctAnswers}</Td>
<Td>{game.gamemode === 'calculadora' ? '-' : game.incorrectAnswers}</Td>
<Td>{game.points}</Td>
<Td>{parseFloat(game.avgTime).toFixed(2)} segundos</Td>
</Tr>
))}
</Tbody>
</Table>
Expand Down
20 changes: 17 additions & 3 deletions webapp/src/pages/Ranking/Ranking.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ const Ranking = () => {
return "Clásico";
} else if(gamemode === "bateria"){
return "Batería de sabios";
} else if(gamemode === "calculadora"){
return "Calculadora humana";
}
return gamemode;
};
Expand All @@ -59,6 +61,7 @@ const Ranking = () => {
case "totalPoints":
return "Puntos totales";
case "ratioCorrect":
if (gamemode === "calculadora") return null;
return "Ratio de aciertos (%)";
case "avgTime":
return "Tiempo por pregunta (s)";
Expand All @@ -74,6 +77,7 @@ const Ranking = () => {
case "totalPoints":
return stat.totalPoints;
case "ratioCorrect":
if (gamemode === "calculadora") return null;
return Math.round(stat.ratioCorrect * 100) / 100;
case "avgTime":
return Math.round(stat.avgTime * 100) / 100;
Expand Down Expand Up @@ -111,9 +115,12 @@ const Ranking = () => {
<Flex flexDirection="column" rowGap="1rem">
<Heading as="h2">Ranking - modo {getModeName()}</Heading>
<Select id="displaySelector" onChange={handleDisplayChange}>
{displayOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
{displayOptions.map(option => {
if (gamemode === "calculadora" && option.value === "ratioCorrect") {
return null;
}
return <option key={option.value} value={option.value}>{option.label}</option>;
})}
</Select>
<Button
className={gamemode === "clasico" ? "active" : ""}
Expand All @@ -127,6 +134,12 @@ const Ranking = () => {
>
Batería de sabios
</Button>
<Button
className={gamemode === "calculadora" ? "active" : ""}
onClick={() => handleGamemodeChange("calculadora")}
>
Calculadora humana
</Button>
<Table>
<Thead>
<Tr>
Expand All @@ -152,3 +165,4 @@ const Ranking = () => {
export default Ranking;



74 changes: 43 additions & 31 deletions webapp/src/pages/Stats/Stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ const Stats = () => {
setGamemode(mode);
fetchStats(mode);
};


const handleSearch = () => {
fetchStats(gamemode);
Expand All @@ -69,6 +68,8 @@ const Stats = () => {
return "Clásico";
} else if (gamemode === "bateria") {
return "Batería de sabios";
} else if (gamemode === "calculadora") {
return "Calculadora humana";
}
return gamemode;
};
Expand Down Expand Up @@ -139,6 +140,12 @@ const Stats = () => {
>
Batería de sabios
</Button>
<Button
className={gamemode === "calculadora" ? "active" : ""}
onClick={() => handleGamemodeChange("calculadora")}
>
Calculadora humana
</Button>
</Flex>
{stats === null && !isLoading && (
<p mt="10rem">El usuario no ha jugado ninguna partida.</p>
Expand All @@ -162,36 +169,40 @@ const Stats = () => {
</Td>
<Td>{stats.avgPoints.toFixed(2)}</Td>
</Tr>
<Tr>
<Td>
<strong>Puntos totales</strong>
</Td>
<Td>{stats.totalPoints}</Td>
</Tr>
<Tr>
<Td>
<strong>Preguntas correctas totales</strong>
</Td>
<Td>{stats.totalCorrectQuestions}</Td>
</Tr>
<Tr>
<Td>
<strong>Preguntas incorrectas totales</strong>
</Td>
<Td>{stats.totalIncorrectQuestions}</Td>
</Tr>
<Tr>
<Td>
<strong>Porcentaje de aciertos</strong>
</Td>
<Td>{stats.ratioCorrect.toFixed(2)}%</Td>
</Tr>
<Tr>
<Td>
<strong>Tiempo por pregunta (s):</strong>
</Td>
<Td>{stats.avgTime.toFixed(2)}</Td>
</Tr>
<Tr>
<Td>
<strong>Puntos totales</strong>
</Td>
<Td>{stats.totalPoints}</Td>
</Tr>
{gamemode !== "calculadora" && (
<>
<Tr>
<Td>
<strong>Preguntas correctas totales</strong>
</Td>
<Td>{stats.totalCorrectQuestions}</Td>
</Tr>
<Tr>
<Td>
<strong>Preguntas incorrectas totales</strong>
</Td>
<Td>{stats.totalIncorrectQuestions}</Td>
</Tr>
<Tr>
<Td>
<strong>Porcentaje de aciertos</strong>
</Td>
<Td>{stats.ratioCorrect.toFixed(2)}%</Td>
</Tr>
</>
)}
<Tr>
<Td>
<strong>Tiempo por pregunta (s):</strong>
</Td>
<Td>{stats.avgTime.toFixed(2)}</Td>
</Tr>
</Tbody>
</Table>
</div>
Expand All @@ -203,3 +214,4 @@ const Stats = () => {
};

export default Stats;

0 comments on commit 417d562

Please sign in to comment.