Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e9cf7c8fcf | |||
| 111a101037 | |||
| 71b7337dba | |||
| dc5c04b693 | |||
| 29eb70b626 | |||
| 5bf5b7a3bc | |||
| e8accf949e | |||
| fa883cde39 | |||
| ae213a3d12 | |||
| cd0685f41c | |||
| e3395a017c | |||
| 396aca8b03 | |||
| c6db380ef9 | |||
| 8d5d7da615 | |||
| 7f70112f63 | |||
| a66ac7086d | |||
| eed77db62f | |||
| 83545152bb | |||
| 71fb45b94c | |||
| 5b6352b4ee | |||
| 7e1344a395 | |||
| db5061ec7f | |||
| 737b76e83b | |||
| 3705a9ea9e | |||
| 72134b405c | |||
| 91056a05d9 | |||
| 18a56e0bbd | |||
| ed7067161a | |||
| 2531ef321a | |||
| d3e523ad73 | |||
| 77249ba51b | |||
| 5446352cf9 | |||
| 95f7d8dad6 |
+1
-1
@@ -71,7 +71,7 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-kahoot-login" id="btnCrearSala">Crear sala</button>
|
||||
<button type="button" class="btn btn-kahoot-register" id="btnCrearSala">Crear sala</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,79 +1,118 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/claseJuego.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// Hay que estar logueado y decir de qué partida se trata
|
||||
// Comprobamos que haya un usuario conectado
|
||||
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
|
||||
echo json_encode([
|
||||
'error' => 'Debes iniciar sesión para jugar.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
||||
$idUsuario = (int) $_SESSION['idUsuario'];
|
||||
|
||||
// Comprobamos que se haya indicado la partida
|
||||
|
||||
if (!isset($_POST['idPartida'])) {
|
||||
echo json_encode([
|
||||
'error' => 'No se ha indicado la partida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$idPartida = intval($_POST['idPartida']);
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode(['error' => 'No se ha indicado la partida.']);
|
||||
echo json_encode([
|
||||
'error' => 'La partida indicada no es válida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// Solo pueden jugar los usuarios que están en uno de los equipos de la partida
|
||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida, $idUsuario);
|
||||
// Comprobamos que el usuario pertenezca a la partida
|
||||
|
||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida,$idUsuario);
|
||||
|
||||
if (is_array($perteneceAPartida)) {
|
||||
echo json_encode($perteneceAPartida);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
if (!$perteneceAPartida) {
|
||||
echo json_encode(['error' => 'No formas parte de esta partida.']);
|
||||
echo json_encode([
|
||||
'error' => 'No formas parte de esta partida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// Comprobamos la orden
|
||||
|
||||
switch ($_POST['orden'] ?? '') {
|
||||
$orden = $_POST['orden'] ?? '';
|
||||
|
||||
switch ($orden) {
|
||||
|
||||
// CARGAR LAS PREGUNTAS DE LA PARTIDA
|
||||
|
||||
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
|
||||
case 'cargarPreguntas':
|
||||
|
||||
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
|
||||
$resultado = Juego::cargarPreguntas($idPartida, $idUsuario);
|
||||
echo json_encode($resultado);
|
||||
|
||||
break;
|
||||
break;
|
||||
|
||||
// REGISTRAR RESPUESTA
|
||||
|
||||
// Guarda la respuesta del usuario y dice si ha acertado
|
||||
case 'responder':
|
||||
|
||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta'] ?? 0);
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
|
||||
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0) {
|
||||
echo json_encode(['error' => 'Faltan datos para registrar la respuesta.']);
|
||||
break;
|
||||
}
|
||||
|
||||
echo json_encode(
|
||||
Juego::registrarRespuesta(
|
||||
$idPartida,
|
||||
$idUsuario,
|
||||
$idPartidaxPregunta,
|
||||
$idRespuesta
|
||||
)
|
||||
);
|
||||
if (!isset($_POST['idPartidaxPregunta']) || !isset($_POST['idRespuesta'])){
|
||||
echo json_encode([
|
||||
'error' => 'Faltan datos para registrar la respuesta.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta']);
|
||||
|
||||
$idRespuesta = intval($_POST['idRespuesta']);
|
||||
|
||||
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0){
|
||||
|
||||
echo json_encode([
|
||||
'error' => 'Los datos de la respuesta no son válidos.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Registramos la respuesta del usuario
|
||||
|
||||
$resultado = Juego::registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta);
|
||||
|
||||
echo json_encode($resultado);
|
||||
|
||||
break;
|
||||
|
||||
// Finalizar la partida y registrar los aciertos del usuario
|
||||
|
||||
// Recibe los aciertos del jugador al terminar sus 10 preguntas,
|
||||
// para que resultados.php los pueda usar al montar la hoja de resultados
|
||||
case 'finalizarPartida':
|
||||
|
||||
$aciertos = intval($_POST['aciertos'] ?? 0);
|
||||
|
||||
// Guardamos los aciertos en la sesión
|
||||
|
||||
if (!isset($_SESSION['aciertosPorPartida'])) {
|
||||
|
||||
$_SESSION['aciertosPorPartida'] = [];
|
||||
}
|
||||
|
||||
@@ -81,16 +120,21 @@ switch ($_POST['orden'] ?? '') {
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Aciertos registrados correctamente.',
|
||||
|
||||
'idPartida' => $idPartida,
|
||||
|
||||
'aciertos' => $aciertos
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
|
||||
echo json_encode(['error' => 'La orden indicada no existe.']);
|
||||
echo json_encode([
|
||||
'error' => 'La orden indicada no existe.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
?>
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Redirección si el usuario no ha iniciado sesión
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: login.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$nombreUsuario = htmlspecialchars($_SESSION['nombreUsuario'] ?? 'Usuario');
|
||||
$avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultProfile.jpeg');
|
||||
?>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/conexionBD.php';
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
@@ -26,7 +26,7 @@ if (is_array($conexion)) {
|
||||
switch ($orden) {
|
||||
case 'comprobarEstado':
|
||||
try {
|
||||
// Contar jugadores totales apuntados en los equipos de esta partida
|
||||
// 1. Contar cuántos jugadores hay asignados en esta partida
|
||||
$stmt = $conexion->prepare("
|
||||
SELECT COUNT(exu.idUsuario) AS total_jugadores
|
||||
FROM equipoxpartida exp
|
||||
@@ -38,7 +38,7 @@ switch ($orden) {
|
||||
|
||||
$preguntasTotalesEsperadas = $totalJugadores * 10;
|
||||
|
||||
// Contar respuestas dadas en la partida
|
||||
// 2. Contar cuántas respuestas reales se han guardado
|
||||
$stmtRespuestas = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada ra
|
||||
@@ -50,17 +50,16 @@ switch ($orden) {
|
||||
|
||||
$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])) {
|
||||
|
||||
$conexion->beginTransaction();
|
||||
|
||||
// CÁLCULO DE VELOCIDAD PREGUNTA A PREGUNTA EN SESIÓN
|
||||
// --- CÁLCULO DE VELOCIDAD ---
|
||||
if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) {
|
||||
$_SESSION['primeros_en_acertar'][$idPartida] = [];
|
||||
}
|
||||
|
||||
// Vemos quién fue el primero
|
||||
$stmtVelocidad = $conexion->prepare("
|
||||
SELECT ra.idPartidaxPregunta, ra.idUsuario
|
||||
FROM respuestaalmacenada ra
|
||||
@@ -81,8 +80,7 @@ switch ($orden) {
|
||||
}
|
||||
}
|
||||
|
||||
// Actualizamos la base de datos
|
||||
// Buscamos los aciertos de cada jugador en la partida actual
|
||||
// Consulta de aciertos
|
||||
$stmtAciertos = $conexion->prepare("
|
||||
SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida
|
||||
FROM respuestaalmacenada ra
|
||||
@@ -90,12 +88,12 @@ switch ($orden) {
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
INNER JOIN equipoxusuario exu ON ra.idUsuario = exu.idUsuario
|
||||
WHERE pxp.idPartida = :idPartida AND r.correcta = 1
|
||||
GROUP BY ra.idUsuario
|
||||
GROUP BY ra.idUsuario, exu.idEquipo
|
||||
");
|
||||
$stmtAciertos->execute([':idPartida' => $idPartida]);
|
||||
$jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateAciertosGlobales = $conexion->prepare("
|
||||
$updateAciertos = $conexion->prepare("
|
||||
UPDATE usuario
|
||||
SET aciertos = aciertos + :nuevos_aciertos
|
||||
WHERE idUsuario = :idUsuario
|
||||
@@ -107,7 +105,6 @@ switch ($orden) {
|
||||
$idE = (int)$jp['idEquipo'];
|
||||
$nuevosAciertos = (int)$jp['aciertos_partida'];
|
||||
|
||||
// Sumamos los aciertos al perfil del usuario
|
||||
$updateAciertos->execute([
|
||||
':nuevos_aciertos' => $nuevosAciertos,
|
||||
':idUsuario' => $idU
|
||||
@@ -119,34 +116,42 @@ switch ($orden) {
|
||||
$puntosEquipos[$idE] += $nuevosAciertos;
|
||||
}
|
||||
|
||||
// Determinamos qué equipo ha obtenido más aciertos en la partida
|
||||
arsort($puntosEquipos);
|
||||
$idEquipoGanador = key($puntosEquipos);
|
||||
if (!empty($puntosEquipos)) {
|
||||
arsort($puntosEquipos);
|
||||
$idEquipoGanador = key($puntosEquipos);
|
||||
|
||||
// Obtenemos todos los usuarios de la partida para asignar victorias/derrotas
|
||||
$stmtMiembros = $conexion->prepare("
|
||||
SELECT exu.idUsuario, exu.idEquipo
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmtMiembros->execute([':idPartida' => $idPartida]);
|
||||
$todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
|
||||
$stmtMiembros = $conexion->prepare("
|
||||
SELECT exu.idUsuario, exu.idEquipo
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmtMiembros->execute([':idPartida' => $idPartida]);
|
||||
$todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateVictoria = $conexion->prepare("UPDATE usuario SET victorias = victorias + 1 WHERE idUsuario = :idUsuario");
|
||||
$updateDerrota = $conexion->prepare("UPDATE usuario SET derrotas = derrotas + 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");
|
||||
|
||||
foreach ($todosLosMiembros as $miembro) {
|
||||
$idU = (int)$miembro['idUsuario'];
|
||||
$idE = (int)$miembro['idEquipo'];
|
||||
foreach ($todosLosMiembros as $miembro) {
|
||||
$idU = (int)$miembro['idUsuario'];
|
||||
$idE = (int)$miembro['idEquipo'];
|
||||
|
||||
if ($idE === $idEquipoGanador) {
|
||||
$updateVictoria->execute([':idUsuario' => $idU]);
|
||||
} else {
|
||||
$updateDerrota->execute([':idUsuario' => $idU]);
|
||||
if ($idE === $idEquipoGanador) {
|
||||
$updateVictoria->execute([':idUsuario' => $idU]);
|
||||
} else {
|
||||
$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();
|
||||
$_SESSION['partidas_procesadas'][$idPartida] = true;
|
||||
}
|
||||
@@ -160,7 +165,70 @@ switch ($orden) {
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
echo json_encode(['error' => 'Acción no permitida']);
|
||||
case 'registrarSalidaUsuario':
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -77,8 +77,9 @@
|
||||
}
|
||||
|
||||
.btn-unirse:hover {
|
||||
background-color: #0f56ab;
|
||||
background-color: #1f6f09;
|
||||
color: white;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.modal-kahoot {
|
||||
|
||||
@@ -401,3 +401,18 @@
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
.modal-kahoot {
|
||||
border: none;
|
||||
border-radius: 20px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.modal-kahoot-header {
|
||||
background-color: var(--kahoot-purple);
|
||||
color: white;
|
||||
border-bottom: none;
|
||||
}
|
||||
+1
-1
@@ -276,7 +276,7 @@ $(document).on("click", ".btn-abandonar-sala", function () {
|
||||
mensaje.text(
|
||||
"Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.",
|
||||
);
|
||||
botonConfirmar.text("Sí, abandonar");
|
||||
botonConfirmar.text("Sí, terminar partida");
|
||||
} else {
|
||||
titulo.text("¿Abandonar la sala?");
|
||||
mensaje.text(
|
||||
|
||||
+3
-2
@@ -43,7 +43,7 @@ function comprobarSesion() {
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end user-dropdown-menu" aria-labelledby="userDropdown">
|
||||
<li>
|
||||
<a class="dropdown-item d-flex align-items-center gap-2" href="perfil.html">
|
||||
<a class="dropdown-item d-flex align-items-center gap-2" href="perfil.php">
|
||||
<i class="fa-solid fa-user text-primary"></i> Perfil
|
||||
</a>
|
||||
</li>
|
||||
@@ -202,4 +202,5 @@ $(document).on("click", "#botonCerrarSesion", function (event) {
|
||||
window.location.href = "index.php";
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+5
-5
@@ -36,11 +36,11 @@ function renderizarTablaRanking(jugadores) {
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th scope="col" style="width: 10%;">#</th>
|
||||
<th scope="col" class="text-start" style="width: 35%;">Jugador</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-trophy text-warning me-1"></i> Vic</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-xmark text-danger me-1"></i> Der</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-bullseye text-success me-1"></i> Aciertos</th>
|
||||
<th scope="col" style="width: 10%;"><i class="fa-solid fa-percent text-info me-1"></i> % Vic</th>
|
||||
<th scope="col" class="text-start" style="width: 30%;"><i class="fa-solid fa-user"></i> <br> Jugador</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-trophy text-warning me-1"></i> <br> Victorias</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-xmark text-danger me-1"></i> <br> Derrotas</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-bullseye text-success me-1"></i> <br> Aciertos</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-medal text-info me-1"></i> <br> Efectividad</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
+25
-3
@@ -18,9 +18,21 @@ let preguntas = [];
|
||||
let indice = 0; // pregunta que se está mostrando
|
||||
let bloqueado = false; // true mientras se envía una respuesta o se ve el feedback
|
||||
let numeroAciertos = 0; // número de aciertos del jugador
|
||||
let tiempoRespuesta = 0;
|
||||
let intervaloTiempo;
|
||||
|
||||
$(document).ready(function () {
|
||||
idPartida = parseInt($("body").data("id-partida"), 10);
|
||||
// Obtenemos el idPartida de la URL
|
||||
// Ejemplo: juego.php?idPartida=3
|
||||
|
||||
const parametros = new URLSearchParams(window.location.search);
|
||||
|
||||
idPartida = parseInt(parametros.get("idPartida"), 10);
|
||||
|
||||
if (!idPartida || idPartida < 1) {
|
||||
mostrarError("La partida indicada no es válida.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Un solo listener para todos los botones de respuesta
|
||||
$("#respuestas").on("click", ".btn-answer", function () {
|
||||
@@ -72,6 +84,11 @@ function cargarPreguntas() {
|
||||
function mostrarPregunta() {
|
||||
const pregunta = preguntas[indice];
|
||||
|
||||
tiempoRespuesta = 0;
|
||||
intervaloTiempo = setInterval(function () {
|
||||
tiempoRespuesta++;
|
||||
}, 100);
|
||||
|
||||
bloqueado = false;
|
||||
|
||||
$("#textoPregunta").text(pregunta.nombrePregunta);
|
||||
@@ -100,9 +117,13 @@ function mostrarPregunta() {
|
||||
|
||||
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
|
||||
function responder($botonPulsado) {
|
||||
clearInterval(intervaloTiempo);
|
||||
console.log("Tiempo de respuesta: " + tiempoRespuesta / 10 + " segundos");
|
||||
|
||||
if (bloqueado) {
|
||||
return;
|
||||
}
|
||||
|
||||
bloqueado = true;
|
||||
|
||||
const pregunta = preguntas[indice];
|
||||
@@ -118,7 +139,8 @@ function responder($botonPulsado) {
|
||||
orden: "responder",
|
||||
idPartida: idPartida,
|
||||
idPartidaxPregunta: pregunta.idPartidaxPregunta,
|
||||
idRespuesta: idRespuesta,
|
||||
idRespuesta: idRespuesta,
|
||||
tiempoRespuesta: tiempoRespuesta,
|
||||
},
|
||||
success: function (datos) {
|
||||
if (datos.error) {
|
||||
@@ -216,4 +238,4 @@ function mostrarError(mensaje) {
|
||||
$("#feedback").html(
|
||||
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-27
@@ -1,26 +1,3 @@
|
||||
// COMPROBAR SESIÓN Y MOSTRAR NOMBRE/AVATAR
|
||||
// (antes en perfil.php)
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: { orden: "comprobarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (!respuesta.activa) {
|
||||
// Sin sesión: fuera de aquí
|
||||
window.location.href = "index.php";
|
||||
return;
|
||||
}
|
||||
|
||||
$("#nombre").text(respuesta.usuario.nombreUsuario || "Usuario");
|
||||
$("#fotoPerfil").attr(
|
||||
"src",
|
||||
respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg"
|
||||
);
|
||||
});
|
||||
|
||||
// =========================
|
||||
// MOSTRAR ESTADISTICAS
|
||||
// =========================
|
||||
@@ -73,8 +50,8 @@ function cambiarNombre() {
|
||||
$("#nuevoNombre").val("");
|
||||
|
||||
|
||||
if (typeof comprobarSesion === "function") {
|
||||
comprobarSesion();
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -133,8 +110,8 @@ $("#inputFoto").change(function () {
|
||||
);
|
||||
|
||||
// Actualizamos también el avatar superior en la cabecera
|
||||
if (typeof comprobarSesion === "function") {
|
||||
comprobarSesion();
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+72
-30
@@ -1,38 +1,80 @@
|
||||
$(document).ready(function () {
|
||||
const idPartida = $("body").data("id-partida");
|
||||
|
||||
comprobarEstadoPartida(idPartida);
|
||||
// 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");
|
||||
|
||||
const intervalo = setInterval(function () {
|
||||
comprobarEstadoPartida(idPartida, intervalo);
|
||||
}, 3000);
|
||||
comprobarEstadoPartida(idPartida);
|
||||
|
||||
const intervalo = setInterval(function () {
|
||||
comprobarEstadoPartida(idPartida, intervalo);
|
||||
}, 3000);
|
||||
});
|
||||
|
||||
function comprobarEstadoPartida(idPartida, intervalo = null) {
|
||||
$.ajax({
|
||||
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 (!idPartida || idPartida <= 0) return;
|
||||
|
||||
if (respuesta.terminada) {
|
||||
if (intervalo !== null) clearInterval(intervalo);
|
||||
|
||||
$("#pantalla-espera").fadeOut(400, function() {
|
||||
location.reload();
|
||||
});
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
console.log("Error de comunicación con el controlador.");
|
||||
$.ajax({
|
||||
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;
|
||||
}
|
||||
|
||||
if (respuesta.terminada === true || respuesta.terminada === "true") {
|
||||
if (intervalo !== null) {
|
||||
clearInterval(intervalo);
|
||||
}
|
||||
});
|
||||
|
||||
$("#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;
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Hay que estar logueado para jugar
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// La partida llega por la URL: juego.php?idPartida=3
|
||||
$idPartida = filter_input(INPUT_GET, 'idPartida', FILTER_VALIDATE_INT);
|
||||
|
||||
if (!$idPartida || $idPartida < 1) {
|
||||
header('Location: buscadorSala.php');
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
@@ -24,28 +8,48 @@ if (!$idPartida || $idPartida < 1) {
|
||||
<title>Proyecto Trivial</title>
|
||||
<link rel="stylesheet" href="css/juego.css">
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
|
||||
</head>
|
||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
||||
|
||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
||||
<body>
|
||||
|
||||
<!-- CABECERA Y PROGRESO -->
|
||||
|
||||
<div class="game-header">
|
||||
<span id="contadorPregunta">Cargando…</span>
|
||||
|
||||
<span id="contadorPregunta">
|
||||
Cargando…
|
||||
</span>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="progress-track">
|
||||
|
||||
<div class="progress-fill" id="barraProgreso"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de la Pregunta (lo rellena js/juego.js) -->
|
||||
<!-- PREGUNTA -->
|
||||
|
||||
<div class="question-container">
|
||||
<div id="textoPregunta">Cargando preguntas…</div>
|
||||
|
||||
<div id="textoPregunta">
|
||||
Cargando preguntas…
|
||||
</div>
|
||||
|
||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
||||
<!-- RESPUESTAS -->
|
||||
|
||||
<div class="answers-grid" id="respuestas"></div>
|
||||
|
||||
<!-- JAVASCRIPT -->
|
||||
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/juego.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+17
-4
@@ -1,3 +1,17 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Redirección si el usuario no ha iniciado sesión
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: login.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$nombreUsuario = htmlspecialchars($_SESSION['nombreUsuario'] ?? 'Usuario');
|
||||
$avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultProfile.jpeg');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
@@ -27,7 +41,7 @@
|
||||
|
||||
<body>
|
||||
|
||||
<div id="cabecera"></div>
|
||||
<?php include_once 'cabecera.php'; ?>
|
||||
|
||||
<div class="perfil-container">
|
||||
|
||||
@@ -48,14 +62,14 @@
|
||||
|
||||
<!-- Nombre -->
|
||||
<h1 id="nombre" class="nombre">
|
||||
|
||||
<?= $nombreUsuario ?>
|
||||
</h1>
|
||||
|
||||
<!-- FOTO DE PERFIL -->
|
||||
<div class="foto-container">
|
||||
|
||||
<img id="fotoPerfil"
|
||||
src="img/avatars/defaultProfile.jpeg"
|
||||
src="<?= $avatarUsuario ?>"
|
||||
alt="Foto de perfil"
|
||||
class="avatar rounded-circle">
|
||||
|
||||
@@ -295,7 +309,6 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<!-- Tu JavaScript -->
|
||||
<script>$("#cabecera").load("cabecera.php");</script>
|
||||
<script src="js/perfil.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
+9
-9
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/conexionBD.php';
|
||||
require_once __DIR__ . '/includes/conexionBD.php';
|
||||
|
||||
$idPartida = intval($_GET['idPartida'] ?? 0);
|
||||
if ($idPartida <= 0) {
|
||||
@@ -29,7 +29,7 @@ $primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
|
||||
$jugadoresFinales = [];
|
||||
$equiposFinales = [];
|
||||
|
||||
// Respuestas de velocidad (+2 o +1)
|
||||
// Respuestas de velocidad (+2 o +1) procesadas en la capa de la vista
|
||||
foreach ($listaJugadoresRaw as $jugador) {
|
||||
$idU = (int)$jugador['idUsuario'];
|
||||
$idE = (int)$jugador['idEquipo'];
|
||||
@@ -52,7 +52,6 @@ foreach ($listaJugadoresRaw as $jugador) {
|
||||
$aciertos++;
|
||||
$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) {
|
||||
$puntosTotalesJugador += 2;
|
||||
} else {
|
||||
@@ -77,7 +76,6 @@ foreach ($listaJugadoresRaw as $jugador) {
|
||||
$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($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
|
||||
?>
|
||||
@@ -89,7 +87,7 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Resultados - Trivial</title>
|
||||
<link rel="stylesheet" href="css/resultados.css">
|
||||
<script src="https://jquery.com"></script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
</head>
|
||||
<body data-id-partida="<?php echo $idPartida; ?>">
|
||||
|
||||
@@ -146,11 +144,13 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="contenedor-boton">
|
||||
<a href="/triviagmatico/buscadorSala.php" class="btn-inicio">Volver al Inicio 🏠</a>
|
||||
</div>
|
||||
|
||||
<div class="contenedor-boton">
|
||||
<a href="/triviagmatico/" id="btnVolverInicio" data-id="<?php echo $idPartida; ?>" class="btn-inicio">Volver al Inicio 🏠</a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="js/resultados.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user