5 Commits

Author SHA1 Message Date
Isaac d994f09f7d Ajustado CSS de resultados.php para consistencia con el proyecto.
Importante: He cambiado la ruta del "Volver al inicio" a $_ENV['urlBase']
2026-10-01 13:46:40 +02:00
dbvictor2002 111a101037 Subir archivos a "js" 2026-10-01 12:42:03 +02:00
dbvictor2002 71b7337dba Subir archivos a "controladores" 2026-10-01 12:39:45 +02:00
jorge dc5c04b693 Merge branch 'main' of https://git.desarrolloalcala.com/jorge/triviagmatico 2026-10-01 12:37:29 +02:00
dbvictor2002 29eb70b626 Subir archivos a "/" 2026-10-01 12:33:57 +02:00
5 changed files with 569 additions and 190 deletions
+102 -34
View File
@@ -1,6 +1,6 @@
<?php <?php
session_start(); session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/conexionBD.php'; require_once __DIR__ . '/../includes/conexionBD.php';
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
@@ -26,7 +26,7 @@ if (is_array($conexion)) {
switch ($orden) { switch ($orden) {
case 'comprobarEstado': case 'comprobarEstado':
try { try {
// Contar jugadores totales apuntados en los equipos de esta partida // 1. Contar cuántos jugadores hay asignados en esta partida
$stmt = $conexion->prepare(" $stmt = $conexion->prepare("
SELECT COUNT(exu.idUsuario) AS total_jugadores SELECT COUNT(exu.idUsuario) AS total_jugadores
FROM equipoxpartida exp FROM equipoxpartida exp
@@ -38,7 +38,7 @@ switch ($orden) {
$preguntasTotalesEsperadas = $totalJugadores * 10; $preguntasTotalesEsperadas = $totalJugadores * 10;
// Contar respuestas dadas en la partida // 2. Contar cuántas respuestas reales se han guardado
$stmtRespuestas = $conexion->prepare(" $stmtRespuestas = $conexion->prepare("
SELECT COUNT(*) SELECT COUNT(*)
FROM respuestaalmacenada ra FROM respuestaalmacenada ra
@@ -50,17 +50,16 @@ switch ($orden) {
$terminada = ($respuestasRespondidas >= $preguntasTotalesEsperadas && $preguntasTotalesEsperadas > 0); $terminada = ($respuestasRespondidas >= $preguntasTotalesEsperadas && $preguntasTotalesEsperadas > 0);
// Cuando la partida finaliza, se actualizan los históricos // 3. Si ha terminado, guardamos los datos históricos una sola vez
if ($terminada && !isset($_SESSION['partidas_procesadas'][$idPartida])) { if ($terminada && !isset($_SESSION['partidas_procesadas'][$idPartida])) {
$conexion->beginTransaction(); $conexion->beginTransaction();
// CÁLCULO DE VELOCIDAD PREGUNTA A PREGUNTA EN SESIÓN // --- CÁLCULO DE VELOCIDAD ---
if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) { if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) {
$_SESSION['primeros_en_acertar'][$idPartida] = []; $_SESSION['primeros_en_acertar'][$idPartida] = [];
} }
// Vemos quién fue el primero
$stmtVelocidad = $conexion->prepare(" $stmtVelocidad = $conexion->prepare("
SELECT ra.idPartidaxPregunta, ra.idUsuario SELECT ra.idPartidaxPregunta, ra.idUsuario
FROM respuestaalmacenada ra FROM respuestaalmacenada ra
@@ -81,8 +80,7 @@ switch ($orden) {
} }
} }
// Actualizamos la base de datos // Consulta de aciertos
// Buscamos los aciertos de cada jugador en la partida actual
$stmtAciertos = $conexion->prepare(" $stmtAciertos = $conexion->prepare("
SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida
FROM respuestaalmacenada ra FROM respuestaalmacenada ra
@@ -90,12 +88,12 @@ switch ($orden) {
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
INNER JOIN equipoxusuario exu ON ra.idUsuario = exu.idUsuario INNER JOIN equipoxusuario exu ON ra.idUsuario = exu.idUsuario
WHERE pxp.idPartida = :idPartida AND r.correcta = 1 WHERE pxp.idPartida = :idPartida AND r.correcta = 1
GROUP BY ra.idUsuario GROUP BY ra.idUsuario, exu.idEquipo
"); ");
$stmtAciertos->execute([':idPartida' => $idPartida]); $stmtAciertos->execute([':idPartida' => $idPartida]);
$jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC); $jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC);
$updateAciertosGlobales = $conexion->prepare(" $updateAciertos = $conexion->prepare("
UPDATE usuario UPDATE usuario
SET aciertos = aciertos + :nuevos_aciertos SET aciertos = aciertos + :nuevos_aciertos
WHERE idUsuario = :idUsuario WHERE idUsuario = :idUsuario
@@ -107,7 +105,6 @@ switch ($orden) {
$idE = (int)$jp['idEquipo']; $idE = (int)$jp['idEquipo'];
$nuevosAciertos = (int)$jp['aciertos_partida']; $nuevosAciertos = (int)$jp['aciertos_partida'];
// Sumamos los aciertos al perfil del usuario
$updateAciertos->execute([ $updateAciertos->execute([
':nuevos_aciertos' => $nuevosAciertos, ':nuevos_aciertos' => $nuevosAciertos,
':idUsuario' => $idU ':idUsuario' => $idU
@@ -119,34 +116,42 @@ switch ($orden) {
$puntosEquipos[$idE] += $nuevosAciertos; $puntosEquipos[$idE] += $nuevosAciertos;
} }
// Determinamos qué equipo ha obtenido más aciertos en la partida if (!empty($puntosEquipos)) {
arsort($puntosEquipos); arsort($puntosEquipos);
$idEquipoGanador = key($puntosEquipos); $idEquipoGanador = key($puntosEquipos);
// Obtenemos todos los usuarios de la partida para asignar victorias/derrotas $stmtMiembros = $conexion->prepare("
$stmtMiembros = $conexion->prepare(" SELECT exu.idUsuario, exu.idEquipo
SELECT exu.idUsuario, exu.idEquipo FROM equipoxpartida exp
FROM equipoxpartida exp INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo WHERE exp.idPartida = :idPartida
WHERE exp.idPartida = :idPartida ");
"); $stmtMiembros->execute([':idPartida' => $idPartida]);
$stmtMiembros->execute([':idPartida' => $idPartida]); $todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
$todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
$updateVictoria = $conexion->prepare("UPDATE usuario SET victorias = victorias + 1 WHERE idUsuario = :idUsuario"); $updateVictoria = $conexion->prepare("UPDATE usuario SET victorias = victorias + 1 WHERE idUsuario = :idUsuario");
$updateDerrota = $conexion->prepare("UPDATE usuario SET derrotas = derrotas + 1 WHERE idUsuario = :idUsuario"); $updateDerrota = $conexion->prepare("UPDATE usuario SET derrotas = derrotas + 1 WHERE idUsuario = :idUsuario");
foreach ($todosLosMiembros as $miembro) { foreach ($todosLosMiembros as $miembro) {
$idU = (int)$miembro['idUsuario']; $idU = (int)$miembro['idUsuario'];
$idE = (int)$miembro['idEquipo']; $idE = (int)$miembro['idEquipo'];
if ($idE === $idEquipoGanador) { if ($idE === $idEquipoGanador) {
$updateVictoria->execute([':idUsuario' => $idU]); $updateVictoria->execute([':idUsuario' => $idU]);
} else { } else {
$updateDerrota->execute([':idUsuario' => $idU]); $updateDerrota->execute([':idUsuario' => $idU]);
}
} }
} }
// Marcar fecha fin de la partida para los históricos globales del grupo
$stmtFinalizar = $conexion->prepare("
UPDATE partida
SET fechaFin = NOW()
WHERE idPartida = :idPartida AND fechaFin IS NULL
");
$stmtFinalizar->execute([':idPartida' => $idPartida]);
$conexion->commit(); $conexion->commit();
$_SESSION['partidas_procesadas'][$idPartida] = true; $_SESSION['partidas_procesadas'][$idPartida] = true;
} }
@@ -160,7 +165,70 @@ switch ($orden) {
} }
break; break;
default: case 'registrarSalidaUsuario':
echo json_encode(['error' => 'Acción no permitida']); try {
$idUsuario = (int)$_SESSION['idUsuario'];
$conexion->beginTransaction();
// A. LIBERACIÓN INMEDIATA DEL JUGADOR ACTUAL: Lo borramos de su equipo
$stmtSalir = $conexion->prepare("DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario");
$stmtSalir->execute([':idUsuario' => $idUsuario]);
// B. CONTADOR DE ALUMNOS QUEDAN: Contamos cuántas personas quedan en los equipos de esta partida
$stmtContarQuedan = $conexion->prepare("
SELECT COUNT(exu.idUsuario)
FROM equipoxpartida exp
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
WHERE exp.idPartida = :idPartida
");
$stmtContarQuedan->execute([':idPartida' => $idPartida]);
$jugadoresRestantes = (int)$stmtContarQuedan->fetchColumn();
// C. DESTRUCCIÓN EN CADENA AUTOMÁTICA ATÓMICA (Si da 0, somos los últimos en salir)
if ($jugadoresRestantes === 0) {
// 1. Limpiar las respuestas almacenadas
$stmtBorrarRespuestas = $conexion->prepare("
DELETE ra FROM respuestaalmacenada ra
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
WHERE pxp.idPartida = :idPartida
");
$stmtBorrarRespuestas->execute([':idPartida' => $idPartida]);
// 2. Limpiar las preguntas vinculadas a la partida
$stmtBorrarPreguntas = $conexion->prepare("DELETE FROM partidaxpregunta WHERE idPartida = :idPartida");
$stmtBorrarPreguntas->execute([':idPartida' => $idPartida]);
// 3. NUEVO: Obtener los IDs de los dos equipos que jugaban en esta partida antes de borrar la relación
$stmtObtenerEquipos = $conexion->prepare("SELECT idEquipo FROM equipoxpartida WHERE idPartida = :idPartida");
$stmtObtenerEquipos->execute([':idPartida' => $idPartida]);
$equiposDeLaPartida = $stmtObtenerEquipos->fetchAll(PDO::FETCH_COLUMN);
// 4. Limpiar la relación de equipos de la partida (tabla intermedia)
$stmtBorrarEquiposPartida = $conexion->prepare("DELETE FROM equipoxpartida WHERE idPartida = :idPartida");
$stmtBorrarEquiposPartida = $conexion->prepare("DELETE FROM equipoxpartida WHERE idPartida = :idPartida");
$stmtBorrarEquiposPartida->execute([':idPartida' => $idPartida]);
// 5. NUEVO: Borrar físicamente los equipos de la tabla 'equipo' si existen
if (!empty($equiposDeLaPartida)) {
// Creamos los marcadores (?, ?) de forma dinámica según los equipos que devuelva
$inQuery = implode(',', array_fill(0, count($equiposDeLaPartida), '?'));
$stmtBorrarEquiposFisicos = $conexion->prepare("DELETE FROM equipo WHERE idEquipo IN ($inQuery)");
$stmtBorrarEquiposFisicos->execute($equiposDeLaPartida);
}
// 6. Borrar físicamente la fila de la partida principal
$stmtBorrarSala = $conexion->prepare("DELETE FROM partida WHERE idPartida = :idPartida");
$stmtBorrarSala->execute([':idPartida' => $idPartida]);
}
$conexion->commit();
echo json_encode(['exito' => true, 'usuarios_quedan' => $jugadoresRestantes]);
} catch (PDOException $e) {
if ($conexion->inTransaction()) {
$conexion->rollBack();
}
echo json_encode(['error' => $e->getMessage()]);
}
break; break;
} }
+1
View File
@@ -121,6 +121,7 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 15px; gap: 15px;
text-decoration: none;
} }
.btn-play-kahoot:hover { .btn-play-kahoot:hover {
+377 -114
View File
@@ -1,179 +1,442 @@
/* ========================================================================== /* ==========================================================================
ESTILOS GENERALES Y FONDO VARIABLES DEL PROYECTO
========================================================================== */ ========================================================================== */
:root {
--kahoot-purple: #46178f;
--kahoot-purple-dark: #35116f;
--kahoot-blue: #1368ce;
--kahoot-blue-dark: #0c4891;
--kahoot-red: #e21b3c;
--kahoot-yellow: #ffa602;
--kahoot-yellow-dark: #d88900;
--kahoot-green: #26890c;
--kahoot-green-hover: #1f6f09;
--background: #f2f2f2;
--text-dark: #333333;
--text-muted: #666666;
--white: #ffffff;
}
/* ==========================================================================
ESTILOS GENERALES
========================================================================== */
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-shadow: none;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; font-family: 'Fredoka', sans-serif;
background-color: #f0f4f8; background-color: var(--background);
color: #2c3e50; color: var(--text-dark);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; min-height: 100vh;
padding: 20px; padding: 30px 20px;
} }
/* Contenedor principal estilo tarjeta */
.contenedor {
width: 100%;
max-width: 900px;
background: #ffffff;
padding: 40px;
border-radius: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
text-align: center;
animation: fadeIn 0.5s ease-in-out;
}
h1 {
font-size: 2.5rem;
color: #1a365d;
margin-bottom: 30px;
}
h2 {
font-size: 1.6rem;
color: #2b6cb0;
margin-top: 30px;
margin-bottom: 15px;
text-align: left;
border-bottom: 2px solid #e2e8f0;
padding-bottom: 8px;
}
p {
font-size: 1.1rem;
color: #718096;
margin-bottom: 30px;
}
/* ========================================================================== /* ==========================================================================
PANTALLA DE ESPERA Y ANIMACIÓN DE CARGA (LOADER) CONTENEDOR PRINCIPAL
========================================================================== */ ========================================================================== */
#pantalla-espera {
padding: 60px 20px; .contenedor {
width: 100%;
max-width: 1000px;
margin: 0 auto;
background-color: var(--white);
border-radius: 20px;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.10);
overflow: hidden;
} }
/* ==========================================================================
PANTALLA DE ESPERA
========================================================================== */
#pantalla-espera {
padding: 70px 30px;
text-align: center;
}
#pantalla-espera h2 {
color: var(--kahoot-purple);
font-size: 2rem;
font-weight: 700;
margin-bottom: 15px;
}
#pantalla-espera p {
color: var(--text-muted);
font-size: 1.1rem;
margin-bottom: 35px;
}
/* ==========================================================================
LOADER
========================================================================== */
.loader { .loader {
width: 60px; width: 65px;
height: 60px; height: 65px;
border: 6px solid #e2e8f0;
border-top: 6px solid #3182ce;
border-radius: 50%;
margin: 0 auto; margin: 0 auto;
animation: spin 1.2s linear infinite;
border: 7px solid #e5e5e5;
border-top-color: var(--kahoot-purple);
border-radius: 50%;
animation: spin 1s linear infinite;
} }
@keyframes spin { @keyframes spin {
0% { transform: rotate(0deg); } from {
100% { transform: rotate(360deg); } transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
} }
/* ========================================================================== /* ==========================================================================
TABLAS DE CLASIFICACIÓN (RANKING) CABECERA DE RESULTADOS
========================================================================== */ ========================================================================== */
.tabla-ranking {
width: 100%; #pantalla-resultados {
border-collapse: collapse; padding: 40px;
margin-bottom: 20px;
font-size: 1.05rem;
} }
.tabla-ranking th, #pantalla-resultados h1 {
.tabla-ranking td { text-align: center;
padding: 16px 20px; color: var(--kahoot-yellow);
font-size: 2.6rem;
font-weight: 700;
margin-bottom: 35px;
text-shadow: 2px 2px 0 rgba(70, 23, 143, 0.10);
}
#pantalla-resultados h2 {
display: flex;
align-items: center;
gap: 10px;
font-size: 1.5rem;
font-weight: 700;
margin-top: 35px;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 3px solid #eee;
}
/* ==========================================================================
TABLAS
========================================================================== */
.tabla-ranking {
width: 100%;
border-collapse: separate;
border-spacing: 0;
overflow: hidden;
background-color: #fff;
border: 2px solid #eeeeee;
border-radius: 15px;
margin-bottom: 30px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.06);
}
/* Cabecera */
.tabla-ranking thead th {
background-color: var(--kahoot-purple);
color: white;
padding: 15px 18px;
font-size: 0.95rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.3px;
text-align: left; text-align: left;
} }
.tabla-ranking th { .tabla-ranking thead th:first-child {
background-color: #2d3748; border-top-left-radius: 12px;
color: #ffffff;
font-weight: 600;
text-transform: uppercase;
font-size: 0.9rem;
letter-spacing: 0.5px;
} }
/* Alinear los puntos y aciertos a la derecha para mejor lectura numérica */ .tabla-ranking thead th:last-child {
.tabla-ranking th:last-child, border-top-right-radius: 12px;
.tabla-ranking td:last-child {
text-align: right;
} }
.tabla-ranking tr {
border-bottom: 1px solid #e2e8f0; /* Celdas */
transition: background-color 0.2s;
.tabla-ranking tbody td {
padding: 16px 18px;
font-size: 1rem;
font-weight: 500;
border-bottom: 1px solid #eeeeee;
color: var(--text-dark);
}
/* Última fila */
.tabla-ranking tbody tr:last-child td {
border-bottom: none;
}
/* Hover */
.tabla-ranking tbody tr {
transition:
transform 0.15s ease,
background-color 0.15s ease;
} }
.tabla-ranking tbody tr:hover { .tabla-ranking tbody tr:hover {
background-color: #f7fafc; background-color: #f7f3ff;
} }
/* ========================================================================== /* ==========================================================================
RESALTADO DE GANADORES (1º PUESTO) COLUMNA DE POSICIÓN
========================================================================== */ ========================================================================== */
/* Fila del Equipo Ganador y Jugador Ganador */
.tabla-ranking tr.top-team, .tabla-ranking tbody td:first-child {
.tabla-ranking tr.top-player { font-weight: 700;
background-color: #fefcbf !important; /* Amarillo suave */ color: var(--kahoot-purple);
font-weight: bold; width: 100px;
} }
/* Cambiar el color del texto del puesto #1 a dorado/corona */
.tabla-ranking tr.top-team td:first-child, /* ==========================================================================
.tabla-ranking tr.top-player td:first-child { PUNTOS
color: #b7791f; ========================================================================== */
font-size: 1.2rem;
}
.tabla-ranking td strong { .tabla-ranking td strong {
color: #2f855a; /* Verde para destacar los aciertos conseguidos */ color: var(--kahoot-green);
font-size: 1.1rem; font-size: 1.15rem;
font-weight: 700;
} }
/* ==========================================================================
EFECTOS VISUALES SUAVES
========================================================================== */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
/* ========================================================================== /* ==========================================================================
ESTILOS DEL BOTÓN DE RETORNO A INICIO EQUIPO / JUGADOR GANADOR
========================================================================== */ ========================================================================== */
.tabla-ranking tr.top-team,
.tabla-ranking tr.top-player {
background-color: #fff7df !important;
font-weight: 700;
}
/* Línea lateral amarilla */
.tabla-ranking tr.top-team td:first-child,
.tabla-ranking tr.top-player td:first-child {
color: var(--kahoot-yellow-dark);
font-size: 1.15rem;
}
/* Puntos del ganador */
.tabla-ranking tr.top-team td strong,
.tabla-ranking tr.top-player td strong {
color: var(--kahoot-green);
}
/* ==========================================================================
BOTÓN VOLVER AL INICIO
========================================================================== */
.contenedor-boton { .contenedor-boton {
display: flex;
justify-content: center;
align-items: center;
margin-top: 40px; margin-top: 40px;
padding-top: 20px; padding-top: 10px;
text-align: center;
} }
/* Botón */
.btn-inicio { .btn-inicio {
display: inline-block; display: inline-flex;
background-color: #3182ce; /* Azul corporativo */ align-items: center;
color: #ffffff; justify-content: center;
padding: 14px 28px; gap: 10px;
min-width: 240px;
padding: 15px 28px;
background-color: var(--kahoot-blue);
color: white;
border: none;
border-bottom: 5px solid var(--kahoot-blue-dark);
border-radius: 12px;
font-family: 'Fredoka', sans-serif;
font-size: 1.1rem; font-size: 1.1rem;
font-weight: 600; font-weight: 700;
text-decoration: none; text-decoration: none;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(49, 130, 206, 0.2); box-shadow: 0 5px 10px rgba(19, 104, 206, 0.25);
transition: background-color 0.2s, transform 0.2s, box-shadow 0.2s;
transition: all 0.15s ease;
} }
/* Hover */
.btn-inicio:hover { .btn-inicio:hover {
background-color: #2b6cb0; /* Azul ligeramente más oscuro al pasar el cursor */ background-color: #0f56ab;
box-shadow: 0 6px 12px rgba(43, 108, 176, 0.3); color: white;
transform: translateY(-2px); /* Pequeño salto hacia arriba */
transform: translateY(-3px);
box-shadow: 0 8px 15px rgba(19, 104, 206, 0.30);
} }
/* Click */
.btn-inicio:active { .btn-inicio:active {
transform: translateY(0); /* Vuelve a su posición normal al pulsar */ transform: translateY(3px);
box-shadow: 0 2px 4px rgba(43, 108, 176, 0.2);
border-bottom-width: 2px;
box-shadow: 0 3px 6px rgba(19, 104, 206, 0.20);
}
/* ==========================================================================
RESPONSIVE
========================================================================== */
@media (max-width: 768px) {
body {
padding: 15px 10px;
}
#pantalla-resultados {
padding: 25px 15px;
}
#pantalla-resultados h1 {
font-size: 2rem;
margin-bottom: 25px;
}
#pantalla-resultados h2 {
font-size: 1.3rem;
}
.tabla-ranking {
font-size: 0.9rem;
}
.tabla-ranking thead th,
.tabla-ranking tbody td {
padding: 12px 10px;
}
.tabla-ranking thead th {
font-size: 0.75rem;
}
.tabla-ranking tbody td {
font-size: 0.9rem;
}
.tabla-ranking td strong {
font-size: 1rem;
}
.btn-inicio {
width: 100%;
min-width: 0;
}
}
/* ==========================================================================
MÓVILES PEQUEÑOS
========================================================================== */
@media (max-width: 500px) {
body {
padding: 10px 5px;
}
#pantalla-espera {
padding: 50px 20px;
}
#pantalla-espera h2 {
font-size: 1.5rem;
}
#pantalla-espera p {
font-size: 0.95rem;
}
#pantalla-resultados {
padding: 20px 10px;
}
#pantalla-resultados h1 {
font-size: 1.7rem;
}
#pantalla-resultados h2 {
font-size: 1.15rem;
}
.tabla-ranking {
display: block;
overflow-x: auto;
white-space: nowrap;
}
.tabla-ranking thead th,
.tabla-ranking tbody td {
padding: 10px 8px;
}
.contenedor-boton {
margin-top: 25px;
}
} }
+70 -28
View File
@@ -1,38 +1,80 @@
$(document).ready(function () { $(document).ready(function () {
const idPartida = $("body").data("id-partida"); // Captura segura del ID de la partida desde el body de la página
const idPartida =
$("body").attr("data-id-partida") || $("body").data("id-partida");
comprobarEstadoPartida(idPartida); comprobarEstadoPartida(idPartida);
const intervalo = setInterval(function () { const intervalo = setInterval(function () {
comprobarEstadoPartida(idPartida, intervalo); comprobarEstadoPartida(idPartida, intervalo);
}, 3000); }, 3000);
}); });
function comprobarEstadoPartida(idPartida, intervalo = null) { function comprobarEstadoPartida(idPartida, intervalo = null) {
$.ajax({ if (!idPartida || idPartida <= 0) return;
url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "comprobarEstado",
idPartida: idPartida
},
success: function (respuesta) {
if (respuesta.error) {
console.error("Error:", respuesta.error);
return;
}
if (respuesta.terminada) { $.ajax({
if (intervalo !== null) clearInterval(intervalo); url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "comprobarEstado",
idPartida: idPartida,
},
success: function (respuesta) {
if (respuesta.error) {
console.error("Error del controlador:", respuesta.error);
return;
}
$("#pantalla-espera").fadeOut(400, function() { if (respuesta.terminada === true || respuesta.terminada === "true") {
location.reload(); if (intervalo !== null) {
}); clearInterval(intervalo);
}
},
error: function () {
console.log("Error de comunicación con el controlador.");
} }
});
$("#pantalla-espera").hide();
$("#pantalla-resultados").show();
}
},
error: function () {
console.log("Esperando conexión con el servidor del Trivial...");
},
});
} }
// INTERCEPTOR DE SALIDA: Saca al usuario y destruye la sala en cascada
$(document).on("click", "#btnVolverInicio", function (e) {
e.preventDefault(); // Congelamos un instante la redirección
const urlDestino = $(this).attr("href");
// Leemos el ID de forma científica directamente desde el botón pulsado
const idPartida = $(this).attr("data-id");
if (!idPartida) {
window.location.href = urlDestino;
return;
}
$.ajax({
url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "registrarSalidaUsuario",
idPartida: idPartida,
},
success: function (response) {
console.log(
"Servidor procesó la salida. Usuarios restantes: " +
response.usuarios_quedan,
);
},
error: function (error) {
console.error("Error técnico al salir de la sala:", error);
},
complete: function () {
// Rompemos la pausa y mandamos al jugador al menú de inicio limpio
window.location.href = urlDestino;
},
});
});
+15 -10
View File
@@ -1,6 +1,6 @@
<?php <?php
session_start(); session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/conexionBD.php'; require_once __DIR__ . '/includes/conexionBD.php';
$idPartida = intval($_GET['idPartida'] ?? 0); $idPartida = intval($_GET['idPartida'] ?? 0);
if ($idPartida <= 0) { if ($idPartida <= 0) {
@@ -29,7 +29,7 @@ $primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
$jugadoresFinales = []; $jugadoresFinales = [];
$equiposFinales = []; $equiposFinales = [];
// Respuestas de velocidad (+2 o +1) // Respuestas de velocidad (+2 o +1) procesadas en la capa de la vista
foreach ($listaJugadoresRaw as $jugador) { foreach ($listaJugadoresRaw as $jugador) {
$idU = (int)$jugador['idUsuario']; $idU = (int)$jugador['idUsuario'];
$idE = (int)$jugador['idEquipo']; $idE = (int)$jugador['idEquipo'];
@@ -52,7 +52,6 @@ foreach ($listaJugadoresRaw as $jugador) {
$aciertos++; $aciertos++;
$idPxp = $resp['idPartidaxPregunta']; $idPxp = $resp['idPartidaxPregunta'];
// Si el ID de usuario coincide con el primero guardado de esa pregunta se lleva 2 puntos
if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) { if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) {
$puntosTotalesJugador += 2; $puntosTotalesJugador += 2;
} else { } else {
@@ -77,7 +76,6 @@ foreach ($listaJugadoresRaw as $jugador) {
$equiposFinales[$idE]['puntos'] += $puntosTotalesJugador; $equiposFinales[$idE]['puntos'] += $puntosTotalesJugador;
} }
// Ordenar según la puntuación final de mayor a menor
usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; }); usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; }); usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
?> ?>
@@ -88,19 +86,24 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resultados - Trivial</title> <title>Resultados - Trivial</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/resultados.css"> <link rel="stylesheet" href="css/resultados.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"></script> <script src="js/jquery-4.0.0.min.js"></script>
</head> </head>
<body data-id-partida="<?php echo $idPartida; ?>"> <body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor"> <div id="pantalla-espera" class="contenedor">
<h2>⌛ Esperando a que todos los jugadores terminen...</h2> <h2> <i class="bi bi-hourglass"></i> Esperando a que todos los jugadores terminen...</h2>
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p> <p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
<div class="loader"></div> <div class="loader"></div>
</div> </div>
<div id="pantalla-resultados" class="contenedor" style="display:none;"> <div id="pantalla-resultados" class="contenedor" style="display:none;">
<h1>🏆 Resultados de la Partida 🏆</h1> <h1> <i class="bi bi-trophy-fill"></i> Resultados de la Partida <i class="bi bi-trophy-fill"></i> </h1>
<h2>Clasificación por Equipos</h2> <h2>Clasificación por Equipos</h2>
<table class="tabla-ranking"> <table class="tabla-ranking">
@@ -146,9 +149,11 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
</tbody> </tbody>
</table> </table>
<div class="contenedor-boton">
<a href="/triviagmatico/buscadorSala.php" class="btn-inicio">Volver al Inicio 🏠</a> <div class="contenedor-boton">
</div> <a href="<?= $_ENV['urlBase'] ?>/" id="btnVolverInicio" data-id="<?php echo $idPartida; ?>" class="btn btn-play-kahoot"> <i class="bi bi-arrow-left"></i> Volver al Inicio <i class="bi bi-house-fill"></i> </a>
</div>
</div> </div>
<script src="js/resultados.js"></script> <script src="js/resultados.js"></script>