29 Commits

Author SHA1 Message Date
dbvictor2002 9a41c04daf Eliminar vistas/eyy.md 2026-10-02 13:21:04 +02:00
dbvictor2002 060ea53992 Subir archivos a "vistas" 2026-10-02 13:20:57 +02:00
dbvictor2002 a8a4699bd4 Eliminar modelos/hola.md 2026-10-02 13:20:40 +02:00
dbvictor2002 85e5c2fc0b Subir archivos a "modelos" 2026-10-02 13:20:32 +02:00
v.rodriguezcamacho b58db59f93 carpetas nuevas 2026-10-02 13:19:57 +02:00
dbvictor2002 9ec2222d78 Eliminar vistaResultados.php 2026-10-02 13:08:04 +02:00
dbvictor2002 7344a0c31f Eliminar PartidaModelo.php 2026-10-02 13:07:53 +02:00
dbvictor2002 645e2abc77 Subir archivos a "js" 2026-10-02 12:40:40 +02:00
dbvictor2002 d9020a66c6 Subir archivos a "controladores" 2026-10-02 12:40:17 +02:00
dbvictor2002 9d59a9cc7c Subir archivos a "/" 2026-10-02 12:40:01 +02:00
jorge 8ffb769861 Merge pull request 'separar código para segur MVC' (#39) from perfil_mvc_nuevo into main
Reviewed-on: #39
2026-10-02 11:17:26 +02:00
margarita 1c3fbf2f90 separar código para segur MVC 2026-10-02 11:01:56 +02:00
Juanjo cd53cba69e Actualizar mysqulito/triviagmagicoDEFINITIVO.sql 2026-10-02 10:45:46 +02:00
jorge 5f407ce8f4 Merge pull request 'Arreglado categorias' (#38) from corregir_categorias into main
Reviewed-on: #38
2026-10-02 10:43:55 +02:00
Isaac d20b1fa7d7 Arreglado categorias 2026-10-02 10:42:45 +02:00
jorge 02e725e0f3 Merge pull request 'Add sincronizacion de jugadores en partida' (#37) from sincronizacion_jugadores into main
Reviewed-on: #37
2026-10-02 10:41:50 +02:00
alexis 3856db81ef Add sincronizacion de jugadores en partida 2026-10-02 10:40:01 +02:00
jorge bdc7bef169 Merge pull request 'Ahora se actualiza el nombre y la imagen nueva de forma dinámica' (#36) from perfil_cabecera into main
Reviewed-on: #36
2026-10-02 10:34:47 +02:00
v.rodriguezcamacho 963ab50f37 Ahora se actualiza el nombre y la imagen nueva de forma dinámica 2026-10-02 09:58:03 +02:00
jorge 9488d7cee7 Merge pull request 'Añadir tiempoRespuesta' (#33) from controlador_juego into main
Reviewed-on: #33
2026-10-02 09:42:55 +02:00
Isaac 0b8045544b Arreglado head de cabecera 2026-10-02 09:27:31 +02:00
jorge d67e4d76e2 Corregida cabecera.js 2026-10-02 09:21:23 +02:00
jorge 20131bbe7f Editar cabecera.html (antes de dominio correo) 2026-10-02 09:20:39 +02:00
jorge c624f06b88 Eliminacion includes en buscadorSala 2026-10-02 08:52:52 +02:00
jorge e879a92ac2 Modificación perfil para cabecera mvc 2026-10-02 08:52:00 +02:00
jorge c18576e97d Modificación header index e inclusión cabecera mvc 2026-10-02 08:50:57 +02:00
jorge fd4301d741 Modificación buscadorsala para cabecera mvc 2026-10-02 08:49:36 +02:00
jorge afff6cfb4a Modificación cabecera.js 2026-10-02 08:48:16 +02:00
Juanjo cbdbd8bc4b Añadir tiempoRespuesta 2026-10-01 14:12:36 +02:00
20 changed files with 2128 additions and 1810 deletions
+3 -2
View File
@@ -10,11 +10,12 @@
<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/buscadorSala.css">
<script src="js/jquery-4.0.0.min.js"></script>
</head>
<body>
<?php include_once("cabecera.php"); ?>
<header id="cabecera-container"></header>
<main class="container py-4">
@@ -99,9 +100,9 @@
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/jquery-4.0.0.min.js"></script>
<script src="js/sala.js"></script>
<script src="js/buscadorSala.js"></script>
<script src="js/cabecera.js"></script>
</body>
+18 -4
View File
@@ -1,3 +1,15 @@
<head>
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome para iconos -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<!-- Google Fonts para estilo Kahoot -->
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<!-- cabecera.html -->
<nav class="navbar navbar-expand-lg navbar-kahoot py-3 mb-4">
<div class="container">
@@ -84,13 +96,15 @@
<label for="regPasswordConfirm">Confirmar contraseña</label>
</div>
<input type="hidden" name="orden" value="registrar">
<div class="modal-footer">
<button type="button" class="btn btn-secondary rounded-pill px-3" data-bs-dismiss="modal">Cancelar</button>
<input type="submit" value="Registrarse" class="btn btn-success rounded-pill px-4" id="botonAceptarRegistro"></input>
</div>
</form>
<div id="errorRegistro" class="text-danger fw-bold mt-2"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary rounded-pill px-3" data-bs-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-success rounded-pill px-4" id="botonAceptarRegistro">Registrarse</button>
</div>
</div>
</div>
</div>
</body>
+1 -1
View File
@@ -1,6 +1,6 @@
<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/triviagmatico/includes/conexionBD.php';
require_once __DIR__ . '/../includes/conexionBD.php';
class Categoria{
+9 -2
View File
@@ -229,7 +229,13 @@ class Juego
* - la respuesta pertenece a esa pregunta
* - el usuario no ha respondido ya esa pregunta
*/
public static function registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta)
public static function registrarRespuesta(
$idPartida,
$idUsuario,
$idPartidaxPregunta,
$idRespuesta,
$tiempoRespuesta
)
{
$conexion = conexionBD();
if (is_array($conexion)) {
@@ -298,7 +304,8 @@ class Juego
null,
$idPartidaxPregunta,
$idUsuario,
$idRespuesta
$idRespuesta,
$tiempoRespuesta
);
$guardado = $almacenada->guardarRespuesta();
+21 -5
View File
@@ -132,23 +132,39 @@ class Partida
}
public function iniciarPartida(){
public function iniciarPartida()
{
$conexion = conexionBD();
if (is_array($conexion)) {
return $conexion;
}
try {
$consulta = $conexion->prepare("UPDATE partida SET fechaInicio=NOW() WHERE idPartida=:idPartida AND fechaInicio IS NULL");
$consulta->bindParam(":idPartida", $this->idPartida);
$consulta = $conexion->prepare("
UPDATE partida
SET fechaInicio = NOW()
WHERE idPartida = :idPartida
AND fechaInicio IS NULL
");
$consulta->bindParam(
":idPartida",
$this->idPartida
);
$consulta->execute();
return [
"exito" => "La partida ha comenzado.",
"exito_tecnico" => $this->idPartida
];
} catch (PDOException $error) {
return [
"error" => "Ocurrió un error al iniciar la partida.",
'error_tecnico' => $error->getMessage()
"error" => "ERROR REAL: " . $error->getMessage()
];
}
}
+2
View File
@@ -24,6 +24,8 @@ class Respuesta{
$consulta->bindParam(':idPregunta', $this->idPregunta);
$consulta->bindParam(':nombreRespuesta', $this->nombreRespuesta);
$consulta->bindParam(':correcta', $this->correcta);
$consulta->execute();
$respuesta = [
'exito' => 'La respuesta se guardó correctamente.',
+17 -7
View File
@@ -7,12 +7,14 @@ class RespuestaAlmacenada {
public $idPartidaxPregunta;
public $idUsuario;
public $idRespuesta;
public $tiempoRespuesta;
public function __construct($idRespuestaAlmacenada = null, $idPartidaxPregunta = null, $idUsuario = null, $idRespuesta = null) {
public function __construct($idRespuestaAlmacenada = null, $idPartidaxPregunta = null, $idUsuario = null, $idRespuesta = null, $tiempoRespuesta = null) {
$this->idRespuestaAlmacenada = $idRespuestaAlmacenada;
$this->idPartidaxPregunta = $idPartidaxPregunta;
$this->idUsuario = $idUsuario;
$this->idRespuesta = $idRespuesta;
$this->tiempoRespuesta = $tiempoRespuesta;
}
/**
@@ -20,25 +22,33 @@ class RespuestaAlmacenada {
*/
public function guardarRespuesta() {
$conexion = conexionBD();
if (is_array($conexion)) return $conexion;
if (is_array($conexion)) {
return $conexion;
}
try {
$sql = "INSERT INTO respuestaalmacenada (idPartidaxPregunta, idUsuario, idRespuesta)
VALUES (:idPartidaxPregunta, :idUsuario, :idRespuesta)";
$sql = "INSERT INTO respuestaalmacenada
(idPartidaxPregunta, idUsuario, idRespuesta, tiempoRespuesta)
VALUES
(:idPartidaxPregunta, :idUsuario, :idRespuesta, :tiempoRespuesta)";
$consulta = $conexion->prepare($sql);
$consulta->bindParam(':idPartidaxPregunta', $this->idPartidaxPregunta);
$consulta->bindParam(':idUsuario', $this->idUsuario);
$consulta->bindParam(':idRespuesta', $this->idRespuesta);
$consulta->bindParam(':tiempoRespuesta', $this->tiempoRespuesta);
$consulta->execute();
return [
'exito' => 'Respuesta del usuario almacenada correctamente.',
'exito_tecnico' => $conexion->lastInsertId()
'exito' => 'Respuesta almacenada correctamente.'
];
} catch (PDOException $error) {
return [
'error' => 'Ocurrió un error al guardar la respuesta del jugador.',
'error' => 'Ocurrió un error al guardar la respuesta.',
'error_tecnico' => $error->getMessage()
];
}
+20 -7
View File
@@ -74,20 +74,27 @@ switch ($orden) {
case 'responder':
if (!isset($_POST['idPartidaxPregunta']) || !isset($_POST['idRespuesta'])){
if (
!isset($_POST['idPartidaxPregunta']) ||
!isset($_POST['idRespuesta']) ||
!isset($_POST['tiempoRespuesta'])
) {
echo json_encode([
'error' => 'Faltan datos para registrar la respuesta.'
'error' => 'Faltan datos para registrar la respuestfdfa.'
]);
break;
}
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta']);
$idRespuesta = intval($_POST['idRespuesta']);
$tiempoRespuesta = intval($_POST['tiempoRespuesta']);
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0){
if (
$idPartidaxPregunta <= 0 ||
$idRespuesta <= 0 ||
$tiempoRespuesta < 0
) {
echo json_encode([
'error' => 'Los datos de la respuesta no son válidos.'
]);
@@ -95,9 +102,15 @@ switch ($orden) {
break;
}
// Registramos la respuesta del usuario
// Registramos la respuesta del usuario junto con su tiempo de respuesta
$resultado = Juego::registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta);
$resultado = Juego::registrarRespuesta(
$idPartida,
$idUsuario,
$idPartidaxPregunta,
$idRespuesta,
$tiempoRespuesta
);
echo json_encode($resultado);
+36 -2
View File
@@ -795,13 +795,47 @@ switch ($_POST['orden']) {
*/
$resultado = $partida->iniciar();
$resultado = $partida->iniciarPartida();
echo json_encode($resultado);
break;
case 'comprobarInicio':
if (!isset($_POST['idPartida'])) {
echo json_encode([
'error' => 'No se ha indicado la partida.'
]);
break;
}
$partida = new Partida();
$partida->idPartida =
intval($_POST['idPartida']);
$datosPartida = $partida->buscar();
if (!$datosPartida || isset($datosPartida['error'])) {
echo json_encode([
'error' => 'La partida no existe.'
]);
break;
}
echo json_encode([
'iniciada' => $datosPartida['fechaInicio'] !== null
]);
break;
// OBTENER LA PREGUNTA ACTUAL
@@ -933,7 +967,7 @@ switch ($_POST['orden']) {
) {
echo json_encode([
'error' => 'Faltan datos para registrar la respuesta.'
'error' => 'Faltan datos para registrar la respuestadd.'
]);
break;
+8 -47
View File
@@ -1,7 +1,7 @@
<?php
// controladores/controladorResultados.php
session_start();
require_once __DIR__ . '/../includes/conexionBD.php';
header('Content-Type: application/json; charset=utf-8');
if (!isset($_SESSION['idUsuario'])) {
@@ -26,7 +26,6 @@ if (is_array($conexion)) {
switch ($orden) {
case 'comprobarEstado':
try {
// 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 +37,6 @@ switch ($orden) {
$preguntasTotalesEsperadas = $totalJugadores * 10;
// 2. Contar cuántas respuestas reales se han guardado
$stmtRespuestas = $conexion->prepare("
SELECT COUNT(*)
FROM respuestaalmacenada ra
@@ -50,12 +48,9 @@ switch ($orden) {
$terminada = ($respuestasRespondidas >= $preguntasTotalesEsperadas && $preguntasTotalesEsperadas > 0);
// 3. Si ha terminado, guardamos los datos históricos una sola vez
if ($terminada && !isset($_SESSION['partidas_procesadas'][$idPartida])) {
if ($terminada && !isset($_SESSION['partidas_processed'][$idPartida])) {
$conexion->beginTransaction();
// --- CÁLCULO DE VELOCIDAD ---
if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) {
$_SESSION['primeros_en_acertar'][$idPartida] = [];
}
@@ -74,13 +69,11 @@ switch ($orden) {
foreach ($todosLosAciertos as $acierto) {
$idPxp = $acierto['idPartidaxPregunta'];
$idU = $acierto['idUsuario'];
if (!isset($_SESSION['primeros_en_acertar'][$idPartida][$idPxp])) {
$_SESSION['primeros_en_acertar'][$idPartida][$idPxp] = $idU;
}
}
// Consulta de aciertos
$stmtAciertos = $conexion->prepare("
SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida
FROM respuestaalmacenada ra
@@ -93,11 +86,7 @@ switch ($orden) {
$stmtAciertos->execute([':idPartida' => $idPartida]);
$jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC);
$updateAciertos = $conexion->prepare("
UPDATE usuario
SET aciertos = aciertos + :nuevos_aciertos
WHERE idUsuario = :idUsuario
");
$updateAciertos = $conexion->prepare("UPDATE usuario SET aciertos = aciertos + :nuevos_aciertos WHERE idUsuario = :idUsuario");
$puntosEquipos = [];
foreach ($jugadoresPartida as $jp) {
@@ -105,14 +94,9 @@ switch ($orden) {
$idE = (int)$jp['idEquipo'];
$nuevosAciertos = (int)$jp['aciertos_partida'];
$updateAciertos->execute([
':nuevos_aciertos' => $nuevosAciertos,
':idUsuario' => $idU
]);
$updateAciertos->execute([':nuevos_aciertos' => $nuevosAciertos, ':idUsuario' => $idU]);
if (!isset($puntosEquipos[$idE])) {
$puntosEquipos[$idE] = 0;
}
if (!isset($puntosEquipos[$idE])) { $puntosEquipos[$idE] = 0; }
$puntosEquipos[$idE] += $nuevosAciertos;
}
@@ -135,7 +119,6 @@ switch ($orden) {
foreach ($todosLosMiembros as $miembro) {
$idU = (int)$miembro['idUsuario'];
$idE = (int)$miembro['idEquipo'];
if ($idE === $idEquipoGanador) {
$updateVictoria->execute([':idUsuario' => $idU]);
} else {
@@ -144,23 +127,15 @@ switch ($orden) {
}
}
// 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 = $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;
}
echo json_encode(['terminada' => $terminada]);
} catch (PDOException $e) {
if ($conexion->inTransaction()) {
$conexion->rollBack();
}
if ($conexion->inTransaction()) { $conexion->rollBack(); }
echo json_encode(['error' => $e->getMessage()]);
}
break;
@@ -170,11 +145,9 @@ switch ($orden) {
$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
@@ -184,9 +157,7 @@ switch ($orden) {
$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
@@ -194,29 +165,22 @@ switch ($orden) {
");
$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]);
}
@@ -224,11 +188,8 @@ switch ($orden) {
$conexion->commit();
echo json_encode(['exito' => true, 'usuarios_quedan' => $jugadoresRestantes]);
} catch (PDOException $e) {
if ($conexion->inTransaction()) {
$conexion->rollBack();
}
if ($conexion->inTransaction()) { $conexion->rollBack(); }
echo json_encode(['error' => $e->getMessage()]);
}
break;
}
+10 -2
View File
@@ -4,13 +4,20 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Triviagmático</title>
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- FontAwesome para iconos -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<!-- Google Fonts para estilo Kahoot -->
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/index.css">
<script src="js/jquery-4.0.0.min.js"></script>
</head>
<body>
<?php include 'cabecera.php'; ?>
<header id="cabecera-container"></header>
<div class="container my-5">
<div class="row justify-content-center align-items-center g-4">
@@ -46,6 +53,7 @@
<!-- JS de Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/index.js"></script>
<script src="js/cabecera.js"></script>
</body>
</html>
+78 -63
View File
@@ -1,14 +1,19 @@
let idUsuarioSesion = null;
$(document).ready(function () {
// Cargar la cabecera HTML e iniciar comprobación de sesión SOLO al terminar de cargar
$("#cabecera-container").load("cabecera.html", function (response, status, xhr) {
if (status === "error") {
console.error("Error al cargar cabecera.html:", xhr.status, xhr.statusText);
} else {
comprobarSesion();
}
});
});
// Función auxiliar para escapar texto HTML
function escapeHTML(str) {
return $("<div>")
.text(str ?? "")
.html();
return $("<div>").text(str ?? "").html();
}
// Comprobar estado de sesión al cargar la página
@@ -16,24 +21,21 @@ function comprobarSesion() {
$.ajax({
method: "POST",
url: "controladores/controladorUsuario.php",
dataType: "json",
data: { orden: "comprobarSesion" },
}).done(function (respuesta) {
try {
if (typeof respuesta === "string") {
respuesta = JSON.parse(respuesta);
}
})
.done(function (respuesta) {
const contenedor = $("#contenedorUsuarioCabecera");
if (!contenedor.length) return; // Si aún no existe el contenedor en HTML, cancelamos
contenedor.empty();
if (respuesta.activa && respuesta.usuario) {
// Recogemos el idUsuario de la sesion en una variable para usarlo (no me lo volváis a borrar por favor os lo pido)
if (respuesta && respuesta.activa && respuesta.usuario) {
// Guardar idUsuario globalmente
idUsuarioSesion = respuesta.usuario.idUsuario;
// Obtenemos la ruta del avatar o la de por defecto
const avatarUrl =
respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg";
const avatarUrl = respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg";
// Usuario autenticado: Mostrar Menú Dropdown con el avatar
// Usuario autenticado: Menú desplegable
const htmlUsuario = `
<div class="dropdown">
<button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2"
@@ -58,15 +60,26 @@ function comprobarSesion() {
`;
contenedor.html(htmlUsuario);
// Si estamos en la página de perfil, rellenamos nombre y foto
if ($("#nombre").length) {
$("#nombre").text(respuesta.usuario.nombreUsuario);
// ?t= evita que el navegador enseñe la foto antigua en caché
$("#fotoPerfil").attr("src", avatarUrl + "?t=" + new Date().getTime());
}
// Si estamos en la página principal, mostramos el botón JUGAR
if ($("#colBotonJugar").length) {
$("#colBotonJugar").removeClass("d-none");
$("#colRanking")
.removeClass("col-lg-8")
.addClass("col-lg-7 col-xl-8");
$("#colRanking").removeClass("col-lg-8").addClass("col-lg-7 col-xl-8");
}
} else {
// No hay sesión: Mostrar botones de Login y Registro
// Si estamos en el perfil y no hay sesión, volvemos al inicio
if ($("#nombre").length) {
window.location.href = "index.php";
return;
}
// No hay sesión: Botones de Login y Registro
const htmlInvitado = `
<button type="button" class="btn btn-kahoot-login rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalLogin">
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar Sesión
@@ -77,22 +90,19 @@ function comprobarSesion() {
`;
contenedor.html(htmlInvitado);
// Si estamos en la página principal, ocultamos el botón JUGAR
if ($("#colBotonJugar").length) {
$("#colBotonJugar").addClass("d-none");
$("#colRanking")
.removeClass("col-lg-7 col-xl-8")
.addClass("col-lg-8");
$("#colRanking").removeClass("col-lg-7 col-xl-8").addClass("col-lg-8");
}
}
} catch (e) {
console.error("Error al procesar la respuesta de la sesión:", e);
}
})
.fail(function (xhr, status, error) {
console.error("Error en comprobarSesion AJAX:", error, xhr.responseText);
});
}
// Registro
$("#formRegistro").on("submit", function (event) {
// Registro de usuario
$(document).on("click", "#botonAceptarRegistro", function (event) {
event.preventDefault();
let nombreUsuario = $("#regNombre").val().trim();
@@ -100,61 +110,64 @@ $("#formRegistro").on("submit", function (event) {
let contrasena = $("#regPassword").val();
let contrasenaConfirmacion = $("#regPasswordConfirm").val();
$("#regNombre").removeClass("is-invalid");
$("#regEmail").removeClass("is-invalid");
$("#regPassword").removeClass("is-invalid");
$("#regPasswordConfirm").removeClass("is-invalid");
$("#errorRegistro").text("");
// Resetear estados visuales
$("#regNombre, #regEmail, #regPassword, #regPasswordConfirm").removeClass("is-invalid");
$("#errorRegistro").removeClass("text-danger text-success").text("").show();
if (contrasena !== contrasenaConfirmacion) {
$("#regPassword").addClass("is-invalid");
$("#regPasswordConfirm").addClass("is-invalid");
$("#errorRegistro").text("Las contraseñas no coinciden.");
$("#regPassword, #regPasswordConfirm").addClass("is-invalid");
$("#errorRegistro").addClass("text-danger").text("Las contraseñas no coinciden.");
return;
}
$.ajax({
method: "POST",
url: "controladores/controladorUsuario.php",
dataType: "json",
data: {
nombreUsuario: nombreUsuario,
email: email,
contrasena: contrasena,
orden: "registrarUsuario",
},
}).done(function (respuesta) {
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
})
.done(function (respuesta) {
if (respuesta.error) {
$("#errorRegistro").text(respuesta.error);
$("#regNombre").addClass("is-invalid");
$("#regEmail").addClass("is-invalid");
$("#errorRegistro").addClass("text-danger").text(respuesta.error);
$("#regNombre, #regEmail").addClass("is-invalid");
} else {
// Mostrar mensaje de confirmación
$("#errorRegistro")
.removeClass("text-danger")
.addClass("text-success")
.text(respuesta.exito);
.addClass("text-success fw-bold")
.text(respuesta.exito || "¡Registro completado con éxito!");
if ($("#formRegistro").length) {
$("#formRegistro")[0].reset();
}
// Recargar para iniciar sesión tras 1.5 segundos
setTimeout(function () {
location.reload();
}, 1000);
}, 1500);
}
})
.fail(function (xhr, status, error) {
console.error("Error en el registro:", error, xhr.responseText);
$("#errorRegistro").addClass("text-danger").text("Error de conexión con el servidor.");
});
});
// Login
$("#botonAceptarLogin").click(function (event) {
// Login de usuario
$(document).on("click", "#botonAceptarLogin", function (event) {
event.preventDefault();
let email = $("#loginEmail").val().trim();
let contrasena = $("#loginPassword").val();
let recuerdame = $("#recordar").is(":checked");
$("#loginEmail").removeClass("is-invalid");
$("#loginPassword").removeClass("is-invalid");
$("#errorLogin").text("");
$("#loginEmail, #loginPassword").removeClass("is-invalid");
$("#errorLogin").removeClass("text-success").addClass("text-danger").text("").show();
if (email === "" || contrasena === "") {
$("#errorLogin").text("Todos los campos son obligatorios.");
@@ -166,22 +179,26 @@ $("#botonAceptarLogin").click(function (event) {
$.ajax({
method: "POST",
url: "controladores/controladorUsuario.php",
dataType: "json",
data: {
email: email,
contrasena: contrasena,
recuerdame: recuerdame,
orden: "comprobarUsuario",
},
}).done(function (respuesta) {
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
})
.done(function (respuesta) {
if (respuesta.error) {
$("#loginEmail").addClass("is-invalid");
$("#loginPassword").addClass("is-invalid");
$("#loginEmail, #loginPassword").addClass("is-invalid");
$("#errorLogin").text(respuesta.error);
} else {
// Login correcto: Recargar la vista
location.reload();
}
})
.fail(function (xhr, status, error) {
console.error("Error en el login:", error, xhr.responseText);
$("#errorLogin").text("Error de conexión o respuesta no válida del servidor.");
});
});
@@ -192,15 +209,13 @@ $(document).on("click", "#botonCerrarSesion", function (event) {
$.ajax({
method: "POST",
url: "controladores/controladorUsuario.php",
dataType: "json",
data: { orden: "cerrarSesion" },
}).done(function (respuesta) {
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
if (respuesta.error) {
console.log(respuesta.error);
} else {
})
.done(function (respuesta) {
window.location.href = "index.php";
})
.fail(function () {
window.location.href = "index.php";
}
});
});
+88 -11
View File
@@ -118,7 +118,12 @@ 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");
console.log(
"Tiempo de respuesta: " +
tiempoRespuesta / 10 +
" segundos"
);
if (bloqueado) {
return;
@@ -127,7 +132,29 @@ function responder($botonPulsado) {
bloqueado = true;
const pregunta = preguntas[indice];
const idRespuesta = parseInt($botonPulsado.attr("data-id-respuesta"), 10);
const idRespuesta = parseInt(
$botonPulsado.attr("data-id-respuesta"),
10
);
console.log("PREGUNTA ACTUAL:", pregunta);
console.log(
"idPartidaxPregunta:",
pregunta.idPartidaxPregunta
);
console.log(
"idRespuesta:",
idRespuesta
);
console.log(
"tiempoRespuesta:",
tiempoRespuesta
);
console.log(
"idPartida:",
idPartida
);
$("#respuestas").addClass("bloqueado");
@@ -135,46 +162,96 @@ function responder($botonPulsado) {
url: URL_CONTROLADOR,
type: "POST",
dataType: "json",
data: {
orden: "responder",
idPartida: idPartida,
idPartidaxPregunta: pregunta.idPartidaxPregunta,
idRespuesta: idRespuesta,
tiempoRespuesta: tiempoRespuesta,
tiempoRespuesta: tiempoRespuesta
},
success: function (datos) {
console.log("RESPUESTA DEL SERVIDOR:", datos);
if (datos.error) {
// No se guardó: dejamos que vuelva a intentarlo
$("#feedback").text(datos.error).removeClass("ok").addClass("ko");
$("#feedback")
.text(datos.error)
.removeClass("ok")
.addClass("ko");
$("#respuestas").removeClass("bloqueado");
bloqueado = false;
return;
}
pregunta.respondida = true;
mostrarFeedback($botonPulsado, datos);
mostrarFeedback(
$botonPulsado,
datos
);
setTimeout(function () {
if (datos.terminada || indice >= preguntas.length - 1) {
if (
datos.terminada ||
indice >= preguntas.length - 1
) {
terminar();
} else {
indice++;
$("#respuestas").removeClass("bloqueado");
$("#respuestas")
.removeClass("bloqueado");
mostrarPregunta();
}
}, PAUSA_FEEDBACK);
},
error: function () {
error: function (xhr, status, error) {
console.error(
"ERROR AJAX RESPONDER"
);
console.error(
"HTTP:",
xhr.status
);
console.error(
"ERROR:",
error
);
console.error(
"RESPUESTA:",
xhr.responseText
);
$("#feedback")
.text("No se pudo guardar la respuesta. Inténtalo de nuevo.")
.text(
"No se pudo guardar la respuesta. Inténtalo de nuevo."
)
.removeClass("ok")
.addClass("ko");
$("#respuestas").removeClass("bloqueado");
bloqueado = false;
},
}
});
}
// Marca la respuesta correcta en verde y atenúa el resto
function mostrarFeedback($botonPulsado, datos) {
$("#respuestas .btn-answer").each(function () {
+6 -6
View File
@@ -50,10 +50,9 @@ function cambiarNombre() {
$("#nuevoNombre").val("");
if (typeof comprobarEstadoSesion === "function") {
comprobarEstadoSesion();
}
comprobarSesion();
}
});
}
@@ -71,6 +70,7 @@ function borrarNombre() {
function seleccionarFoto() {
$("#inputFoto").click();
}
$("#inputFoto").change(function () {
@@ -80,6 +80,7 @@ $("#inputFoto").change(function () {
return;
}
// Comprobamos que sea una imagen
if (!archivo.type.startsWith("image/")) {
alert("El archivo seleccionado no es una imagen.");
@@ -110,9 +111,8 @@ $("#inputFoto").change(function () {
);
// Actualizamos también el avatar superior en la cabecera
if (typeof comprobarEstadoSesion === "function") {
comprobarEstadoSesion();
}
comprobarSesion();
}
});
});
+107 -38
View File
@@ -263,14 +263,15 @@ function mostrarSala(partida, equipos, jugadores) {
if (esHost) {
botonIniciarHTML = `
<a
href="juego.php?idPartida=${partida.idPartida}"
class="btn btn-success btn-lg px-4">
<button
type="button"
class="btn btn-success btn-lg px-4 btn-iniciar-partida"
data-id-partida="${partida.idPartida}">
<i class="bi bi-controller"></i>
¡Iniciar Partida!
</a>
</button>
`;
}
@@ -313,7 +314,97 @@ function mostrarSala(partida, equipos, jugadores) {
`;
contenedor.html(salaHTML);
if (!partida.fechaInicio) {
iniciarComprobacionPartida(partida.idPartida);
}
}
let intervaloComprobarPartida = null;
function iniciarComprobacionPartida(idPartida) {
if (intervaloComprobarPartida) {
clearInterval(intervaloComprobarPartida);
}
intervaloComprobarPartida = setInterval(function () {
$.ajax({
url: "controladores/controladorPartida.php",
type: "POST",
dataType: "json",
data: {
orden: "comprobarInicio",
idPartida: idPartida,
},
success: function (respuesta) {
if (respuesta.iniciada) {
clearInterval(intervaloComprobarPartida);
window.location.href = "juego.php?idPartida=" + idPartida;
}
},
});
}, 1000);
}
$(document).on("click", ".btn-iniciar-partida", function () {
const boton = $(this);
const idPartida = boton.data("id-partida");
boton.prop("disabled", true);
boton.html(`
<span class="spinner-border spinner-border-sm"></span>
Iniciando...
`);
$.ajax({
url: "controladores/controladorPartida.php",
type: "POST",
dataType: "json",
data: {
orden: "iniciar",
idPartida: idPartida,
},
success: function (respuesta) {
if (respuesta.error) {
alert(respuesta.error);
boton.prop("disabled", false);
boton.html(`
<i class="bi bi-controller"></i>
¡Iniciar Partida!
`);
return;
}
// El host entra directamente
window.location.href = "juego.php?idPartida=" + idPartida;
},
error: function () {
alert("Ocurrió un error al iniciar la partida.");
boton.prop("disabled", false);
boton.html(`
<i class="bi bi-controller"></i>
¡Iniciar Partida!
`);
},
});
});
$(document).on("click", ".btn-unirse-equipo", function () {
const boton = $(this);
@@ -364,8 +455,7 @@ $(document).on("click", ".btn-abandonar-sala", function () {
botonAbandonarReferencia = $(this);
const esHost =
$(this).data("es-host") === true ||
$(this).data("es-host") === "true";
$(this).data("es-host") === true || $(this).data("es-host") === "true";
const titulo = $("#modalAbandonarSalaLabel");
@@ -384,9 +474,7 @@ $(document).on("click", ".btn-abandonar-sala", function () {
} else {
titulo.text("¿Abandonar la sala?");
mensaje.text(
"Si sales de la sala, perderás tu lugar en el equipo.",
);
mensaje.text("Si sales de la sala, perderás tu lugar en el equipo.");
botonConfirmar.text("Sí, salir");
}
@@ -399,17 +487,13 @@ $(document).on("click", ".btn-abandonar-sala", function () {
});
$(document).on("click", "#btnConfirmarAbandonar", function () {
const modalEl =
document.getElementById("modalAbandonarSala");
const modalEl = document.getElementById("modalAbandonarSala");
const modalInstance =
bootstrap.Modal.getInstance(modalEl);
const modalInstance = bootstrap.Modal.getInstance(modalEl);
const btnConfirmar = $(this);
btnConfirmar
.prop("disabled", true)
.text("Saliendo...");
btnConfirmar.prop("disabled", true).text("Saliendo...");
$.ajax({
url: "controladores/controladorEquipoxUsuario.php",
@@ -421,9 +505,7 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
},
success: function (respuesta) {
btnConfirmar
.prop("disabled", false)
.text("Sí, salir");
btnConfirmar.prop("disabled", false).text("Sí, salir");
if (modalInstance) {
modalInstance.hide();
@@ -449,16 +531,11 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
},
error: function (xhr, status, error) {
console.error(
"Error al salir de la sala:",
error
);
console.error("Error al salir de la sala:", error);
alert("No se pudo salir de la sala.");
btnConfirmar
.prop("disabled", false)
.text("Sí, salir");
btnConfirmar.prop("disabled", false).text("Sí, salir");
if (modalInstance) {
modalInstance.hide();
@@ -473,16 +550,11 @@ function escapeHTML(texto) {
.html();
}
function mostrarEquipos(
partida,
equipos,
jugadores
) {
function mostrarEquipos(partida, equipos, jugadores) {
let equiposHTML = "";
equipos.forEach(function (equipo) {
const jugadoresEquipo =
jugadores.filter(function (jugador) {
const jugadoresEquipo = jugadores.filter(function (jugador) {
return jugador.idEquipo == equipo.idEquipo;
});
@@ -490,8 +562,7 @@ function mostrarEquipos(
if (jugadoresEquipo.length > 0) {
jugadoresEquipo.forEach(function (jugador) {
const esHost =
jugador.idUsuario == partida.idUsuario;
const esHost = jugador.idUsuario == partida.idUsuario;
jugadoresHTML += `
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${
@@ -507,9 +578,7 @@ function mostrarEquipos(
}
</span>
${escapeHTML(
jugador.nombreUsuario
)}
${escapeHTML(jugador.nombreUsuario)}
</div>
${
+37
View File
@@ -0,0 +1,37 @@
<?php
// modelos/PartidaModelo.php
class PartidaModelo {
private $conexion;
public function __construct($conexion) {
$this->conexion = $conexion;
}
// Obtiene los jugadores mapeados en la partida actual
public function obtenerJugadoresPartida($idPartida) {
$stmt = $this->conexion->prepare("
SELECT u.idUsuario, u.nombreUsuario, e.idEquipo, e.nombreEquipo
FROM equipoxpartida exp
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
INNER JOIN equipo e ON exu.idEquipo = e.idEquipo
WHERE exp.idPartida = :idPartida
");
$stmt->execute([':idPartida' => $idPartida]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Obtiene las respuestas guardadas por un usuario específico
public function obtenerRespuestasUsuario($idPartida, $idUsuario) {
$stmtRespuestas = $this->conexion->prepare("
SELECT ra.idPartidaxPregunta, r.correcta
FROM respuestaalmacenada ra
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario
");
$stmtRespuestas->execute([':idPartida' => $idPartida, ':idUsuario' => $idUsuario]);
return $stmtRespuestas->fetchAll(PDO::FETCH_ASSOC);
}
}
+293 -205
View File
@@ -1,42 +1,42 @@
/*M!999999\- enable the sandbox mode */
-- MariaDB dump 10.19-11.7.2-MariaDB, for Win64 (AMD64)
-- phpMyAdmin SQL Dump
-- version 5.2.3
-- https://www.phpmyadmin.net/
--
-- Host: localhost Database: triviagmatico
-- ------------------------------------------------------
-- Server version 10.4.32-MariaDB
-- Host: localhost:3306
-- Generation Time: Oct 02, 2026 at 08:40 AM
-- Server version: 8.4.3
-- PHP Version: 8.3.30
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*M!100616 SET @OLD_NOTE_VERBOSITY=@@NOTE_VERBOSITY, NOTE_VERBOSITY=0 */;
--
-- Database: `triviagmatico`
--
-- --------------------------------------------------------
--
-- Table structure for table `categoria`
--
DROP TABLE IF EXISTS `categoria`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `categoria` (
`idCategoria` int(11) NOT NULL AUTO_INCREMENT,
`nombreCategoria` varchar(50) NOT NULL,
PRIMARY KEY (`idCategoria`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idCategoria` int NOT NULL,
`nombreCategoria` varchar(50) COLLATE utf8mb4_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `categoria`
--
LOCK TABLES `categoria` WRITE;
/*!40000 ALTER TABLE `categoria` DISABLE KEYS */;
INSERT INTO `categoria` VALUES
INSERT INTO `categoria` (`idCategoria`, `nombreCategoria`) VALUES
(4, 'Historia'),
(5, 'Geografía'),
(6, 'Ciencia'),
@@ -50,98 +50,69 @@ INSERT INTO `categoria` VALUES
(14, 'Tecnología'),
(15, 'Cultura'),
(16, 'Gastronomía');
/*!40000 ALTER TABLE `categoria` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `equipo`
--
DROP TABLE IF EXISTS `equipo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `equipo` (
`idEquipo` int(11) NOT NULL AUTO_INCREMENT,
`nombreEquipo` varchar(50) NOT NULL,
PRIMARY KEY (`idEquipo`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idEquipo` int NOT NULL,
`nombreEquipo` varchar(50) COLLATE utf8mb4_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `equipo`
--
LOCK TABLES `equipo` WRITE;
/*!40000 ALTER TABLE `equipo` DISABLE KEYS */;
INSERT INTO `equipo` VALUES
INSERT INTO `equipo` (`idEquipo`, `nombreEquipo`) VALUES
(1, 'Los Trivialistas'),
(2, 'Los Cerebritos'),
(3, 'Los Sabios'),
(4, 'Los Exploradores');
/*!40000 ALTER TABLE `equipo` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `equipoxpartida`
--
DROP TABLE IF EXISTS `equipoxpartida`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `equipoxpartida` (
`idEquipoxPartida` int(11) NOT NULL AUTO_INCREMENT,
`idPartida` int(11) DEFAULT NULL,
`idEquipo` int(11) DEFAULT NULL,
PRIMARY KEY (`idEquipoxPartida`),
KEY `FK idEquipo tabla equipo` (`idEquipo`),
KEY `FK idPartida tabla partida` (`idPartida`),
CONSTRAINT `FK idEquipo tabla equipo` FOREIGN KEY (`idEquipo`) REFERENCES `equipo` (`idEquipo`),
CONSTRAINT `FK idPartida tabla partida` FOREIGN KEY (`idPartida`) REFERENCES `partida` (`idPartida`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idEquipoxPartida` int NOT NULL,
`idPartida` int DEFAULT NULL,
`idEquipo` int DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `equipoxpartida`
--
LOCK TABLES `equipoxpartida` WRITE;
/*!40000 ALTER TABLE `equipoxpartida` DISABLE KEYS */;
INSERT INTO `equipoxpartida` VALUES
INSERT INTO `equipoxpartida` (`idEquipoxPartida`, `idPartida`, `idEquipo`) VALUES
(1, 1, 1),
(2, 1, 2),
(3, 2, 2),
(4, 2, 3),
(5, 3, 3),
(6, 3, 4);
/*!40000 ALTER TABLE `equipoxpartida` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `equipoxusuario`
--
DROP TABLE IF EXISTS `equipoxusuario`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `equipoxusuario` (
`idEquipoxUsuario` int(11) NOT NULL AUTO_INCREMENT,
`idUsuario` int(11) NOT NULL,
`idEquipo` int(11) NOT NULL,
PRIMARY KEY (`idEquipoxUsuario`),
KEY `idUsuario` (`idUsuario`),
KEY `idEquipo` (`idEquipo`),
CONSTRAINT `equipoxusuario_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`),
CONSTRAINT `equipoxusuario_ibfk_2` FOREIGN KEY (`idEquipo`) REFERENCES `equipo` (`idEquipo`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idEquipoxUsuario` int NOT NULL,
`idUsuario` int NOT NULL,
`idEquipo` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `equipoxusuario`
--
LOCK TABLES `equipoxusuario` WRITE;
/*!40000 ALTER TABLE `equipoxusuario` DISABLE KEYS */;
INSERT INTO `equipoxusuario` VALUES
INSERT INTO `equipoxusuario` (`idEquipoxUsuario`, `idUsuario`, `idEquipo`) VALUES
(1, 1, 1),
(2, 2, 1),
(3, 3, 1),
@@ -152,68 +123,48 @@ INSERT INTO `equipoxusuario` VALUES
(8, 8, 3),
(9, 9, 4),
(10, 10, 4);
/*!40000 ALTER TABLE `equipoxusuario` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `partida`
--
DROP TABLE IF EXISTS `partida`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `partida` (
`idPartida` int(11) NOT NULL AUTO_INCREMENT,
`nombrePartida` varchar(100) NOT NULL,
`idUsuario` int(11) NOT NULL,
`fechaCreacion` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fechaInicio` DATETIME NULL,
`fechaFin` DATETIME NULL,
PRIMARY KEY (`idPartida`),
KEY `FK idUsuario tabla usuario` (`idUsuario`),
CONSTRAINT `FK idUsuario tabla usuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idPartida` int NOT NULL,
`nombrePartida` varchar(100) COLLATE utf8mb4_spanish_ci NOT NULL,
`idUsuario` int NOT NULL,
`fechaCreacion` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fechaInicio` datetime DEFAULT NULL,
`fechaFin` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `partida`
--
LOCK TABLES `partida` WRITE;
/*!40000 ALTER TABLE `partida` DISABLE KEYS */;
INSERT INTO `partida` (idPartida, nombrePartida, idUsuario, fechaInicio, fechaFin) VALUES
(1,'Partida de prueba 1',1, NULL, NULL),
(2,'Partida de prueba 2',4, NULL, NULL),
(3,'Partida de prueba 3',9, NULL, NULL);
/*!40000 ALTER TABLE `partida` ENABLE KEYS */;
UNLOCK TABLES;
INSERT INTO `partida` (`idPartida`, `nombrePartida`, `idUsuario`, `fechaCreacion`, `fechaInicio`, `fechaFin`) VALUES
(1, 'Partida de prueba 1', 1, '2026-10-01 09:03:18', NULL, NULL),
(2, 'Partida de prueba 2', 4, '2026-10-01 09:03:18', NULL, NULL),
(3, 'Partida de prueba 3', 9, '2026-10-01 09:03:18', NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `partidaxpregunta`
--
DROP TABLE IF EXISTS `partidaxpregunta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `partidaxpregunta` (
`idPartidaxPregunta` int(11) NOT NULL AUTO_INCREMENT,
`idPartida` int(11) NOT NULL,
`idPregunta` int(11) NOT NULL,
PRIMARY KEY (`idPartidaxPregunta`),
KEY `idPartida` (`idPartida`),
KEY `idPregunta` (`idPregunta`),
CONSTRAINT `partidaxpregunta_ibfk_1` FOREIGN KEY (`idPartida`) REFERENCES `partida` (`idPartida`),
CONSTRAINT `partidaxpregunta_ibfk_2` FOREIGN KEY (`idPregunta`) REFERENCES `pregunta` (`idPregunta`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idPartidaxPregunta` int NOT NULL,
`idPartida` int NOT NULL,
`idPregunta` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `partidaxpregunta`
--
LOCK TABLES `partidaxpregunta` WRITE;
/*!40000 ALTER TABLE `partidaxpregunta` DISABLE KEYS */;
INSERT INTO `partidaxpregunta` VALUES
INSERT INTO `partidaxpregunta` (`idPartidaxPregunta`, `idPartida`, `idPregunta`) VALUES
(1, 1, 2140),
(2, 1, 2141),
(3, 1, 2142),
@@ -234,34 +185,24 @@ INSERT INTO `partidaxpregunta` VALUES
(18, 2, 2158),
(19, 2, 2159),
(20, 2, 2160);
/*!40000 ALTER TABLE `partidaxpregunta` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `pregunta`
--
DROP TABLE IF EXISTS `pregunta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `pregunta` (
`idPregunta` int(11) NOT NULL AUTO_INCREMENT,
`idCategoria` int(11) NOT NULL,
`nombrePregunta` varchar(255) NOT NULL,
PRIMARY KEY (`idPregunta`),
UNIQUE KEY `nombrePregunta` (`nombrePregunta`),
KEY `idCategoria` (`idCategoria`),
CONSTRAINT `pregunta_ibfk_1` FOREIGN KEY (`idCategoria`) REFERENCES `categoria` (`idCategoria`)
) ENGINE=InnoDB AUTO_INCREMENT=2535 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idPregunta` int NOT NULL,
`idCategoria` int NOT NULL,
`nombrePregunta` varchar(255) COLLATE utf8mb4_spanish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `pregunta`
--
LOCK TABLES `pregunta` WRITE;
/*!40000 ALTER TABLE `pregunta` DISABLE KEYS */;
INSERT INTO `pregunta` VALUES
INSERT INTO `pregunta` (`idPregunta`, `idCategoria`, `nombrePregunta`) VALUES
(2140, 4, '¿En qué año llegó Cristóbal Colón a América?'),
(2141, 5, '¿Cuál es la capital de España?'),
(2142, 6, '¿Qué planeta es conocido como el planeta rojo?'),
@@ -487,42 +428,29 @@ INSERT INTO `pregunta` VALUES
(2525, 6, '¿Qué científico estudió la electricidad y los rayos con una cometa?'),
(2531, 14, '¿Qué unidad se utiliza normalmente para medir almacenamiento digital?'),
(2534, 16, '¿Qué dulce español se consume tradicionalmente en Navidad?');
/*!40000 ALTER TABLE `pregunta` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `respuesta`
--
DROP TABLE IF EXISTS `respuesta`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `respuesta` (
`idRespuesta` int(11) NOT NULL AUTO_INCREMENT,
`idPregunta` int(11) NOT NULL,
`nombreRespuesta` varchar(255) NOT NULL,
`correcta` tinyint(1) DEFAULT 0,
PRIMARY KEY (`idRespuesta`),
KEY `idPregunta` (`idPregunta`),
CONSTRAINT `respuesta_ibfk_1` FOREIGN KEY (`idPregunta`) REFERENCES `pregunta` (`idPregunta`)
) ENGINE=InnoDB AUTO_INCREMENT=4935 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idRespuesta` int NOT NULL,
`idPregunta` int NOT NULL,
`nombreRespuesta` varchar(255) COLLATE utf8mb4_spanish_ci NOT NULL,
`correcta` tinyint(1) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `respuesta`
--
LOCK TABLES `respuesta` WRITE;
/*!40000 ALTER TABLE `respuesta` DISABLE KEYS */;
INSERT INTO `respuesta` VALUES
INSERT INTO `respuesta` (`idRespuesta`, `idPregunta`, `nombreRespuesta`, `correcta`) VALUES
(3355, 2140, '1492', 1),
(3356, 2140, '1512', 0),
(3357, 2140, '1453', 0),
(3358, 2140, '1600', 0),
(3399,2141,'Madrid',1),
(3400,2141,'Barcelona',0),
(3401,2141,'Sevilla',0),
(3402,2141,'Valencia',0),
(3363, 2142, 'Marte', 1),
(3364, 2142, 'Venus', 0),
(3365, 2142, 'Júpiter', 0),
@@ -559,6 +487,10 @@ INSERT INTO `respuesta` VALUES
(3396, 2150, 'Julio César', 0),
(3397, 2150, 'Nerón', 0),
(3398, 2150, 'Trajano', 0),
(3399, 2141, 'Madrid', 1),
(3400, 2141, 'Barcelona', 0),
(3401, 2141, 'Sevilla', 0),
(3402, 2141, 'Valencia', 0),
(3403, 2152, 'Oxígeno', 1),
(3404, 2152, 'Helio', 0),
(3405, 2152, 'Hidrógeno', 0),
@@ -1415,70 +1347,44 @@ INSERT INTO `respuesta` VALUES
(4932, 2534, 'Croissant', 0),
(4933, 2534, 'Brownie', 0),
(4934, 2534, 'Tiramisú', 0);
/*!40000 ALTER TABLE `respuesta` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `respuestaalmacenada`
--
DROP TABLE IF EXISTS `respuestaalmacenada`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `respuestaalmacenada` (
`idRespuestaAlmacenada` int(11) NOT NULL AUTO_INCREMENT,
`idPartidaxPregunta` int(11) NOT NULL,
`idUsuario` int(11) NOT NULL,
`idRespuesta` int(11) NOT NULL,
`primero` tinyint(1) DEFAULT 0,
PRIMARY KEY (`idRespuestaAlmacenada`),
KEY `idPartidaxPregunta` (`idPartidaxPregunta`),
KEY `idUsuario` (`idUsuario`),
KEY `idRespuesta` (`idRespuesta`),
CONSTRAINT `respuestaalmacenada_ibfk_1` FOREIGN KEY (`idPartidaxPregunta`) REFERENCES `partidaxpregunta` (`idPartidaxPregunta`) ON DELETE CASCADE,
CONSTRAINT `respuestaalmacenada_ibfk_2` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`) ON DELETE CASCADE,
CONSTRAINT `respuestaalmacenada_ibfk_3` FOREIGN KEY (`idRespuesta`) REFERENCES `respuesta` (`idRespuesta`) ON DELETE CASCADE
`idRespuestaAlmacenada` int NOT NULL,
`idPartidaxPregunta` int NOT NULL,
`idUsuario` int NOT NULL,
`idRespuesta` int NOT NULL,
`tiempoRespuesta` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `respuestaalmacenada`
--
LOCK TABLES `respuestaalmacenada` WRITE;
/*!40000 ALTER TABLE `respuestaalmacenada` DISABLE KEYS */;
/*!40000 ALTER TABLE `respuestaalmacenada` ENABLE KEYS */;
UNLOCK TABLES;
-- --------------------------------------------------------
--
-- Table structure for table `usuario`
--
DROP TABLE IF EXISTS `usuario`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `usuario` (
`idUsuario` int(11) NOT NULL AUTO_INCREMENT,
`nombreUsuario` varchar(50) NOT NULL,
`contrasena` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL,
`avatar` varchar(200) DEFAULT NULL,
`cookie` varchar(200) DEFAULT NULL,
`aciertos` int(11) NOT NULL,
`victorias` int(11) NOT NULL,
`derrotas` int(11) NOT NULL,
PRIMARY KEY (`idUsuario`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
`idUsuario` int NOT NULL,
`nombreUsuario` varchar(50) COLLATE utf8mb4_spanish_ci NOT NULL,
`contrasena` varchar(100) COLLATE utf8mb4_spanish_ci NOT NULL,
`email` varchar(50) COLLATE utf8mb4_spanish_ci NOT NULL,
`avatar` varchar(200) COLLATE utf8mb4_spanish_ci DEFAULT NULL,
`cookie` varchar(200) COLLATE utf8mb4_spanish_ci DEFAULT NULL,
`aciertos` int NOT NULL,
`victorias` int NOT NULL,
`derrotas` int NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_spanish_ci;
--
-- Dumping data for table `usuario`
--
LOCK TABLES `usuario` WRITE;
/*!40000 ALTER TABLE `usuario` DISABLE KEYS */;
INSERT INTO `usuario` VALUES
INSERT INTO `usuario` (`idUsuario`, `nombreUsuario`, `contrasena`, `email`, `avatar`, `cookie`, `aciertos`, `victorias`, `derrotas`) VALUES
(1, 'Carlos', '1234', 'carlos@test.com', NULL, NULL, 125, 18, 7),
(2, 'Lucia', '1234', 'lucia@test.com', NULL, NULL, 98, 14, 9),
(3, 'Miguel', 'abcd', 'miguel@test.com', NULL, NULL, 210, 32, 5),
@@ -1488,21 +1394,203 @@ INSERT INTO `usuario` VALUES
(7, 'Javier', '1234', 'javier@test.com', NULL, NULL, 185, 27, 8),
(8, 'Marta', 'qwer', 'marta@test.com', NULL, NULL, 67, 9, 13),
(9, 'Alejandro', 'qwer', 'alejandro@test.com', NULL, NULL, 240, 41, 4),
(10,'Elena','hola','elena@test.com',NULL,NULL,112,16,10);
/*!40000 ALTER TABLE `usuario` ENABLE KEYS */;
UNLOCK TABLES;
(10, 'Elena', 'hola', 'elena@test.com', NULL, NULL, 112, 16, 10),
(11, 'papa', '$2y$10$tj.YXSaXhMbh63zYuwbnSuc8bVNzIHI3zZHs1cCmS.iNN25fRbZ5u', 'pepe', 'img/avatars/defaultProfile.jpeg', NULL, 13, 6, 0);
--
-- Dumping routines for database 'triviagmatico'
-- Indexes for dumped tables
--
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
--
-- Indexes for table `categoria`
--
ALTER TABLE `categoria`
ADD PRIMARY KEY (`idCategoria`);
--
-- Indexes for table `equipo`
--
ALTER TABLE `equipo`
ADD PRIMARY KEY (`idEquipo`);
--
-- Indexes for table `equipoxpartida`
--
ALTER TABLE `equipoxpartida`
ADD PRIMARY KEY (`idEquipoxPartida`),
ADD KEY `FK idEquipo tabla equipo` (`idEquipo`),
ADD KEY `FK idPartida tabla partida` (`idPartida`);
--
-- Indexes for table `equipoxusuario`
--
ALTER TABLE `equipoxusuario`
ADD PRIMARY KEY (`idEquipoxUsuario`),
ADD KEY `idUsuario` (`idUsuario`),
ADD KEY `idEquipo` (`idEquipo`);
--
-- Indexes for table `partida`
--
ALTER TABLE `partida`
ADD PRIMARY KEY (`idPartida`),
ADD KEY `FK idUsuario tabla usuario` (`idUsuario`);
--
-- Indexes for table `partidaxpregunta`
--
ALTER TABLE `partidaxpregunta`
ADD PRIMARY KEY (`idPartidaxPregunta`),
ADD KEY `idPartida` (`idPartida`),
ADD KEY `idPregunta` (`idPregunta`);
--
-- Indexes for table `pregunta`
--
ALTER TABLE `pregunta`
ADD PRIMARY KEY (`idPregunta`),
ADD UNIQUE KEY `nombrePregunta` (`nombrePregunta`),
ADD KEY `idCategoria` (`idCategoria`);
--
-- Indexes for table `respuesta`
--
ALTER TABLE `respuesta`
ADD PRIMARY KEY (`idRespuesta`),
ADD KEY `idPregunta` (`idPregunta`);
--
-- Indexes for table `respuestaalmacenada`
--
ALTER TABLE `respuestaalmacenada`
ADD PRIMARY KEY (`idRespuestaAlmacenada`),
ADD KEY `idPartidaxPregunta` (`idPartidaxPregunta`),
ADD KEY `idUsuario` (`idUsuario`),
ADD KEY `idRespuesta` (`idRespuesta`);
--
-- Indexes for table `usuario`
--
ALTER TABLE `usuario`
ADD PRIMARY KEY (`idUsuario`),
ADD UNIQUE KEY `email` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categoria`
--
ALTER TABLE `categoria`
MODIFY `idCategoria` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT for table `equipo`
--
ALTER TABLE `equipo`
MODIFY `idEquipo` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
--
-- AUTO_INCREMENT for table `equipoxpartida`
--
ALTER TABLE `equipoxpartida`
MODIFY `idEquipoxPartida` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `equipoxusuario`
--
ALTER TABLE `equipoxusuario`
MODIFY `idEquipoxUsuario` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=19;
--
-- AUTO_INCREMENT for table `partida`
--
ALTER TABLE `partida`
MODIFY `idPartida` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `partidaxpregunta`
--
ALTER TABLE `partidaxpregunta`
MODIFY `idPartidaxPregunta` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=101;
--
-- AUTO_INCREMENT for table `pregunta`
--
ALTER TABLE `pregunta`
MODIFY `idPregunta` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2535;
--
-- AUTO_INCREMENT for table `respuesta`
--
ALTER TABLE `respuesta`
MODIFY `idRespuesta` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4935;
--
-- AUTO_INCREMENT for table `respuestaalmacenada`
--
ALTER TABLE `respuestaalmacenada`
MODIFY `idRespuestaAlmacenada` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=51;
--
-- AUTO_INCREMENT for table `usuario`
--
ALTER TABLE `usuario`
MODIFY `idUsuario` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `equipoxpartida`
--
ALTER TABLE `equipoxpartida`
ADD CONSTRAINT `FK idEquipo tabla equipo` FOREIGN KEY (`idEquipo`) REFERENCES `equipo` (`idEquipo`),
ADD CONSTRAINT `FK idPartida tabla partida` FOREIGN KEY (`idPartida`) REFERENCES `partida` (`idPartida`);
--
-- Constraints for table `equipoxusuario`
--
ALTER TABLE `equipoxusuario`
ADD CONSTRAINT `equipoxusuario_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`),
ADD CONSTRAINT `equipoxusuario_ibfk_2` FOREIGN KEY (`idEquipo`) REFERENCES `equipo` (`idEquipo`);
--
-- Constraints for table `partida`
--
ALTER TABLE `partida`
ADD CONSTRAINT `FK idUsuario tabla usuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`);
--
-- Constraints for table `partidaxpregunta`
--
ALTER TABLE `partidaxpregunta`
ADD CONSTRAINT `partidaxpregunta_ibfk_1` FOREIGN KEY (`idPartida`) REFERENCES `partida` (`idPartida`),
ADD CONSTRAINT `partidaxpregunta_ibfk_2` FOREIGN KEY (`idPregunta`) REFERENCES `pregunta` (`idPregunta`);
--
-- Constraints for table `pregunta`
--
ALTER TABLE `pregunta`
ADD CONSTRAINT `pregunta_ibfk_1` FOREIGN KEY (`idCategoria`) REFERENCES `categoria` (`idCategoria`);
--
-- Constraints for table `respuesta`
--
ALTER TABLE `respuesta`
ADD CONSTRAINT `respuesta_ibfk_1` FOREIGN KEY (`idPregunta`) REFERENCES `pregunta` (`idPregunta`);
--
-- Constraints for table `respuestaalmacenada`
--
ALTER TABLE `respuestaalmacenada`
ADD CONSTRAINT `respuestaalmacenada_ibfk_1` FOREIGN KEY (`idPartidaxPregunta`) REFERENCES `partidaxpregunta` (`idPartidaxPregunta`) ON DELETE CASCADE,
ADD CONSTRAINT `respuestaalmacenada_ibfk_2` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`) ON DELETE CASCADE,
ADD CONSTRAINT `respuestaalmacenada_ibfk_3` FOREIGN KEY (`idRespuesta`) REFERENCES `respuesta` (`idRespuesta`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*M!100616 SET NOTE_VERBOSITY=@OLD_NOTE_VERBOSITY */;
-- Dump completed on 2026-09-25 10:00:41
+4 -20
View File
@@ -1,17 +1,3 @@
<?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">
@@ -41,7 +27,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
<body>
<?php include_once 'cabecera.php'; ?>
<header id="cabecera-container"></header>
<div class="perfil-container">
@@ -61,15 +47,13 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
<div class="col-md-6 text-center">
<!-- Nombre -->
<h1 id="nombre" class="nombre">
<?= $nombreUsuario ?>
</h1>
<h1 id="nombre" class="nombre"></h1>
<!-- FOTO DE PERFIL -->
<div class="foto-container">
<img id="fotoPerfil"
src="<?= $avatarUsuario ?>"
src="img/avatars/defaultProfile.jpeg"
alt="Foto de perfil"
class="avatar rounded-circle">
@@ -310,7 +294,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
<!-- Tu JavaScript -->
<script src="js/perfil.js"></script>
<script src="js/cabecera.js"></script>
</body>
</html>
+11 -101
View File
@@ -1,6 +1,8 @@
<?php
// resultados.php (Actúa como el Controlador Frontal de esta pantalla)
session_start();
require_once __DIR__ . '/includes/conexionBD.php';
require_once __DIR__ . '/modelos/PartidaModelo.php';
$idPartida = intval($_GET['idPartida'] ?? 0);
if ($idPartida <= 0) {
@@ -12,37 +14,22 @@ if (is_array($conexion)) {
die("Error de conexión a la base de datos.");
}
// Obtener listado de jugadores y sus equipos en esta partida
$stmt = $conexion->prepare("
SELECT u.idUsuario, u.nombreUsuario, e.idEquipo, e.nombreEquipo
FROM equipoxpartida exp
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
INNER JOIN equipo e ON exu.idEquipo = e.idEquipo
WHERE exp.idPartida = :idPartida
");
$stmt->execute([':idPartida' => $idPartida]);
$listaJugadoresRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Instanciamos el modelo
$modelo = new PartidaModelo($conexion);
// Obtenemos datos crudos del modelo
$listaJugadoresRaw = $modelo->obtenerJugadoresPartida($idPartida);
$primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
$jugadoresFinales = [];
$equiposFinales = [];
// Respuestas de velocidad (+2 o +1) procesadas en la capa de la vista
// Procesamiento de la lógica de negocio (puntos y velocidad)
foreach ($listaJugadoresRaw as $jugador) {
$idU = (int)$jugador['idUsuario'];
$idE = (int)$jugador['idEquipo'];
$stmtRespuestas = $conexion->prepare("
SELECT ra.idPartidaxPregunta, r.correcta
FROM respuestaalmacenada ra
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario
");
$stmtRespuestas->execute([':idPartida' => $idPartida, ':idUsuario' => $idU]);
$respuestasUsuario = $stmtRespuestas->fetchAll(PDO::FETCH_ASSOC);
$respuestasUsuario = $modelo->obtenerRespuestasUsuario($idPartida, $idU);
$aciertos = 0;
$puntosTotalesJugador = 0;
@@ -52,6 +39,7 @@ foreach ($listaJugadoresRaw as $jugador) {
$aciertos++;
$idPxp = $resp['idPartidaxPregunta'];
// Regula si es el más rápido (+2) o normal (+1)
if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) {
$puntosTotalesJugador += 2;
} else {
@@ -76,86 +64,8 @@ foreach ($listaJugadoresRaw as $jugador) {
$equiposFinales[$idE]['puntos'] += $puntosTotalesJugador;
}
// Ordenaciones de rankings
usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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">
<script src="js/jquery-4.0.0.min.js"></script>
</head>
<body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor">
<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>
<div class="loader"></div>
</div>
<div id="pantalla-resultados" class="contenedor" style="display:none;">
<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>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Equipo</th>
<th>Puntos Totales</th>
</tr>
</thead>
<tbody>
<?php foreach ($equiposFinales as $index => $eq): ?>
<tr class="<?php echo $index === 0 ? 'top-team' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($eq['nombre']); ?></td>
<td><strong><?php echo $eq['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2>Rendimiento Individual</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Jugador</th>
<th>Equipo</th>
<th>Aciertos</th>
<th>Puntos Logrados</th>
</tr>
</thead>
<tbody>
<?php foreach ($jugadoresFinales as $index => $jug): ?>
<tr class="<?php echo $index === 0 ? 'top-player' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($jug['nombre']); ?></td>
<td><?php echo htmlspecialchars($jug['equipo']); ?></td>
<td><?php echo $jug['aciertos']; ?> / 10</td>
<td><strong><?php echo $jug['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="contenedor-boton">
<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>
<script src="js/resultados.js"></script>
</body>
</html>
require_once __DIR__ . '/vistas/vistaResultados.php';
+72
View File
@@ -0,0 +1,72 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resultados - Trivial</title>
<link rel="stylesheet" href="css/resultados.css">
<script src="js/jquery-4.0.0.min.js"></script>
</head>
<body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor">
<h2>⌛ Esperando a que todos los jugadores terminen...</h2>
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
<div class="loader"></div>
</div>
<div id="pantalla-resultados" class="contenedor" style="display:none;">
<h1>🏆 Resultados de la Partida 🏆</h1>
<h2>Clasificación por Equipos</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Equipo</th>
<th>Puntos Totales</th>
</tr>
</thead>
<tbody>
<?php foreach ($equiposFinales as $index => $eq): ?>
<tr class="<?php echo $index === 0 ? 'top-team' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($eq['nombre']); ?></td>
<td><strong><?php echo $eq['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2>Rendimiento Individual</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Jugador</th>
<th>Equipo</th>
<th>Aciertos</th>
<th>Puntos Logrados</th>
</tr>
</thead>
<tbody>
<?php foreach ($jugadoresFinales as $index => $jug): ?>
<tr class="<?php echo $index === 0 ? 'top-player' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($jug['nombre']); ?></td>
<td><?php echo htmlspecialchars($jug['equipo']); ?></td>
<td><?php echo $jug['aciertos']; ?> / 10</td>
<td><strong><?php echo $jug['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<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>