Skip to content

Commit

Permalink
Merge pull request #68 from Arquisoft/newstatsservice
Browse files Browse the repository at this point in the history
Separado el ranking a una vista aparte. Arreglados guardado de partida y ranking
  • Loading branch information
iyanfdezz authored Mar 21, 2024
2 parents b236ca3 + 436b27c commit 235e50d
Show file tree
Hide file tree
Showing 9 changed files with 222 additions and 64 deletions.
32 changes: 28 additions & 4 deletions statsservice/model/stats-getter.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,39 @@ class StatsForUser {
ratioCorrect: newRatioCorrect,
avgTime: newAvgTime
};
}
};

async getRanking(gamemode) {
async getRanking(gamemode, filterBy) {
try {
var stats = await Stats.find({gamemode:gamemode}).sort({ avgPoints: -1 }).limit(10);
let sortBy, displayField;

switch (filterBy) {
case "avgPoints":
sortBy = { avgPoints: -1 };
displayField = "avgPoints";
break;
case "totalPoints":
sortBy = { totalPoints: -1 };
displayField = "totalPoints";
break;
case "ratioCorrect":
sortBy = { ratioCorrect: -1 };
displayField = "ratioCorrect";
break;
case "avgTime":
sortBy = { avgTime: -1 };
displayField = "avgTime";
break;
default:
return null;
}

const stats = await Stats.find({ gamemode: gamemode }).sort(sortBy).limit(10);

if (stats && stats.length > 0) {
return stats.map(stat => ({
username: stat.username,
avgPoints: stat.avgPoints
[displayField]: stat[displayField]
}));
} else {
return null;
Expand All @@ -78,6 +101,7 @@ class StatsForUser {
}
}


}

module.exports = StatsForUser;
Expand Down
2 changes: 1 addition & 1 deletion statsservice/stats-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ app.get("/stats", async (req, res) => {

app.get("/ranking", async (req, res) => {
try {
var data = await statsGetter.getRanking(req.query.gamemode);
var data = await statsGetter.getRanking(req.query.gamemode,req.query.filterBy);
res.json(data);

} catch (error) {
Expand Down
2 changes: 2 additions & 0 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Clasico from "./pages/Clasico/Clasico.js";
import Bateria from "./pages/Bateria/Bateria.js";
import WrongRoute from "./pages/WrongRoute/WrongRoute.js";
import Stats from "./pages/Stats/Stats.js";
import Ranking from "./pages/Ranking/Ranking.js";
import "./App.css";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { ProtectedRoute } from "./routers/ProtectedRoute.js";
Expand All @@ -26,6 +27,7 @@ function App() {
<Route path="/home/clasico" element={<Clasico />} />
<Route path="/home/bateria" element={<Bateria />} />
<Route path="/stats" element={<Stats />} />
<Route path="/ranking" element={<Ranking />} />
<Route path="/config" element={<Config />} />
</Route>

Expand Down
10 changes: 6 additions & 4 deletions webapp/src/pages/Bateria/Bateria.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ const JuegoPreguntas = () => {
useEffect(() => {
if (tiempoRestante === 0) {
setJuegoTerminado(true);

if(preguntasCorrectas+preguntasFalladas>0){
const preguntasTotales=preguntasCorrectas+preguntasFalladas;
const tMedio=180/preguntasTotales;
setTiempoMedio(tMedio);
}
guardarPartida();
}
const timer = setInterval(() => {
Expand All @@ -64,9 +68,7 @@ const JuegoPreguntas = () => {
}, [tiempoRestante]);

const guardarPartida = async () => {
if(preguntasCorrectas+preguntasFalladas>0){
setTiempoMedio(180/(preguntasCorrectas+preguntasFalladas));
}

const username = localStorage.getItem("username");
const newGame = {
username: username,
Expand Down
43 changes: 28 additions & 15 deletions webapp/src/pages/Clasico/Clasico.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,8 @@ const JuegoPreguntas = () => {
}, []);

useEffect(() => {
setProgressPercent((tiempoRestante / SECS_PER_QUESTION) * 100);
const roundedProgressPercent = ((tiempoRestante / SECS_PER_QUESTION) * 100).toFixed(2);
setProgressPercent(roundedProgressPercent);

const timer = setInterval(() => {
setTiempoRestante((prevTiempo) =>
Expand Down Expand Up @@ -111,34 +112,46 @@ const JuegoPreguntas = () => {
};

const handleSiguientePregunta = () => {
if (respuestaSeleccionada === preguntaActual.correcta) {
if (respuestaSeleccionada === preguntaActual.correcta) {
const newCorrectQuestions=preguntasCorrectas+1;
setPuntuacion(puntuacion + 1);
setPreguntasCorrectas(preguntasCorrectas + 1);
console.log("bien");
setPreguntasCorrectas(newCorrectQuestions);
console.log("bien")
} else {
setPreguntasFalladas(preguntasFalladas + 1);
console.log("mal");
const newIncorrectQuestions=preguntasFalladas+1;
setPreguntasFalladas(newIncorrectQuestions);
console.log("mal")
}
setTiempoTotal(tiempoTotal+tiempoRestante);
setRespuestaSeleccionada(null);
setTiempoRestante(10);
setProgressPercent(100);

if (indicePregunta + 1 < preguntas.length) {
if (indicePregunta+1 < preguntas.length) {
setIndicePregunta(indicePregunta + 1);
setPreguntaActual(preguntas[indicePregunta + 1]);
} else {
setJuegoTerminado(true);
if (preguntasCorrectas + preguntasFalladas > 0) {
setTiempoMedio(tiempoTotal / (preguntasCorrectas + preguntasFalladas));
const preguntasTotales=preguntasCorrectas+preguntasFalladas;
console.log(preguntasCorrectas);
console.log(preguntasFalladas);
const tMedio=tiempoTotal/preguntasTotales;
setTiempoMedio(tMedio);

}
guardarPartida();
}

};

useEffect(() => {
if (juegoTerminado) {
guardarPartida();
}
}, [juegoTerminado]);

const guardarPartida = async () => {


//Now we store the game in the stats DB
const username = localStorage.getItem("username");
const newGame = {
Expand Down Expand Up @@ -215,17 +228,17 @@ const JuegoPreguntas = () => {
</div>
<div className="answer">
<button
onClick={() => setTiempoRestante(0)}
onClick={() => {
setTiempoTotal(tiempoTotal+tiempoRestante);
setTiempoRestante(0);
}}
disabled={tiempoRestante === 0 || juegoTerminado}
>
Responder
</button>
</div>

<div className="timer">Tiempo restante: {tiempoRestante}</div>
<div className="timer">
Tiempo restante: {Math.floor(tiempoRestante)}
</div>
<div className="timer">Tiempo restante: {parseFloat(tiempoRestante).toFixed(2).toString()}</div>
<div className="points">Puntuación: {puntuacion}</div>
<div className="progressBarContainer">
<div
Expand Down
Empty file.
156 changes: 156 additions & 0 deletions webapp/src/pages/Ranking/Ranking.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import React, { useState, useEffect } from "react";
import Nav from "../../components/Nav/Nav.js";
import Footer from "../../components/Footer/Footer.js";

const Ranking = () => {
const gatewayUrl = process.env.GATEWAY_SERVICE_URL || "http://localhost:8000";

const [ranking, setRanking] = useState([]);
const [filterBy, setFilterBy] = useState("avgPoints");
const [displayOptions] = useState([
{ value: "avgPoints", label: "Puntos promedio" },
{ value: "totalPoints", label: "Puntos totales" },
{ value: "ratioCorrect", label: "Ratio de aciertos" },
{ value: "avgTime", label: "Tiempo por pregunta (s)" },
{ value: "avgPoints", label: "Reestablecer por defecto" }
]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [gamemode, setGamemode] = useState("clasico");

const fetchRanking = () => {
setIsLoading(true);
fetch(gatewayUrl + `/ranking?gamemode=${gamemode}&filterBy=${filterBy}`)
.then((response) => response.json())
.then((data) => {
setRanking(data);
setIsLoading(false);
})
.catch((error) => {
console.error('Error al obtener el ranking:', error);
setError(error.message || 'Ha ocurrido un error al obtener el ranking');
setIsLoading(false);
});
};

const getModeName = () => {
if(gamemode=="clasico"){
return "Clásico";
}else if(gamemode=="bateria"){
return "Batería de sabios";
}
return gamemode;
};

useEffect(() => {
fetchRanking();
}, [gamemode, filterBy]);

const handleDisplayChange = (event) => {
setFilterBy(event.target.value);
};

const getDisplayedField = () => {
switch (filterBy) {
case "avgPoints":
return "Puntos promedio";
case "totalPoints":
return "Puntos totales";
case "ratioCorrect":
return "Ratio de aciertos (%)";
case "avgTime":
return "Tiempo por pregunta (s)";
default:
return "";
}
};

const getDisplayValue = (stat) => {
switch (filterBy) {
case "avgPoints":
return Math.round(stat.avgPoints * 100) / 100;
case "totalPoints":
return stat.totalPoints;
case "ratioCorrect":
return Math.round(stat.ratioCorrect * 100) / 100;
case "avgTime":
return Math.round(stat.avgTime * 100) / 100;
default:
return "";
}
};

const handleGamemodeChange = (mode) => {
setGamemode(mode);
fetchRanking();
};

if (isLoading) {
return (
<div>
<h2>Cargando ...</h2>
<p>Se está consultando el ranking, espere unos instantes.</p>
</div>
);
}

if (error) {
return (
<div>
<h2>Error: {error}</h2>
<p>Ha ocurrido un error al obtener el ranking</p>
</div>
);
}

return (
<>
<Nav/>
<div>
<h2>Ranking - Modo {getModeName()}</h2>
<div>
<label htmlFor="displaySelector">Mostrar:</label>
<select id="displaySelector" onChange={handleDisplayChange}>
{displayOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
<div>
<button
className={gamemode === "clasico" ? "active" : ""}
onClick={() => handleGamemodeChange("clasico")}
>
Clásico
</button>
<button
className={gamemode === "bateria" ? "active" : ""}
onClick={() => handleGamemodeChange("bateria")}
>
Batería de sabios
</button>
</div>
<table>
<thead>
<tr>
<th>Usuario</th>
<th>{getDisplayedField()}</th>
</tr>
</thead>
<tbody>
{ranking && ranking.map((stat, index) => (
<tr key={index}>
<td>{stat.username}</td>
<td>{getDisplayValue(stat)}</td>
</tr>
))}
</tbody>
</table>
</div>
<Footer/>
</>
);
};

export default Ranking;

3 changes: 1 addition & 2 deletions webapp/src/pages/Sobre/Sobre.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ const Sobre = () => {
const designers = [
{ name: 'Martín Cancio Barrera', id: 'UO287561', github: 'https://github.com/CANCI0' },
{ name: 'Iyán Fernández Riol', id: 'UO288231', github: 'https://github.com/iyanfdezz' },
{ name: 'Rodrigo García Iglesias', id: 'UO276396', github: 'https://github.com/Rodrox11' },
{ name: 'Alfredo Jirout Cid', id: 'UO288443', github: 'https://github.com/UO288443' }
{ name: 'Rodrigo García Iglesias', id: 'UO276396', github: 'https://github.com/Rodrox11' }
];

return (
Expand Down
Loading

0 comments on commit 235e50d

Please sign in to comment.