16 Commits

Author SHA1 Message Date
alexis 3856db81ef Add sincronizacion de jugadores en partida 2026-10-02 10:40:01 +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
jorge 46bfb7ea62 Merge pull request 'Ahora pide el @ a la hora de registrar el correo electronico' (#28) from dominio_correo into main
Reviewed-on: #28
2026-10-01 14:15:47 +02:00
Juanjo cbdbd8bc4b Añadir tiempoRespuesta 2026-10-01 14:12:36 +02:00
jorge 8bea83460b Merge pull request 'Ajustado CSS de resultados.php para consistencia con el proyecto.' (#30) from css_resultados into main
Reviewed-on: #30
2026-10-01 14:10:46 +02:00
v.rodriguezcamacho 83b1ae90c6 Cambio pasado a cabecera.html y cabecera.php ha sido eliminado 2026-10-01 13:47:21 +02:00
Isaac d994f09f7d Ajustado CSS de resultados.php para consistencia con el proyecto.
Importante: He cambiado la ruta del "Volver al inicio" a $_ENV['urlBase']
2026-10-01 13:46:40 +02:00
v.rodriguezcamacho 90a2ad1256 Ahora pide el @ a la hora de registrar el correo electronico 2026-10-01 13:18:12 +02:00
17 changed files with 974 additions and 464 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="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/index.css">
<link rel="stylesheet" href="css/buscadorSala.css"> <link rel="stylesheet" href="css/buscadorSala.css">
<script src="js/jquery-4.0.0.min.js"></script>
</head> </head>
<body> <body>
<?php include_once("cabecera.php"); ?> <header id="cabecera-container"></header>
<main class="container py-4"> <main class="container py-4">
@@ -99,9 +100,9 @@
</div> </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> <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/sala.js"></script>
<script src="js/buscadorSala.js"></script> <script src="js/buscadorSala.js"></script>
<script src="js/cabecera.js"></script>
</body> </body>
+110
View File
@@ -0,0 +1,110 @@
<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">
<a class="navbar-brand" href="index.php">
<img src="img/favicon/favicon.svg" alt="TRIVIAGMÁTICO" class="me-2" style="height: 35px;">
TRIVIAGMÁTICO
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
<!-- Contenedor dinámico de usuario/botones -->
<div class="d-flex align-items-center gap-3" id="contenedorUsuarioCabecera"></div>
</div>
</div>
</nav>
<!-- MODAL DE LOGIN -->
<div class="modal fade" id="modalLogin" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-dark">
<div class="modal-header">
<h1 class="modal-title fs-5 fw-bold" id="loginModalLabel">
<i class="fa-solid fa-right-to-bracket text-primary me-2"></i>Iniciar sesión
</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
</div>
<div class="modal-body">
<form id="formLogin">
<div class="form-floating mb-3">
<input type="email" class="form-control border-dark" id="loginEmail" name="email" placeholder="Correo electrónico" required>
<label for="loginEmail">Correo electrónico</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="loginPassword" name="contrasena" placeholder="Contraseña" required>
<label for="loginPassword">Contraseña</label>
</div>
<div class="form-check">
<input class="form-check-input" id="recordar" name="recordar" type="checkbox" />
<label for="recordar" class="small">Recuérdeme durante 10 días</label>
</div>
<input type="hidden" name="orden" value="validar">
</form>
<div id="errorLogin" 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-primary rounded-pill px-4" id="botonAceptarLogin">Entrar</button>
</div>
</div>
</div>
</div>
<!-- MODAL DE REGISTRO -->
<div class="modal fade" id="modalRegistro" tabindex="-1" aria-labelledby="registroModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-dark">
<div class="modal-header">
<h1 class="modal-title fs-5 fw-bold" id="registroModalLabel">
<i class="fa-solid fa-user-plus text-success me-2"></i>Registrarse
</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
</div>
<div class="modal-body">
<form id="formRegistro">
<div class="form-floating mb-3">
<input type="text" class="form-control border-dark" id="regNombre" name="nombreUsuario" placeholder="Nombre" required>
<label for="regNombre">Nombre</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control border-dark" id="regEmail" name="email" placeholder="Correo electrónico" required>
<label for="regEmail">Correo electrónico</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="regPassword" name="contrasena" placeholder="Contraseña" required>
<label for="regPassword">Contraseña</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="regPasswordConfirm" name="contrasenaConfirm" placeholder="Confirmar contraseña" required>
<label for="regPasswordConfirm">Confirmar contraseña</label>
</div>
<input type="hidden" name="orden" value="registrar">
</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>
-108
View File
@@ -1,108 +0,0 @@
<!-- 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>
<nav class="navbar navbar-expand-lg navbar-kahoot py-3 mb-4">
<div class="container">
<a class="navbar-brand" href="index.php">
<img src="img/favicon/favicon.svg" alt="TRIVIAGMÁTICO" class="me-2" style="height: 35px;">
TRIVIAGMÁTICO
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
<!-- Contenedor dinámico de usuario/botones -->
<div class="d-flex align-items-center gap-3" id="contenedorUsuarioCabecera">
</div>
</div>
</div>
</nav>
<!-- MODAL DE LOGIN -->
<div class="modal fade" id="modalLogin" tabindex="-1" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-dark">
<div class="modal-header">
<h1 class="modal-title fs-5 fw-bold" id="loginModalLabel">
<i class="fa-solid fa-right-to-bracket text-primary me-2"></i>Iniciar sesión
</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
</div>
<div class="modal-body">
<form id="formLogin">
<div class="form-floating mb-3">
<input type="email" class="form-control border-dark" id="loginEmail" name="email" placeholder="Correo electrónico" required>
<label for="loginEmail">Correo electrónico</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="loginPassword" name="contrasena" placeholder="Contraseña" required>
<label for="loginPassword">Contraseña</label>
</div>
<div class="form-check">
<input class="form-check-input" id="recordar" name="recordar" type="checkbox" />
<label for="recordar" class="small">Recuérdeme durante 10 días</label>
</div>
<input type="hidden" name="orden" value="validar">
</form>
<div id="errorLogin" 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-primary rounded-pill px-4" id="botonAceptarLogin">Entrar</button>
</div>
</div>
</div>
</div>
<!-- MODAL DE REGISTRO -->
<div class="modal fade" id="modalRegistro" tabindex="-1" aria-labelledby="registroModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content border-dark">
<div class="modal-header">
<h1 class="modal-title fs-5 fw-bold" id="registroModalLabel">
<i class="fa-solid fa-user-plus text-success me-2"></i>Registrarse
</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
</div>
<div class="modal-body">
<form id="formRegistro">
<div class="form-floating mb-3">
<input type="text" class="form-control border-dark" id="regNombre" name="nombreUsuario" placeholder="Nombre" required>
<label for="regNombre">Nombre</label>
</div>
<div class="form-floating mb-3">
<input type="email" class="form-control border-dark" id="regEmail" name="email" placeholder="Correo electrónico" required>
<label for="regEmail">Correo electrónico</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="regPassword" name="contrasena" placeholder="Contraseña" required>
<label for="regPassword">Contraseña</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control border-dark" id="regPasswordConfirm" name="contrasenaConfirm" placeholder="Confirmar contraseña" required>
<label for="regPasswordConfirm">Confirmar contraseña</label>
</div>
<input type="hidden" name="orden" value="registrar">
</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>
<script src="js/cabecera.js"></script>
+9 -2
View File
@@ -229,7 +229,13 @@ class Juego
* - la respuesta pertenece a esa pregunta * - la respuesta pertenece a esa pregunta
* - el usuario no ha respondido ya 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(); $conexion = conexionBD();
if (is_array($conexion)) { if (is_array($conexion)) {
@@ -298,7 +304,8 @@ class Juego
null, null,
$idPartidaxPregunta, $idPartidaxPregunta,
$idUsuario, $idUsuario,
$idRespuesta $idRespuesta,
$tiempoRespuesta
); );
$guardado = $almacenada->guardarRespuesta(); $guardado = $almacenada->guardarRespuesta();
+23 -7
View File
@@ -132,26 +132,42 @@ class Partida
} }
public function iniciarPartida(){ public function iniciarPartida()
{
$conexion = conexionBD(); $conexion = conexionBD();
if (is_array($conexion)){
if (is_array($conexion)) {
return $conexion; return $conexion;
} }
try { 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(); $consulta->execute();
return [ return [
"exito" => "La partida ha comenzado.", "exito" => "La partida ha comenzado.",
"exito_tecnico" => $this->idPartida "exito_tecnico" => $this->idPartida
]; ];
} catch (PDOException $error) { } catch (PDOException $error) {
return [ return [
"error" => "Ocurrió un error al iniciar la partida.", "error" => "ERROR REAL: " . $error->getMessage()
'error_tecnico' => $error->getMessage()
]; ];
} }
} }
public function finalizar(){ public function finalizar(){
+2
View File
@@ -24,6 +24,8 @@ class Respuesta{
$consulta->bindParam(':idPregunta', $this->idPregunta); $consulta->bindParam(':idPregunta', $this->idPregunta);
$consulta->bindParam(':nombreRespuesta', $this->nombreRespuesta); $consulta->bindParam(':nombreRespuesta', $this->nombreRespuesta);
$consulta->bindParam(':correcta', $this->correcta); $consulta->bindParam(':correcta', $this->correcta);
$consulta->execute(); $consulta->execute();
$respuesta = [ $respuesta = [
'exito' => 'La respuesta se guardó correctamente.', 'exito' => 'La respuesta se guardó correctamente.',
+18 -8
View File
@@ -7,12 +7,14 @@ class RespuestaAlmacenada {
public $idPartidaxPregunta; public $idPartidaxPregunta;
public $idUsuario; public $idUsuario;
public $idRespuesta; 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->idRespuestaAlmacenada = $idRespuestaAlmacenada;
$this->idPartidaxPregunta = $idPartidaxPregunta; $this->idPartidaxPregunta = $idPartidaxPregunta;
$this->idUsuario = $idUsuario; $this->idUsuario = $idUsuario;
$this->idRespuesta = $idRespuesta; $this->idRespuesta = $idRespuesta;
$this->tiempoRespuesta = $tiempoRespuesta;
} }
/** /**
@@ -20,29 +22,37 @@ class RespuestaAlmacenada {
*/ */
public function guardarRespuesta() { public function guardarRespuesta() {
$conexion = conexionBD(); $conexion = conexionBD();
if (is_array($conexion)) return $conexion;
if (is_array($conexion)) {
return $conexion;
}
try { try {
$sql = "INSERT INTO respuestaalmacenada (idPartidaxPregunta, idUsuario, idRespuesta) $sql = "INSERT INTO respuestaalmacenada
VALUES (:idPartidaxPregunta, :idUsuario, :idRespuesta)"; (idPartidaxPregunta, idUsuario, idRespuesta, tiempoRespuesta)
VALUES
(:idPartidaxPregunta, :idUsuario, :idRespuesta, :tiempoRespuesta)";
$consulta = $conexion->prepare($sql); $consulta = $conexion->prepare($sql);
$consulta->bindParam(':idPartidaxPregunta', $this->idPartidaxPregunta); $consulta->bindParam(':idPartidaxPregunta', $this->idPartidaxPregunta);
$consulta->bindParam(':idUsuario', $this->idUsuario); $consulta->bindParam(':idUsuario', $this->idUsuario);
$consulta->bindParam(':idRespuesta', $this->idRespuesta); $consulta->bindParam(':idRespuesta', $this->idRespuesta);
$consulta->bindParam(':tiempoRespuesta', $this->tiempoRespuesta);
$consulta->execute(); $consulta->execute();
return [ return [
'exito' => 'Respuesta del usuario almacenada correctamente.', 'exito' => 'Respuesta almacenada correctamente.'
'exito_tecnico' => $conexion->lastInsertId()
]; ];
} catch (PDOException $error) { } catch (PDOException $error) {
return [ return [
'error' => 'Ocurrió un error al guardar la respuesta del jugador.', 'error' => 'Ocurrió un error al guardar la respuesta.',
'error_tecnico' => $error->getMessage() 'error_tecnico' => $error->getMessage()
]; ];
} }
} }
/** /**
* Obtiene los aciertos totales de un usuario en una partida específica. * Obtiene los aciertos totales de un usuario en una partida específica.
+21 -8
View File
@@ -74,20 +74,27 @@ switch ($orden) {
case 'responder': case 'responder':
if (!isset($_POST['idPartidaxPregunta']) || !isset($_POST['idRespuesta'])){ if (
!isset($_POST['idPartidaxPregunta']) ||
!isset($_POST['idRespuesta']) ||
!isset($_POST['tiempoRespuesta'])
) {
echo json_encode([ echo json_encode([
'error' => 'Faltan datos para registrar la respuesta.' 'error' => 'Faltan datos para registrar la respuestfdfa.'
]); ]);
break; break;
} }
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta']); $idPartidaxPregunta = intval($_POST['idPartidaxPregunta']);
$idRespuesta = intval($_POST['idRespuesta']); $idRespuesta = intval($_POST['idRespuesta']);
$tiempoRespuesta = intval($_POST['tiempoRespuesta']);
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0){ if (
$idPartidaxPregunta <= 0 ||
$idRespuesta <= 0 ||
$tiempoRespuesta < 0
) {
echo json_encode([ echo json_encode([
'error' => 'Los datos de la respuesta no son válidos.' 'error' => 'Los datos de la respuesta no son válidos.'
]); ]);
@@ -95,13 +102,19 @@ switch ($orden) {
break; 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); echo json_encode($resultado);
break; break;
// Finalizar la partida y registrar los aciertos del usuario // Finalizar la partida y registrar los aciertos del usuario
+37 -3
View File
@@ -246,7 +246,7 @@ switch ($_POST['orden']) {
// Asignamos el ID real de la pregunta a la partida // Asignamos el ID real de la pregunta a la partida
$partida->asignarPregunta($idPreguntaAleatoria); $partida->asignarPregunta($idPreguntaAleatoria);
} }
}//fin shile } //fin shile
/* /*
@@ -795,13 +795,47 @@ switch ($_POST['orden']) {
*/ */
$resultado = $partida->iniciar(); $resultado = $partida->iniciarPartida();
echo json_encode($resultado); echo json_encode($resultado);
break; 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 // OBTENER LA PREGUNTA ACTUAL
@@ -933,7 +967,7 @@ switch ($_POST['orden']) {
) { ) {
echo json_encode([ echo json_encode([
'error' => 'Faltan datos para registrar la respuesta.' 'error' => 'Faltan datos para registrar la respuestadd.'
]); ]);
break; break;
+1
View File
@@ -121,6 +121,7 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 15px; gap: 15px;
text-decoration: none;
} }
.btn-play-kahoot:hover { .btn-play-kahoot:hover {
+377 -114
View File
@@ -1,179 +1,442 @@
/* ========================================================================== /* ==========================================================================
ESTILOS GENERALES Y FONDO VARIABLES DEL PROYECTO
========================================================================== */ ========================================================================== */
:root {
--kahoot-purple: #46178f;
--kahoot-purple-dark: #35116f;
--kahoot-blue: #1368ce;
--kahoot-blue-dark: #0c4891;
--kahoot-red: #e21b3c;
--kahoot-yellow: #ffa602;
--kahoot-yellow-dark: #d88900;
--kahoot-green: #26890c;
--kahoot-green-hover: #1f6f09;
--background: #f2f2f2;
--text-dark: #333333;
--text-muted: #666666;
--white: #ffffff;
}
/* ==========================================================================
ESTILOS GENERALES
========================================================================== */
* { * {
margin: 0; margin: 0;
padding: 0; padding: 0;
box-shadow: none;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; font-family: 'Fredoka', sans-serif;
background-color: #f0f4f8; background-color: var(--background);
color: #2c3e50; color: var(--text-dark);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh; min-height: 100vh;
padding: 20px; padding: 30px 20px;
} }
/* Contenedor principal estilo tarjeta */
.contenedor {
width: 100%;
max-width: 900px;
background: #ffffff;
padding: 40px;
border-radius: 16px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
text-align: center;
animation: fadeIn 0.5s ease-in-out;
}
h1 {
font-size: 2.5rem;
color: #1a365d;
margin-bottom: 30px;
}
h2 {
font-size: 1.6rem;
color: #2b6cb0;
margin-top: 30px;
margin-bottom: 15px;
text-align: left;
border-bottom: 2px solid #e2e8f0;
padding-bottom: 8px;
}
p {
font-size: 1.1rem;
color: #718096;
margin-bottom: 30px;
}
/* ========================================================================== /* ==========================================================================
PANTALLA DE ESPERA Y ANIMACIÓN DE CARGA (LOADER) CONTENEDOR PRINCIPAL
========================================================================== */ ========================================================================== */
#pantalla-espera {
padding: 60px 20px; .contenedor {
width: 100%;
max-width: 1000px;
margin: 0 auto;
background-color: var(--white);
border-radius: 20px;
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.10);
overflow: hidden;
} }
/* ==========================================================================
PANTALLA DE ESPERA
========================================================================== */
#pantalla-espera {
padding: 70px 30px;
text-align: center;
}
#pantalla-espera h2 {
color: var(--kahoot-purple);
font-size: 2rem;
font-weight: 700;
margin-bottom: 15px;
}
#pantalla-espera p {
color: var(--text-muted);
font-size: 1.1rem;
margin-bottom: 35px;
}
/* ==========================================================================
LOADER
========================================================================== */
.loader { .loader {
width: 60px; width: 65px;
height: 60px; height: 65px;
border: 6px solid #e2e8f0;
border-top: 6px solid #3182ce;
border-radius: 50%;
margin: 0 auto; margin: 0 auto;
animation: spin 1.2s linear infinite;
border: 7px solid #e5e5e5;
border-top-color: var(--kahoot-purple);
border-radius: 50%;
animation: spin 1s linear infinite;
} }
@keyframes spin { @keyframes spin {
0% { transform: rotate(0deg); } from {
100% { transform: rotate(360deg); } transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
} }
/* ========================================================================== /* ==========================================================================
TABLAS DE CLASIFICACIÓN (RANKING) CABECERA DE RESULTADOS
========================================================================== */ ========================================================================== */
.tabla-ranking {
width: 100%; #pantalla-resultados {
border-collapse: collapse; padding: 40px;
margin-bottom: 20px;
font-size: 1.05rem;
} }
.tabla-ranking th, #pantalla-resultados h1 {
.tabla-ranking td { text-align: center;
padding: 16px 20px; color: var(--kahoot-yellow);
font-size: 2.6rem;
font-weight: 700;
margin-bottom: 35px;
text-shadow: 2px 2px 0 rgba(70, 23, 143, 0.10);
}
#pantalla-resultados h2 {
display: flex;
align-items: center;
gap: 10px;
font-size: 1.5rem;
font-weight: 700;
margin-top: 35px;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 3px solid #eee;
}
/* ==========================================================================
TABLAS
========================================================================== */
.tabla-ranking {
width: 100%;
border-collapse: separate;
border-spacing: 0;
overflow: hidden;
background-color: #fff;
border: 2px solid #eeeeee;
border-radius: 15px;
margin-bottom: 30px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.06);
}
/* Cabecera */
.tabla-ranking thead th {
background-color: var(--kahoot-purple);
color: white;
padding: 15px 18px;
font-size: 0.95rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.3px;
text-align: left; text-align: left;
} }
.tabla-ranking th { .tabla-ranking thead th:first-child {
background-color: #2d3748; border-top-left-radius: 12px;
color: #ffffff;
font-weight: 600;
text-transform: uppercase;
font-size: 0.9rem;
letter-spacing: 0.5px;
} }
/* Alinear los puntos y aciertos a la derecha para mejor lectura numérica */ .tabla-ranking thead th:last-child {
.tabla-ranking th:last-child, border-top-right-radius: 12px;
.tabla-ranking td:last-child {
text-align: right;
} }
.tabla-ranking tr {
border-bottom: 1px solid #e2e8f0; /* Celdas */
transition: background-color 0.2s;
.tabla-ranking tbody td {
padding: 16px 18px;
font-size: 1rem;
font-weight: 500;
border-bottom: 1px solid #eeeeee;
color: var(--text-dark);
}
/* Última fila */
.tabla-ranking tbody tr:last-child td {
border-bottom: none;
}
/* Hover */
.tabla-ranking tbody tr {
transition:
transform 0.15s ease,
background-color 0.15s ease;
} }
.tabla-ranking tbody tr:hover { .tabla-ranking tbody tr:hover {
background-color: #f7fafc; background-color: #f7f3ff;
} }
/* ========================================================================== /* ==========================================================================
RESALTADO DE GANADORES (1º PUESTO) COLUMNA DE POSICIÓN
========================================================================== */ ========================================================================== */
/* Fila del Equipo Ganador y Jugador Ganador */
.tabla-ranking tr.top-team, .tabla-ranking tbody td:first-child {
.tabla-ranking tr.top-player { font-weight: 700;
background-color: #fefcbf !important; /* Amarillo suave */ color: var(--kahoot-purple);
font-weight: bold; width: 100px;
} }
/* Cambiar el color del texto del puesto #1 a dorado/corona */
.tabla-ranking tr.top-team td:first-child, /* ==========================================================================
.tabla-ranking tr.top-player td:first-child { PUNTOS
color: #b7791f; ========================================================================== */
font-size: 1.2rem;
}
.tabla-ranking td strong { .tabla-ranking td strong {
color: #2f855a; /* Verde para destacar los aciertos conseguidos */ color: var(--kahoot-green);
font-size: 1.1rem; font-size: 1.15rem;
font-weight: 700;
} }
/* ==========================================================================
EFECTOS VISUALES SUAVES
========================================================================== */
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
/* ========================================================================== /* ==========================================================================
ESTILOS DEL BOTÓN DE RETORNO A INICIO EQUIPO / JUGADOR GANADOR
========================================================================== */ ========================================================================== */
.tabla-ranking tr.top-team,
.tabla-ranking tr.top-player {
background-color: #fff7df !important;
font-weight: 700;
}
/* Línea lateral amarilla */
.tabla-ranking tr.top-team td:first-child,
.tabla-ranking tr.top-player td:first-child {
color: var(--kahoot-yellow-dark);
font-size: 1.15rem;
}
/* Puntos del ganador */
.tabla-ranking tr.top-team td strong,
.tabla-ranking tr.top-player td strong {
color: var(--kahoot-green);
}
/* ==========================================================================
BOTÓN VOLVER AL INICIO
========================================================================== */
.contenedor-boton { .contenedor-boton {
display: flex;
justify-content: center;
align-items: center;
margin-top: 40px; margin-top: 40px;
padding-top: 20px; padding-top: 10px;
text-align: center;
} }
/* Botón */
.btn-inicio { .btn-inicio {
display: inline-block; display: inline-flex;
background-color: #3182ce; /* Azul corporativo */ align-items: center;
color: #ffffff; justify-content: center;
padding: 14px 28px; gap: 10px;
min-width: 240px;
padding: 15px 28px;
background-color: var(--kahoot-blue);
color: white;
border: none;
border-bottom: 5px solid var(--kahoot-blue-dark);
border-radius: 12px;
font-family: 'Fredoka', sans-serif;
font-size: 1.1rem; font-size: 1.1rem;
font-weight: 600; font-weight: 700;
text-decoration: none; text-decoration: none;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(49, 130, 206, 0.2); box-shadow: 0 5px 10px rgba(19, 104, 206, 0.25);
transition: background-color 0.2s, transform 0.2s, box-shadow 0.2s;
transition: all 0.15s ease;
} }
/* Hover */
.btn-inicio:hover { .btn-inicio:hover {
background-color: #2b6cb0; /* Azul ligeramente más oscuro al pasar el cursor */ background-color: #0f56ab;
box-shadow: 0 6px 12px rgba(43, 108, 176, 0.3); color: white;
transform: translateY(-2px); /* Pequeño salto hacia arriba */
transform: translateY(-3px);
box-shadow: 0 8px 15px rgba(19, 104, 206, 0.30);
} }
/* Click */
.btn-inicio:active { .btn-inicio:active {
transform: translateY(0); /* Vuelve a su posición normal al pulsar */ transform: translateY(3px);
box-shadow: 0 2px 4px rgba(43, 108, 176, 0.2);
border-bottom-width: 2px;
box-shadow: 0 3px 6px rgba(19, 104, 206, 0.20);
}
/* ==========================================================================
RESPONSIVE
========================================================================== */
@media (max-width: 768px) {
body {
padding: 15px 10px;
}
#pantalla-resultados {
padding: 25px 15px;
}
#pantalla-resultados h1 {
font-size: 2rem;
margin-bottom: 25px;
}
#pantalla-resultados h2 {
font-size: 1.3rem;
}
.tabla-ranking {
font-size: 0.9rem;
}
.tabla-ranking thead th,
.tabla-ranking tbody td {
padding: 12px 10px;
}
.tabla-ranking thead th {
font-size: 0.75rem;
}
.tabla-ranking tbody td {
font-size: 0.9rem;
}
.tabla-ranking td strong {
font-size: 1rem;
}
.btn-inicio {
width: 100%;
min-width: 0;
}
}
/* ==========================================================================
MÓVILES PEQUEÑOS
========================================================================== */
@media (max-width: 500px) {
body {
padding: 10px 5px;
}
#pantalla-espera {
padding: 50px 20px;
}
#pantalla-espera h2 {
font-size: 1.5rem;
}
#pantalla-espera p {
font-size: 0.95rem;
}
#pantalla-resultados {
padding: 20px 10px;
}
#pantalla-resultados h1 {
font-size: 1.7rem;
}
#pantalla-resultados h2 {
font-size: 1.15rem;
}
.tabla-ranking {
display: block;
overflow-x: auto;
white-space: nowrap;
}
.tabla-ranking thead th,
.tabla-ranking tbody td {
padding: 10px 8px;
}
.contenedor-boton {
margin-top: 25px;
}
} }
+10 -2
View File
@@ -4,13 +4,20 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Triviagmático</title>
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg"> <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> </head>
<body> <body>
<?php include 'cabecera.php'; ?> <header id="cabecera-container"></header>
<div class="container my-5"> <div class="container my-5">
<div class="row justify-content-center align-items-center g-4"> <div class="row justify-content-center align-items-center g-4">
@@ -46,6 +53,7 @@
<!-- JS de Bootstrap --> <!-- JS de Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <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/index.js"></script>
<script src="js/cabecera.js"></script>
</body> </body>
</html> </html>
+65 -63
View File
@@ -1,14 +1,19 @@
let idUsuarioSesion = null; let idUsuarioSesion = null;
$(document).ready(function () { $(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(); comprobarSesion();
}
});
}); });
// Función auxiliar para escapar texto HTML // Función auxiliar para escapar texto HTML
function escapeHTML(str) { function escapeHTML(str) {
return $("<div>") return $("<div>").text(str ?? "").html();
.text(str ?? "")
.html();
} }
// Comprobar estado de sesión al cargar la página // Comprobar estado de sesión al cargar la página
@@ -16,24 +21,21 @@ function comprobarSesion() {
$.ajax({ $.ajax({
method: "POST", method: "POST",
url: "controladores/controladorUsuario.php", url: "controladores/controladorUsuario.php",
dataType: "json",
data: { orden: "comprobarSesion" }, data: { orden: "comprobarSesion" },
}).done(function (respuesta) { })
try { .done(function (respuesta) {
if (typeof respuesta === "string") {
respuesta = JSON.parse(respuesta);
}
const contenedor = $("#contenedorUsuarioCabecera"); const contenedor = $("#contenedorUsuarioCabecera");
if (!contenedor.length) return; // Si aún no existe el contenedor en HTML, cancelamos
contenedor.empty(); contenedor.empty();
if (respuesta.activa && respuesta.usuario) { if (respuesta && 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) // Guardar idUsuario globalmente
idUsuarioSesion = respuesta.usuario.idUsuario; 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 = ` const htmlUsuario = `
<div class="dropdown"> <div class="dropdown">
<button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2" <button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2"
@@ -61,12 +63,10 @@ function comprobarSesion() {
// Si estamos en la página principal, mostramos el botón JUGAR // Si estamos en la página principal, mostramos el botón JUGAR
if ($("#colBotonJugar").length) { if ($("#colBotonJugar").length) {
$("#colBotonJugar").removeClass("d-none"); $("#colBotonJugar").removeClass("d-none");
$("#colRanking") $("#colRanking").removeClass("col-lg-8").addClass("col-lg-7 col-xl-8");
.removeClass("col-lg-8")
.addClass("col-lg-7 col-xl-8");
} }
} else { } else {
// No hay sesión: Mostrar botones de Login y Registro // No hay sesión: Botones de Login y Registro
const htmlInvitado = ` const htmlInvitado = `
<button type="button" class="btn btn-kahoot-login rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalLogin"> <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 <i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar Sesión
@@ -77,22 +77,19 @@ function comprobarSesion() {
`; `;
contenedor.html(htmlInvitado); contenedor.html(htmlInvitado);
// Si estamos en la página principal, ocultamos el botón JUGAR
if ($("#colBotonJugar").length) { if ($("#colBotonJugar").length) {
$("#colBotonJugar").addClass("d-none"); $("#colBotonJugar").addClass("d-none");
$("#colRanking") $("#colRanking").removeClass("col-lg-7 col-xl-8").addClass("col-lg-8");
.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 // Registro de usuario
$("#botonAceptarRegistro").click(function (event) { $(document).on("click", "#botonAceptarRegistro", function (event) {
event.preventDefault(); event.preventDefault();
let nombreUsuario = $("#regNombre").val().trim(); let nombreUsuario = $("#regNombre").val().trim();
@@ -100,61 +97,64 @@ $("#botonAceptarRegistro").click(function (event) {
let contrasena = $("#regPassword").val(); let contrasena = $("#regPassword").val();
let contrasenaConfirmacion = $("#regPasswordConfirm").val(); let contrasenaConfirmacion = $("#regPasswordConfirm").val();
$("#regNombre").removeClass("is-invalid"); // Resetear estados visuales
$("#regEmail").removeClass("is-invalid"); $("#regNombre, #regEmail, #regPassword, #regPasswordConfirm").removeClass("is-invalid");
$("#regPassword").removeClass("is-invalid"); $("#errorRegistro").removeClass("text-danger text-success").text("").show();
$("#regPasswordConfirm").removeClass("is-invalid");
$("#errorRegistro").text("");
if (contrasena !== contrasenaConfirmacion) { if (contrasena !== contrasenaConfirmacion) {
$("#regPassword").addClass("is-invalid"); $("#regPassword, #regPasswordConfirm").addClass("is-invalid");
$("#regPasswordConfirm").addClass("is-invalid"); $("#errorRegistro").addClass("text-danger").text("Las contraseñas no coinciden.");
$("#errorRegistro").text("Las contraseñas no coinciden.");
return; return;
} }
$.ajax({ $.ajax({
method: "POST", method: "POST",
url: "controladores/controladorUsuario.php", url: "controladores/controladorUsuario.php",
dataType: "json",
data: { data: {
nombreUsuario: nombreUsuario, nombreUsuario: nombreUsuario,
email: email, email: email,
contrasena: contrasena, contrasena: contrasena,
orden: "registrarUsuario", orden: "registrarUsuario",
}, },
}).done(function (respuesta) { })
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta); .done(function (respuesta) {
if (respuesta.error) { if (respuesta.error) {
$("#errorRegistro").text(respuesta.error); $("#errorRegistro").addClass("text-danger").text(respuesta.error);
$("#regNombre").addClass("is-invalid"); $("#regNombre, #regEmail").addClass("is-invalid");
$("#regEmail").addClass("is-invalid");
} else { } else {
// Mostrar mensaje de confirmación
$("#errorRegistro") $("#errorRegistro")
.removeClass("text-danger") .removeClass("text-danger")
.addClass("text-success") .addClass("text-success fw-bold")
.text(respuesta.exito); .text(respuesta.exito || "¡Registro completado con éxito!");
if ($("#formRegistro").length) {
$("#formRegistro")[0].reset(); $("#formRegistro")[0].reset();
}
// Recargar para iniciar sesión tras 1.5 segundos
setTimeout(function () { setTimeout(function () {
location.reload(); 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 // Login de usuario
$("#botonAceptarLogin").click(function (event) { $(document).on("click", "#botonAceptarLogin", function (event) {
event.preventDefault(); event.preventDefault();
let email = $("#loginEmail").val().trim(); let email = $("#loginEmail").val().trim();
let contrasena = $("#loginPassword").val(); let contrasena = $("#loginPassword").val();
let recuerdame = $("#recordar").is(":checked"); let recuerdame = $("#recordar").is(":checked");
$("#loginEmail").removeClass("is-invalid"); $("#loginEmail, #loginPassword").removeClass("is-invalid");
$("#loginPassword").removeClass("is-invalid"); $("#errorLogin").removeClass("text-success").addClass("text-danger").text("").show();
$("#errorLogin").text("");
if (email === "" || contrasena === "") { if (email === "" || contrasena === "") {
$("#errorLogin").text("Todos los campos son obligatorios."); $("#errorLogin").text("Todos los campos son obligatorios.");
@@ -166,22 +166,26 @@ $("#botonAceptarLogin").click(function (event) {
$.ajax({ $.ajax({
method: "POST", method: "POST",
url: "controladores/controladorUsuario.php", url: "controladores/controladorUsuario.php",
dataType: "json",
data: { data: {
email: email, email: email,
contrasena: contrasena, contrasena: contrasena,
recuerdame: recuerdame, recuerdame: recuerdame,
orden: "comprobarUsuario", orden: "comprobarUsuario",
}, },
}).done(function (respuesta) { })
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta); .done(function (respuesta) {
if (respuesta.error) { if (respuesta.error) {
$("#loginEmail").addClass("is-invalid"); $("#loginEmail, #loginPassword").addClass("is-invalid");
$("#loginPassword").addClass("is-invalid");
$("#errorLogin").text(respuesta.error); $("#errorLogin").text(respuesta.error);
} else { } else {
// Login correcto: Recargar la vista
location.reload(); 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 +196,13 @@ $(document).on("click", "#botonCerrarSesion", function (event) {
$.ajax({ $.ajax({
method: "POST", method: "POST",
url: "controladores/controladorUsuario.php", url: "controladores/controladorUsuario.php",
dataType: "json",
data: { orden: "cerrarSesion" }, data: { orden: "cerrarSesion" },
}).done(function (respuesta) { })
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta); .done(function (respuesta) {
window.location.href = "index.php";
if (respuesta.error) { })
console.log(respuesta.error); .fail(function () {
} else {
window.location.href = "index.php"; 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 // 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
function responder($botonPulsado) { function responder($botonPulsado) {
clearInterval(intervaloTiempo); clearInterval(intervaloTiempo);
console.log("Tiempo de respuesta: " + tiempoRespuesta / 10 + " segundos");
console.log(
"Tiempo de respuesta: " +
tiempoRespuesta / 10 +
" segundos"
);
if (bloqueado) { if (bloqueado) {
return; return;
@@ -127,7 +132,29 @@ function responder($botonPulsado) {
bloqueado = true; bloqueado = true;
const pregunta = preguntas[indice]; 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"); $("#respuestas").addClass("bloqueado");
@@ -135,46 +162,96 @@ function responder($botonPulsado) {
url: URL_CONTROLADOR, url: URL_CONTROLADOR,
type: "POST", type: "POST",
dataType: "json", dataType: "json",
data: { data: {
orden: "responder", orden: "responder",
idPartida: idPartida, idPartida: idPartida,
idPartidaxPregunta: pregunta.idPartidaxPregunta, idPartidaxPregunta: pregunta.idPartidaxPregunta,
idRespuesta: idRespuesta, idRespuesta: idRespuesta,
tiempoRespuesta: tiempoRespuesta, tiempoRespuesta: tiempoRespuesta
}, },
success: function (datos) { success: function (datos) {
console.log("RESPUESTA DEL SERVIDOR:", datos);
if (datos.error) { 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"); $("#respuestas").removeClass("bloqueado");
bloqueado = false; bloqueado = false;
return; return;
} }
pregunta.respondida = true; pregunta.respondida = true;
mostrarFeedback($botonPulsado, datos);
mostrarFeedback(
$botonPulsado,
datos
);
setTimeout(function () { setTimeout(function () {
if (datos.terminada || indice >= preguntas.length - 1) {
if (
datos.terminada ||
indice >= preguntas.length - 1
) {
terminar(); terminar();
} else { } else {
indice++; indice++;
$("#respuestas").removeClass("bloqueado");
$("#respuestas")
.removeClass("bloqueado");
mostrarPregunta(); mostrarPregunta();
} }
}, PAUSA_FEEDBACK); }, 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") $("#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") .removeClass("ok")
.addClass("ko"); .addClass("ko");
$("#respuestas").removeClass("bloqueado"); $("#respuestas").removeClass("bloqueado");
bloqueado = false; bloqueado = false;
}, }
}); });
} }
// Marca la respuesta correcta en verde y atenúa el resto // Marca la respuesta correcta en verde y atenúa el resto
function mostrarFeedback($botonPulsado, datos) { function mostrarFeedback($botonPulsado, datos) {
$("#respuestas .btn-answer").each(function () { $("#respuestas .btn-answer").each(function () {
+107 -38
View File
@@ -263,14 +263,15 @@ function mostrarSala(partida, equipos, jugadores) {
if (esHost) { if (esHost) {
botonIniciarHTML = ` botonIniciarHTML = `
<a <button
href="juego.php?idPartida=${partida.idPartida}" type="button"
class="btn btn-success btn-lg px-4"> class="btn btn-success btn-lg px-4 btn-iniciar-partida"
data-id-partida="${partida.idPartida}">
<i class="bi bi-controller"></i> <i class="bi bi-controller"></i>
¡Iniciar Partida! ¡Iniciar Partida!
</a> </button>
`; `;
} }
@@ -313,8 +314,98 @@ function mostrarSala(partida, equipos, jugadores) {
`; `;
contenedor.html(salaHTML); 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 () { $(document).on("click", ".btn-unirse-equipo", function () {
const boton = $(this); const boton = $(this);
@@ -364,8 +455,7 @@ $(document).on("click", ".btn-abandonar-sala", function () {
botonAbandonarReferencia = $(this); botonAbandonarReferencia = $(this);
const esHost = 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"); const titulo = $("#modalAbandonarSalaLabel");
@@ -384,9 +474,7 @@ $(document).on("click", ".btn-abandonar-sala", function () {
} else { } else {
titulo.text("¿Abandonar la sala?"); titulo.text("¿Abandonar la sala?");
mensaje.text( mensaje.text("Si sales de la sala, perderás tu lugar en el equipo.");
"Si sales de la sala, perderás tu lugar en el equipo.",
);
botonConfirmar.text("Sí, salir"); botonConfirmar.text("Sí, salir");
} }
@@ -399,17 +487,13 @@ $(document).on("click", ".btn-abandonar-sala", function () {
}); });
$(document).on("click", "#btnConfirmarAbandonar", function () { $(document).on("click", "#btnConfirmarAbandonar", function () {
const modalEl = const modalEl = document.getElementById("modalAbandonarSala");
document.getElementById("modalAbandonarSala");
const modalInstance = const modalInstance = bootstrap.Modal.getInstance(modalEl);
bootstrap.Modal.getInstance(modalEl);
const btnConfirmar = $(this); const btnConfirmar = $(this);
btnConfirmar btnConfirmar.prop("disabled", true).text("Saliendo...");
.prop("disabled", true)
.text("Saliendo...");
$.ajax({ $.ajax({
url: "controladores/controladorEquipoxUsuario.php", url: "controladores/controladorEquipoxUsuario.php",
@@ -421,9 +505,7 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
}, },
success: function (respuesta) { success: function (respuesta) {
btnConfirmar btnConfirmar.prop("disabled", false).text("Sí, salir");
.prop("disabled", false)
.text("Sí, salir");
if (modalInstance) { if (modalInstance) {
modalInstance.hide(); modalInstance.hide();
@@ -449,16 +531,11 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
}, },
error: function (xhr, status, error) { error: function (xhr, status, error) {
console.error( console.error("Error al salir de la sala:", error);
"Error al salir de la sala:",
error
);
alert("No se pudo salir de la sala."); alert("No se pudo salir de la sala.");
btnConfirmar btnConfirmar.prop("disabled", false).text("Sí, salir");
.prop("disabled", false)
.text("Sí, salir");
if (modalInstance) { if (modalInstance) {
modalInstance.hide(); modalInstance.hide();
@@ -473,16 +550,11 @@ function escapeHTML(texto) {
.html(); .html();
} }
function mostrarEquipos( function mostrarEquipos(partida, equipos, jugadores) {
partida,
equipos,
jugadores
) {
let equiposHTML = ""; let equiposHTML = "";
equipos.forEach(function (equipo) { equipos.forEach(function (equipo) {
const jugadoresEquipo = const jugadoresEquipo = jugadores.filter(function (jugador) {
jugadores.filter(function (jugador) {
return jugador.idEquipo == equipo.idEquipo; return jugador.idEquipo == equipo.idEquipo;
}); });
@@ -490,8 +562,7 @@ function mostrarEquipos(
if (jugadoresEquipo.length > 0) { if (jugadoresEquipo.length > 0) {
jugadoresEquipo.forEach(function (jugador) { jugadoresEquipo.forEach(function (jugador) {
const esHost = const esHost = jugador.idUsuario == partida.idUsuario;
jugador.idUsuario == partida.idUsuario;
jugadoresHTML += ` jugadoresHTML += `
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${ <div class="jugador border border-2 d-flex align-items-center justify-content-between ${
@@ -507,9 +578,7 @@ function mostrarEquipos(
} }
</span> </span>
${escapeHTML( ${escapeHTML(jugador.nombreUsuario)}
jugador.nombreUsuario
)}
</div> </div>
${ ${
+2 -2
View File
@@ -41,7 +41,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
<body> <body>
<?php include_once 'cabecera.php'; ?> <header id="cabecera-container"></header>
<div class="perfil-container"> <div class="perfil-container">
@@ -310,7 +310,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
<!-- Tu JavaScript --> <!-- Tu JavaScript -->
<script src="js/perfil.js"></script> <script src="js/perfil.js"></script>
<script src="js/cabecera.js"></script>
</body> </body>
</html> </html>
+8 -3
View File
@@ -86,19 +86,24 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resultados - Trivial</title> <title>Resultados - Trivial</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/resultados.css"> <link rel="stylesheet" href="css/resultados.css">
<script src="js/jquery-4.0.0.min.js"></script> <script src="js/jquery-4.0.0.min.js"></script>
</head> </head>
<body data-id-partida="<?php echo $idPartida; ?>"> <body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor"> <div id="pantalla-espera" class="contenedor">
<h2>⌛ Esperando a que todos los jugadores terminen...</h2> <h2> <i class="bi bi-hourglass"></i> Esperando a que todos los jugadores terminen...</h2>
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p> <p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
<div class="loader"></div> <div class="loader"></div>
</div> </div>
<div id="pantalla-resultados" class="contenedor" style="display:none;"> <div id="pantalla-resultados" class="contenedor" style="display:none;">
<h1>🏆 Resultados de la Partida 🏆</h1> <h1> <i class="bi bi-trophy-fill"></i> Resultados de la Partida <i class="bi bi-trophy-fill"></i> </h1>
<h2>Clasificación por Equipos</h2> <h2>Clasificación por Equipos</h2>
<table class="tabla-ranking"> <table class="tabla-ranking">
@@ -146,7 +151,7 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
<div class="contenedor-boton"> <div class="contenedor-boton">
<a href="/triviagmatico/" id="btnVolverInicio" data-id="<?php echo $idPartida; ?>" class="btn-inicio">Volver al Inicio 🏠</a> <a href="<?= $_ENV['urlBase'] ?>/" id="btnVolverInicio" data-id="<?php echo $idPartida; ?>" class="btn btn-play-kahoot"> <i class="bi bi-arrow-left"></i> Volver al Inicio <i class="bi bi-house-fill"></i> </a>
</div> </div>
</div> </div>