Compare commits
12 Commits
26a46c29e8
...
juegophp
| Author | SHA1 | Date | |
|---|---|---|---|
| 449cb1d976 | |||
| 3cc0dfb122 | |||
| 4efb831b7a | |||
| 22f38f924f | |||
| 01aa2643f6 | |||
| 07c1f79474 | |||
| 54b6b0d67b | |||
| 57e3dfc444 | |||
| 8c7958ad96 | |||
| bf2361ad43 | |||
| 03715d621e | |||
| 6da20872c6 |
+56
-154
@@ -4,200 +4,102 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<title>Trivial - Lobby</title>
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet">
|
||||
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<link rel="stylesheet" href="css/buscadorSala.css">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php
|
||||
include_once("cabecera.php");
|
||||
?>
|
||||
<?php include_once("cabecera.php"); ?>
|
||||
|
||||
<main class="container py-5">
|
||||
<main class="container py-4">
|
||||
|
||||
<!-- Botón Volver -->
|
||||
<div class="mb-4">
|
||||
<a href="index.php" class="btn btn-outline-secondary d-inline-flex align-items-center gap-2">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-left" viewBox="0 0 16 16">
|
||||
<path fill-rule="evenodd" d="M15 8a.5.5 0 0 0-.5-.5H2.707l3.147-3.146a.5.5 0 1 0-.708-.708l-4 4a.5.5 0 0 0 0 .708l4 4a.5.5 0 0 0 .708-.708L2.707 8.5H14.5A.5.5 0 0 0 15 8"/>
|
||||
</svg>
|
||||
Volver al Inicio
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Botón Crear Sala -->
|
||||
<div id="contenedorCrearSala" class="text-center mb-5">
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-play-kahoot btn-crear-sala"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalCrearSala">
|
||||
|
||||
<span>+</span>
|
||||
Crear sala
|
||||
|
||||
<button type="button" class="btn btn-play-kahoot btn-crear-sala" data-bs-toggle="modal" data-bs-target="#modalCrearSala">
|
||||
<span>+</span> Crear sala
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="contenedorSalas"
|
||||
class="row justify-content-center g-4">
|
||||
|
||||
<div
|
||||
id="cargandoSalas"
|
||||
class="col-12 text-center">
|
||||
|
||||
<div
|
||||
class="spinner-border text-primary"
|
||||
role="status">
|
||||
|
||||
<span class="visually-hidden">
|
||||
Cargando...
|
||||
</span>
|
||||
|
||||
<!-- Contenedor Principal de Salas -->
|
||||
<div id="contenedorSalas" class="row justify-content-center g-4">
|
||||
<div id="cargandoSalas" class="col-12 text-center">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Cargando...</span>
|
||||
</div>
|
||||
|
||||
<p class="mt-3 text-muted">
|
||||
Cargando salas...
|
||||
</p>
|
||||
|
||||
<p class="mt-3 text-muted">Cargando salas...</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
<!-- Modal Crear Sala -->
|
||||
<div
|
||||
class="modal fade"
|
||||
id="modalCrearSala"
|
||||
tabindex="-1"
|
||||
aria-labelledby="modalCrearSalaLabel"
|
||||
aria-hidden="true">
|
||||
|
||||
<div class="modal fade" id="modalCrearSala" tabindex="-1" aria-labelledby="modalCrearSalaLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
|
||||
<div class="modal-content modal-kahoot">
|
||||
|
||||
<div class="modal-header modal-kahoot-header">
|
||||
|
||||
<h5
|
||||
class="modal-title"
|
||||
id="modalCrearSalaLabel">
|
||||
|
||||
Crear sala
|
||||
|
||||
</h5>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn-close btn-close-white"
|
||||
data-bs-dismiss="modal"
|
||||
aria-label="Cerrar">
|
||||
</button>
|
||||
|
||||
<h5 class="modal-title" id="modalCrearSalaLabel">Crear sala</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body p-4">
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreSala"
|
||||
class="form-label">
|
||||
|
||||
Nombre de la sala
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreSala"
|
||||
class="form-control input-kahoot"
|
||||
name="nombreSala"
|
||||
placeholder="Ej. Noche de Trivial"
|
||||
maxlength="100">
|
||||
|
||||
<label for="nombreSala" class="form-label">Nombre de la sala</label>
|
||||
<input type="text" id="nombreSala" class="form-control input-kahoot" name="nombreSala" placeholder="Ej. Noche de Trivial" maxlength="100">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreEquipo1"
|
||||
class="form-label">
|
||||
|
||||
Nombre del equipo 1
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreEquipo1"
|
||||
name="nombreEquipo1"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Ej. Los cerebritos"
|
||||
maxlength="50">
|
||||
|
||||
<label for="nombreEquipo1" class="form-label">Nombre del equipo 1</label>
|
||||
<input type="text" id="nombreEquipo1" name="nombreEquipo1" class="form-control input-kahoot" placeholder="Ej. Los cerebritos" maxlength="50">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreEquipo2"
|
||||
class="form-label">
|
||||
|
||||
Nombre del equipo 2
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreEquipo2"
|
||||
name="nombreEquipo2"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Ej. Los campeones"
|
||||
maxlength="50">
|
||||
|
||||
<label for="nombreEquipo2" class="form-label">Nombre del equipo 2</label>
|
||||
<input type="text" id="nombreEquipo2" name="nombreEquipo2" class="form-control input-kahoot" placeholder="Ej. Los campeones" maxlength="50">
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
data-bs-dismiss="modal">
|
||||
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-kahoot-login" id="btnCrearSala">Crear sala</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!--MODAL ABANDONAR SALA -->
|
||||
<!-- Modal Confirmar Abandonar Sala -->
|
||||
<div class="modal fade" id="modalAbandonarSala" tabindex="-1" aria-labelledby="modalAbandonarSalaLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content modal-kahoot text-center p-3">
|
||||
<div class="modal-body">
|
||||
<div class="mb-3 fs-1">⚠️</div>
|
||||
<h4 class="modal-title mb-2 fw-bold text-white" id="modalAbandonarSalaLabel">¿Abandonar la sala?</h4>
|
||||
<p class="text-white-50">Si sales de la sala, perderás tu lugar en el equipo.</p>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-center border-0 gap-2">
|
||||
<button type="button" class="btn btn-secondary px-4 py-2" data-bs-dismiss="modal">
|
||||
Cancelar
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-kahoot-login"
|
||||
id="btnCrearSala">
|
||||
|
||||
Crear sala
|
||||
|
||||
<button type="button" id="btnConfirmarAbandonar" class="btn btn-danger px-4 py-2">
|
||||
Sí, salir
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script
|
||||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js">
|
||||
</script>
|
||||
|
||||
<script src="js/jquery/jquery.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/buscadorSala.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+10
-55
@@ -1,13 +1,3 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Comprobación de sesión
|
||||
$isLoggedIn = isset($_SESSION['idUsuario']) && !empty($_SESSION['idUsuario']);
|
||||
$username = $isLoggedIn ? $_SESSION['nombreUsuario'] : '';
|
||||
?>
|
||||
|
||||
<!-- Bootstrap 5 CSS -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<!-- FontAwesome para iconos -->
|
||||
@@ -17,7 +7,6 @@ $username = $isLoggedIn ? $_SESSION['nombreUsuario'] : '';
|
||||
<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">
|
||||
@@ -32,44 +21,8 @@ $username = $isLoggedIn ? $_SESSION['nombreUsuario'] : '';
|
||||
<div class="collapse navbar-collapse" id="navbarContent">
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
|
||||
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<!-- Menú desplegable cuando la sesión está iniciada -->
|
||||
<div class="dropdown">
|
||||
<button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2"
|
||||
type="button"
|
||||
id="userDropdown"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false">
|
||||
<i class="fa-solid fa-circle-user fa-lg text-warning"></i>
|
||||
<span><?= htmlspecialchars($username) ?></span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end user-dropdown-menu" aria-labelledby="userDropdown">
|
||||
<li>
|
||||
<a class="dropdown-item d-flex align-items-center gap-2" href="perfil.php">
|
||||
<i class="fa-solid fa-user text-primary"></i> Perfil
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<hr class="dropdown-divider">
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item logout-item d-flex align-items-center gap-2" href="#" id="botonCerrarSesion">
|
||||
<i class="fa-solid fa-right-from-bracket"></i> Cerrar Sesión
|
||||
</a>
|
||||
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<!-- Botones que abren los modales cuando NO hay sesión iniciada -->
|
||||
<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
|
||||
</button>
|
||||
<button type="button" class="btn btn-kahoot-register rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
<i class="fa-solid fa-user-plus me-1"></i> Registrarse
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
<!-- Contenedor dinámico cargado por js/cabecera.js -->
|
||||
<div class="d-flex align-items-center gap-3" id="contenedorUsuarioCabecera">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -95,11 +48,6 @@ $username = $isLoggedIn ? $_SESSION['nombreUsuario'] : '';
|
||||
<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>
|
||||
@@ -139,7 +87,14 @@ $username = $isLoggedIn ? $_SESSION['nombreUsuario'] : '';
|
||||
<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">
|
||||
|
||||
<!-- Checkbox Recuérdame -->
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input border-dark" type="checkbox" value="" id="recuerdameCheck">
|
||||
<label class="form-check-label fw-semibold" for="recuerdameCheck">
|
||||
Recuérdame en 10 días
|
||||
</label>
|
||||
</div>
|
||||
</form>
|
||||
<div id="errorRegistro" class="text-danger fw-bold mt-2"></div>
|
||||
</div>
|
||||
|
||||
@@ -118,4 +118,30 @@ class EquipoxUsuario
|
||||
}
|
||||
}
|
||||
|
||||
public static function salirDeSala($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
'exito' => true,
|
||||
'mensaje' => 'Usuario eliminado de la sala correctamente.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al salir de la sala.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
require_once __DIR__ . '/ClaseRespuestaAlmacenada.php';
|
||||
|
||||
/**
|
||||
* Lógica de la dinámica de juego (la usa juego.php a través de ControladorJuego.php):
|
||||
* - deja preparadas las 10 preguntas de la partida
|
||||
* - se las devuelve al jugador con sus respuestas SIN decir cuál es la correcta
|
||||
* - guarda la respuesta de cada jugador y le dice si ha acertado
|
||||
*
|
||||
* Todos los métodos devuelven un array con la clave 'error' si algo falla,
|
||||
* igual que el resto de clases del proyecto.
|
||||
*/
|
||||
class Juego
|
||||
{
|
||||
const NUM_PREGUNTAS = 10;
|
||||
|
||||
/**
|
||||
* Comprueba que el usuario pertenece a alguno de los equipos de la partida.
|
||||
* Devuelve true/false (o el array de error si falla la BD).
|
||||
*/
|
||||
public static function usuarioEnPartida($idPartida, $idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) AS total
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu
|
||||
ON exu.idEquipo = exp.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
AND exu.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
return (int)$consulta->fetchColumn() > 0;
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al comprobar si perteneces a la partida.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Si la partida todavía no tiene preguntas, le asigna 10 al azar.
|
||||
* Se hace dentro de una transacción con la fila de la partida bloqueada
|
||||
* para que, si varios jugadores entran a la vez, las preguntas se
|
||||
* asignen una sola vez.
|
||||
* Devuelve null si todo va bien, o un array de error.
|
||||
*/
|
||||
private static function asegurarPreguntas($conexion, $idPartida)
|
||||
{
|
||||
try {
|
||||
$conexion->beginTransaction();
|
||||
|
||||
$bloqueo = $conexion->prepare("
|
||||
SELECT idPartida FROM partida
|
||||
WHERE idPartida = :idPartida
|
||||
FOR UPDATE
|
||||
");
|
||||
$bloqueo->execute([':idPartida' => $idPartida]);
|
||||
|
||||
if (!$bloqueo->fetch()) {
|
||||
$conexion->rollBack();
|
||||
return ['error' => 'La partida no existe.'];
|
||||
}
|
||||
|
||||
$cuenta = $conexion->prepare("
|
||||
SELECT COUNT(*) FROM partidaxpregunta
|
||||
WHERE idPartida = :idPartida
|
||||
");
|
||||
$cuenta->execute([':idPartida' => $idPartida]);
|
||||
|
||||
if ((int)$cuenta->fetchColumn() === 0) {
|
||||
|
||||
// Solo preguntas que tengan alguna respuesta marcada como correcta
|
||||
$elegidas = $conexion->query("
|
||||
SELECT p.idPregunta
|
||||
FROM pregunta p
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM respuesta r
|
||||
WHERE r.idPregunta = p.idPregunta
|
||||
AND r.correcta = 1
|
||||
)
|
||||
ORDER BY RAND()
|
||||
LIMIT " . self::NUM_PREGUNTAS
|
||||
)->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
$insertar = $conexion->prepare("
|
||||
INSERT INTO partidaxpregunta (idPartida, idPregunta)
|
||||
VALUES (:idPartida, :idPregunta)
|
||||
");
|
||||
foreach ($elegidas as $idPregunta) {
|
||||
$insertar->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idPregunta' => $idPregunta
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$conexion->commit();
|
||||
return null;
|
||||
} catch (PDOException $error) {
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
return [
|
||||
'error' => 'Ocurrió un error al preparar las preguntas de la partida.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve las preguntas de la partida (máximo 10) con sus respuestas
|
||||
* mezcladas. NO incluye el campo 'correcta' para que no se pueda hacer
|
||||
* trampa mirando la respuesta del servidor.
|
||||
* Cada pregunta indica si este usuario ya la ha respondido, para poder
|
||||
* retomar la partida si recarga la página.
|
||||
*/
|
||||
public static function cargarPreguntas($idPartida, $idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
$error = self::asegurarPreguntas($conexion, $idPartida);
|
||||
if ($error !== null) {
|
||||
return $error;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Las preguntas, siempre en el mismo orden para todos los jugadores
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT
|
||||
pxp.idPartidaxPregunta,
|
||||
p.idPregunta,
|
||||
p.nombrePregunta
|
||||
FROM partidaxpregunta pxp
|
||||
INNER JOIN pregunta p
|
||||
ON p.idPregunta = pxp.idPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
ORDER BY pxp.idPartidaxPregunta
|
||||
LIMIT " . self::NUM_PREGUNTAS
|
||||
);
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
$preguntas = $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// 2. Las respuestas de todas esas preguntas, agrupadas por pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT DISTINCT
|
||||
r.idRespuesta,
|
||||
r.idPregunta,
|
||||
r.nombreRespuesta
|
||||
FROM respuesta r
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPregunta = r.idPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
|
||||
$respuestasPorPregunta = [];
|
||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
||||
$respuestasPorPregunta[(int)$fila['idPregunta']][] = [
|
||||
'idRespuesta' => (int)$fila['idRespuesta'],
|
||||
'nombreRespuesta' => $fila['nombreRespuesta']
|
||||
];
|
||||
}
|
||||
|
||||
// 3. Qué preguntas ha respondido ya este usuario
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT ra.idPartidaxPregunta
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
AND ra.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
$respondidas = array_flip($consulta->fetchAll(PDO::FETCH_COLUMN));
|
||||
|
||||
// 4. Montamos la respuesta final
|
||||
$resultado = [];
|
||||
foreach ($preguntas as $pregunta) {
|
||||
$idPregunta = (int)$pregunta['idPregunta'];
|
||||
$idPxp = (int)$pregunta['idPartidaxPregunta'];
|
||||
|
||||
$respuestas = $respuestasPorPregunta[$idPregunta] ?? [];
|
||||
shuffle($respuestas);
|
||||
|
||||
$resultado[] = [
|
||||
'idPartidaxPregunta' => $idPxp,
|
||||
'idPregunta' => $idPregunta,
|
||||
'nombrePregunta' => $pregunta['nombrePregunta'],
|
||||
'respondida' => isset($respondidas[$idPxp]),
|
||||
'respuestas' => $respuestas
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'total' => count($resultado),
|
||||
'respondidas' => count($respondidas),
|
||||
'preguntas' => $resultado
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al cargar las preguntas.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda la respuesta que ha elegido el usuario en una pregunta y
|
||||
* devuelve si ha acertado y cuál era la correcta (para el feedback).
|
||||
* Comprueba en el servidor que:
|
||||
* - la pregunta pertenece a la partida
|
||||
* - la respuesta pertenece a esa pregunta
|
||||
* - el usuario no ha respondido ya esa pregunta
|
||||
*/
|
||||
public static function registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. La pregunta tiene que ser de esta partida
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT idPregunta
|
||||
FROM partidaxpregunta
|
||||
WHERE idPartidaxPregunta = :idPxp
|
||||
AND idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPxp' => $idPartidaxPregunta,
|
||||
':idPartida' => $idPartida
|
||||
]);
|
||||
$idPregunta = $consulta->fetchColumn();
|
||||
|
||||
if ($idPregunta === false) {
|
||||
return ['error' => 'Esa pregunta no pertenece a esta partida.'];
|
||||
}
|
||||
|
||||
// 2. La respuesta tiene que ser una de las de esa pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT idRespuesta, correcta
|
||||
FROM respuesta
|
||||
WHERE idPregunta = :idPregunta
|
||||
");
|
||||
$consulta->execute([':idPregunta' => $idPregunta]);
|
||||
|
||||
$elegida = null;
|
||||
$primeraCorrecta = null;
|
||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
||||
if ((int)$fila['correcta'] === 1 && $primeraCorrecta === null) {
|
||||
$primeraCorrecta = (int)$fila['idRespuesta'];
|
||||
}
|
||||
if ((int)$fila['idRespuesta'] === $idRespuesta) {
|
||||
$elegida = $fila;
|
||||
}
|
||||
}
|
||||
|
||||
if ($elegida === null) {
|
||||
return ['error' => 'Esa respuesta no pertenece a la pregunta.'];
|
||||
}
|
||||
|
||||
// 3. Solo se puede responder una vez a cada pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada
|
||||
WHERE idPartidaxPregunta = :idPxp
|
||||
AND idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPxp' => $idPartidaxPregunta,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
|
||||
if ((int)$consulta->fetchColumn() > 0) {
|
||||
return ['error' => 'Ya has respondido a esta pregunta.'];
|
||||
}
|
||||
|
||||
// 4. Guardamos la respuesta con la clase que ya existía
|
||||
$almacenada = new RespuestaAlmacenada(
|
||||
null,
|
||||
$idPartidaxPregunta,
|
||||
$idUsuario,
|
||||
$idRespuesta
|
||||
);
|
||||
$guardado = $almacenada->guardarRespuesta();
|
||||
|
||||
if (isset($guardado['error'])) {
|
||||
return $guardado;
|
||||
}
|
||||
|
||||
// 5. Progreso del usuario en la partida
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
AND ra.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
$respondidas = (int)$consulta->fetchColumn();
|
||||
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) FROM partidaxpregunta
|
||||
WHERE idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
$total = min((int)$consulta->fetchColumn(), self::NUM_PREGUNTAS);
|
||||
|
||||
$acierto = (int)$elegida['correcta'] === 1;
|
||||
|
||||
return [
|
||||
'exito' => 'Respuesta guardada.',
|
||||
'acierto' => $acierto,
|
||||
'idRespuestaCorrecta' => $acierto ? $idRespuesta : $primeraCorrecta,
|
||||
'respondidas' => $respondidas,
|
||||
'total' => $total,
|
||||
'terminada' => $respondidas >= $total
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la respuesta.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,4 +75,16 @@ switch ($_POST['orden']) {
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case 'salirDeSala':
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Usuario no autenticado']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$idUsuario = $_SESSION['idUsuario'];
|
||||
$respuesta = EquipoxUsuario::salirDeSala($idUsuario);
|
||||
|
||||
echo json_encode($respuesta);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseJuego.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// Hay que estar logueado y decir de qué partida se trata
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode(['error' => 'No se ha indicado la partida.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Solo pueden jugar los usuarios que están en uno de los equipos de la partida
|
||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida, $idUsuario);
|
||||
|
||||
if (is_array($perteneceAPartida)) {
|
||||
echo json_encode($perteneceAPartida);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!$perteneceAPartida) {
|
||||
echo json_encode(['error' => 'No formas parte de esta partida.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
switch ($_POST['orden'] ?? '') {
|
||||
|
||||
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
|
||||
case 'cargarPreguntas':
|
||||
|
||||
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
|
||||
|
||||
break;
|
||||
|
||||
|
||||
// Guarda la respuesta del usuario y dice si ha acertado
|
||||
case 'responder':
|
||||
|
||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta'] ?? 0);
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
|
||||
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0) {
|
||||
echo json_encode(['error' => 'Faltan datos para registrar la respuesta.']);
|
||||
break;
|
||||
}
|
||||
|
||||
echo json_encode(
|
||||
Juego::registrarRespuesta(
|
||||
$idPartida,
|
||||
$idUsuario,
|
||||
$idPartidaxPregunta,
|
||||
$idRespuesta
|
||||
)
|
||||
);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
// Recibe los aciertos del jugador al terminar sus 10 preguntas,
|
||||
// para que resultados.php los pueda usar al montar la hoja de resultados
|
||||
case 'finalizarPartida':
|
||||
|
||||
$aciertos = intval($_POST['aciertos'] ?? 0);
|
||||
|
||||
if (!isset($_SESSION['aciertosPorPartida'])) {
|
||||
$_SESSION['aciertosPorPartida'] = [];
|
||||
}
|
||||
|
||||
$_SESSION['aciertosPorPartida'][$idPartida] = $aciertos;
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Aciertos registrados correctamente.',
|
||||
'idPartida' => $idPartida,
|
||||
'aciertos' => $aciertos
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
|
||||
echo json_encode(['error' => 'La orden indicada no existe.']);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClasePregunta.php';
|
||||
require_once '../clases/ClaseRespuesta.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
@@ -11,16 +12,116 @@ switch ($_POST['orden']) {
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
$nombrePregunta = trim($_POST['nombrePregunta'] ?? '');
|
||||
|
||||
if ($idCategoria <= 0 || $nombrePregunta == '') {
|
||||
echo json_encode(['error' => 'La categoría y el texto de la pregunta son obligatorios']);
|
||||
$respuestaCorrecta = trim($_POST['respuestaCorrecta'] ?? '');
|
||||
$respuestaIncorrecta1 = trim($_POST['respuestaIncorrecta1'] ?? '');
|
||||
$respuestaIncorrecta2 = trim($_POST['respuestaIncorrecta2'] ?? '');
|
||||
$respuestaIncorrecta3 = trim($_POST['respuestaIncorrecta3'] ?? '');
|
||||
|
||||
// Comprobamos los datos
|
||||
if (
|
||||
$idCategoria <= 0 ||
|
||||
$nombrePregunta === '' ||
|
||||
$respuestaCorrecta === '' ||
|
||||
$respuestaIncorrecta1 === '' ||
|
||||
$respuestaIncorrecta2 === '' ||
|
||||
$respuestaIncorrecta3 === ''
|
||||
) {
|
||||
|
||||
echo json_encode([
|
||||
'error' => 'La categoría, la pregunta y todas las respuestas son obligatorias.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$pregunta = new Pregunta($idCategoria, $nombrePregunta);
|
||||
$resultado = $pregunta->guardar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
/*
|
||||
* ==========================================
|
||||
* 1. CREAMOS LA PREGUNTA
|
||||
* ==========================================
|
||||
*/
|
||||
|
||||
$pregunta = new Pregunta(
|
||||
$idCategoria,
|
||||
$nombrePregunta
|
||||
);
|
||||
|
||||
$resultadoPregunta = $pregunta->guardar();
|
||||
|
||||
|
||||
if (isset($resultadoPregunta['error'])) {
|
||||
|
||||
echo json_encode($resultadoPregunta);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
// Obtenemos el ID de la pregunta creada
|
||||
$idPregunta = (int)$resultadoPregunta['exito_tecnico'];
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* 2. CREAMOS LAS RESPUESTAS
|
||||
* ==========================================
|
||||
*/
|
||||
|
||||
$respuestas = [
|
||||
[
|
||||
'texto' => $respuestaCorrecta,
|
||||
'correcta' => 1
|
||||
],
|
||||
[
|
||||
'texto' => $respuestaIncorrecta1,
|
||||
'correcta' => 0
|
||||
],
|
||||
[
|
||||
'texto' => $respuestaIncorrecta2,
|
||||
'correcta' => 0
|
||||
],
|
||||
[
|
||||
'texto' => $respuestaIncorrecta3,
|
||||
'correcta' => 0
|
||||
]
|
||||
];
|
||||
|
||||
|
||||
foreach ($respuestas as $respuesta) {
|
||||
|
||||
$objRespuesta = new Respuesta(
|
||||
null,
|
||||
$idPregunta,
|
||||
$respuesta['texto'],
|
||||
$respuesta['correcta']
|
||||
);
|
||||
|
||||
|
||||
$resultadoRespuesta = $objRespuesta->insertar();
|
||||
|
||||
|
||||
if (isset($resultadoRespuesta['error'])) {
|
||||
|
||||
echo json_encode($resultadoRespuesta);
|
||||
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* 3. TODO CORRECTO
|
||||
* ==========================================
|
||||
*/
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Pregunta creada correctamente.',
|
||||
'idPregunta' => $idPregunta
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
|
||||
case 'obtenerPreguntasPorCategoria':
|
||||
@@ -49,5 +150,4 @@ switch ($_POST['orden']) {
|
||||
|
||||
echo json_encode($listado);
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@@ -55,6 +55,13 @@ switch ($_POST['orden']) {
|
||||
|
||||
if ($resultado instanceof Usuario) {
|
||||
|
||||
// === GUARDAR EN SESIÓN (incluido avatar)===
|
||||
$_SESSION['idUsuario'] = $resultado->getIdUsuario();
|
||||
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
||||
$_SESSION['email'] = $resultado->getEmail();
|
||||
$_SESSION['avatar'] = $resultado->getAvatar();
|
||||
// =================================================
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Login correcto',
|
||||
'idUsuario' => $resultado->getIdUsuario(),
|
||||
@@ -77,6 +84,7 @@ switch ($_POST['orden']) {
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
// Destruimos la sesión
|
||||
session_destroy();
|
||||
@@ -86,7 +94,6 @@ switch ($_POST['orden']) {
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
case 'mostrarEstadisticas':
|
||||
|
||||
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
||||
@@ -229,4 +236,19 @@ switch ($_POST['orden']) {
|
||||
'ranking' => $ranking
|
||||
]);
|
||||
break;
|
||||
|
||||
case 'comprobarSesion':
|
||||
if (isset($_SESSION['idUsuario']) && !empty($_SESSION['idUsuario'])) {
|
||||
echo json_encode([
|
||||
'activa' => true,
|
||||
'usuario' => [
|
||||
'idUsuario' => $_SESSION['idUsuario'],
|
||||
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? '',
|
||||
'avatar' => $_SESSION['avatar'] ?? ''
|
||||
]
|
||||
]);
|
||||
} else {
|
||||
echo json_encode(['activa' => false]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -117,3 +117,65 @@
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Lógica de juego (js/juego.js) ===== */
|
||||
|
||||
.game-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
height: 8px;
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
background-color: #1368ce;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.feedback {
|
||||
min-height: 1.5em;
|
||||
margin-top: 12px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.feedback.ok { color: #26890c; }
|
||||
.feedback.ko { color: #e21b3c; }
|
||||
|
||||
/* Mientras se envía la respuesta o se ve el feedback no se puede volver a pulsar */
|
||||
.answers-grid.bloqueado .btn-answer {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.btn-answer.correcta {
|
||||
box-shadow: 0 0 0 6px #fff, 0 0 0 10px #26890c;
|
||||
}
|
||||
|
||||
.btn-answer.incorrecta,
|
||||
.btn-answer.atenuada {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.btn-answer:focus-visible {
|
||||
outline: 4px solid #333;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.progress-fill,
|
||||
.btn-answer {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
@@ -1,8 +1,3 @@
|
||||
<?php
|
||||
|
||||
include 'cabecera.php';
|
||||
?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="es-ES">
|
||||
|
||||
@@ -10,28 +5,26 @@ include 'cabecera.php';
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Triviagmático</title>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php include 'cabecera.php'; ?>
|
||||
|
||||
<div class="container my-5">
|
||||
<div class="row justify-content-center align-items-center g-4">
|
||||
|
||||
<!-- Botón Jugar (solo se muestra si está logueado) -->
|
||||
<?php if ($isLoggedIn): ?>
|
||||
<div class="col-12 col-lg-5 col-xl-4">
|
||||
<!-- Botón Jugar (oculto por defecto, JS lo muestra si hay sesión activa) -->
|
||||
<div class="col-12 col-lg-5 col-xl-4 d-none" id="colBotonJugar">
|
||||
<a href="buscadorSala.php" class="btn btn-play-kahoot" id="btnJugar">
|
||||
<i class="fa-solid fa-play"></i>
|
||||
<span>¡JUGAR!</span>
|
||||
</a>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- Ranking -->
|
||||
<div class="col-12 <?= $isLoggedIn ? 'col-lg-7 col-xl-8' : 'col-lg-8' ?>">
|
||||
<div class="col-12 col-lg-8" id="colRanking">
|
||||
<div class="card ranking-card">
|
||||
<div class="ranking-header">
|
||||
<h3 class="m-0"><i class="fa-solid fa-trophy me-2"></i> RANKING GLOBAL DE JUGADORES</h3>
|
||||
|
||||
+161
-387
@@ -4,603 +4,377 @@ $(document).ready(function () {
|
||||
comprobarSalaUsuario();
|
||||
});
|
||||
|
||||
// 1. Comprobar si el usuario actual ya pertenece a una sala
|
||||
function comprobarSalaUsuario() {
|
||||
|
||||
$("#cargandoSalas").remove();
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "obtenerSalaUsuario"
|
||||
},
|
||||
|
||||
data: { orden: "obtenerSalaUsuario" },
|
||||
success: function (respuesta) {
|
||||
|
||||
console.log("Sala del usuario:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
|
||||
console.error(respuesta.error);
|
||||
|
||||
if (respuesta.error || !respuesta.asociado) {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
$("#contenedorCrearSala").show();
|
||||
cargarSalas();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (respuesta.asociado) {
|
||||
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
|
||||
cargarSalaUsuario(respuesta.idPartida);
|
||||
|
||||
} else {
|
||||
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
cargarSalas();
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
$("#contenedorCrearSala").hide(); // Ocultar "Crear Sala" si ya pertenece a una
|
||||
cargarSalaUsuario(respuesta.idPartida);
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"Error al comprobar la sala del usuario:",
|
||||
error
|
||||
);
|
||||
|
||||
console.error("Error al comprobar la sala del usuario:", error);
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
cargarSalas();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
// 2. Cargar únicamente la sala en la que está metido el usuario
|
||||
function cargarSalaUsuario(idPartida) {
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "buscar",
|
||||
idPartida: idPartida
|
||||
},
|
||||
|
||||
data: { orden: "buscar", idPartida: idPartida },
|
||||
success: function (partida) {
|
||||
|
||||
if (partida.error) {
|
||||
|
||||
console.error(partida.error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
cargarInformacionSala(partida);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"Error al obtener la sala del usuario:",
|
||||
error
|
||||
);
|
||||
}
|
||||
console.error("Error al obtener la sala del usuario:", error);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
// 3. Cargar la lista completa de todas las salas
|
||||
function cargarSalas() {
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "listar"
|
||||
},
|
||||
|
||||
data: { orden: "listar" },
|
||||
success: function (partidas) {
|
||||
|
||||
const contenedor = $("#contenedorSalas");
|
||||
|
||||
contenedor.empty();
|
||||
contenedor.empty();
|
||||
|
||||
if (!Array.isArray(partidas) || partidas.length === 0) {
|
||||
|
||||
contenedor.html(`
|
||||
<div class="col-12 text-center">
|
||||
<p class="text-muted">
|
||||
No hay salas disponibles.
|
||||
</p>
|
||||
<p class="text-muted">No hay salas disponibles actualmente.</p>
|
||||
</div>
|
||||
`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
partidas.forEach(function (partida) {
|
||||
|
||||
cargarInformacionSala(partida);
|
||||
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"Error al obtener las partidas:",
|
||||
error
|
||||
);
|
||||
}
|
||||
console.error("Error al obtener las partidas:", error);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
// 4. Obtener equipos y jugadores asociados a una sala concreta
|
||||
function cargarInformacionSala(partida) {
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getEquipos",
|
||||
idPartida: partida.idPartida
|
||||
},
|
||||
|
||||
data: { orden: "getEquipos", idPartida: partida.idPartida },
|
||||
success: function (equipos) {
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getJugadores",
|
||||
idPartida: partida.idPartida
|
||||
},
|
||||
|
||||
data: { orden: "getJugadores", idPartida: partida.idPartida },
|
||||
success: function (jugadores) {
|
||||
|
||||
mostrarSala(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
);
|
||||
mostrarSala(partida, equipos, jugadores);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"Error al obtener jugadores:",
|
||||
error
|
||||
);
|
||||
}
|
||||
console.error("Error al obtener jugadores:", error);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"Error al obtener equipos:",
|
||||
error
|
||||
);
|
||||
}
|
||||
console.error("Error al obtener equipos:", error);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
// 5. Renderizar el HTML de la sala y botones según estado
|
||||
function mostrarSala(partida, equipos, jugadores) {
|
||||
|
||||
const contenedor = $("#contenedorSalas");
|
||||
|
||||
let equiposHTML = "";
|
||||
|
||||
equipos.forEach(function (equipo) {
|
||||
|
||||
const jugadoresEquipo = jugadores.filter(function (jugador) {
|
||||
|
||||
return jugador.idEquipo == equipo.idEquipo;
|
||||
|
||||
});
|
||||
|
||||
let jugadoresHTML = "";
|
||||
|
||||
if (jugadoresEquipo.length > 0) {
|
||||
|
||||
jugadoresEquipo.forEach(function (jugador) {
|
||||
|
||||
jugadoresHTML += `
|
||||
<div class="jugador">
|
||||
|
||||
<span class="avatar">
|
||||
👤
|
||||
</span>
|
||||
|
||||
<span class="avatar">👤</span>
|
||||
${escapeHTML(jugador.nombreUsuario)}
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
jugadoresHTML = `
|
||||
<div class="text-muted small">
|
||||
Sin jugadores
|
||||
</div>
|
||||
`;
|
||||
jugadoresHTML = `<div class="text-muted small">Sin jugadores</div>`;
|
||||
}
|
||||
|
||||
|
||||
// Botón "Unirse" solo visible si NO pertenece a ningún equipo
|
||||
let botonUnirseHTML = "";
|
||||
|
||||
if (!usuarioYaEstaEnEquipo) {
|
||||
|
||||
botonUnirseHTML = `
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-unirse w-100 btn-unirse-equipo"
|
||||
<button type="button" class="btn btn-unirse w-100 btn-unirse-equipo mt-2"
|
||||
data-id-partida="${partida.idPartida}"
|
||||
data-id-equipo="${equipo.idEquipo}">
|
||||
|
||||
Unirse
|
||||
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
equiposHTML += `
|
||||
<div class="equipo">
|
||||
|
||||
<h6>
|
||||
${escapeHTML(equipo.nombreEquipo)}
|
||||
</h6>
|
||||
|
||||
<div class="jugadores">
|
||||
|
||||
<div class="equipo me-2 ms-2 p-3 border rounded">
|
||||
<h6>${escapeHTML(equipo.nombreEquipo)}</h6>
|
||||
<div class="jugadores mb-2">
|
||||
${jugadoresHTML}
|
||||
|
||||
</div>
|
||||
|
||||
${botonUnirseHTML}
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
||||
let accionesSalaHTML = "";
|
||||
if (usuarioYaEstaEnEquipo) {
|
||||
accionesSalaHTML = `
|
||||
<div class="sala-acciones text-center mt-4 pt-3 border-top d-flex justify-content-center gap-3">
|
||||
<button type="button" class="btn btn-outline-danger btn-abandonar-sala" data-id-partida="${partida.idPartida}">
|
||||
Abandonar sala
|
||||
</button>
|
||||
<a href="juego.php?idPartida=${partida.idPartida}" class="btn btn-success btn-lg px-4">
|
||||
🎮 ¡Iniciar Partida!
|
||||
</a>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const salaHTML = `
|
||||
<div class="col-12 col-md-10 col-lg-8">
|
||||
|
||||
<div class="sala">
|
||||
|
||||
<div class="sala-header">
|
||||
|
||||
<div class="sala card p-3 shadow-sm mb-4">
|
||||
<div class="sala-header h4 text-center mb-3">
|
||||
${escapeHTML(partida.nombrePartida)}
|
||||
|
||||
</div>
|
||||
|
||||
<div class="sala-body">
|
||||
|
||||
<div class="equipos">
|
||||
|
||||
<div class="equipos d-flex justify-content-around">
|
||||
${equiposHTML}
|
||||
|
||||
</div>
|
||||
|
||||
${accionesSalaHTML}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
|
||||
|
||||
contenedor.append(salaHTML);
|
||||
|
||||
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// UNIRSE A UN EQUIPO
|
||||
// ======================================================
|
||||
|
||||
$(document).on(
|
||||
"click",
|
||||
".btn-unirse-equipo",
|
||||
function () {
|
||||
|
||||
// 6. Evento: Unirse a un Equipo
|
||||
$(document).on("click", ".btn-unirse-equipo", function () {
|
||||
const boton = $(this);
|
||||
|
||||
const idEquipo = boton.data("id-equipo");
|
||||
|
||||
const idPartida = boton.data("id-partida");
|
||||
|
||||
|
||||
boton.prop("disabled", true);
|
||||
|
||||
boton.text("Uniéndose...");
|
||||
|
||||
boton.prop("disabled", true).text("Uniéndose...");
|
||||
|
||||
$.ajax({
|
||||
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
|
||||
type: "POST",
|
||||
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "registrarUsuarioEnEquipo",
|
||||
idEquipo: idEquipo
|
||||
idEquipo: idEquipo,
|
||||
},
|
||||
|
||||
|
||||
success: function (respuesta) {
|
||||
|
||||
console.log(
|
||||
"Respuesta al unirse:",
|
||||
respuesta
|
||||
);
|
||||
|
||||
|
||||
if (respuesta.error) {
|
||||
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false);
|
||||
|
||||
boton.text("Unirse");
|
||||
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// ==========================================
|
||||
// UNIÓN CORRECTA
|
||||
// ==========================================
|
||||
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
|
||||
// Ocultamos el botón "Crear sala"
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
|
||||
|
||||
// Eliminamos las salas actuales
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
|
||||
// Cargamos directamente la sala
|
||||
// donde acaba de entrar el usuario
|
||||
|
||||
cargarSalaUsuario(idPartida);
|
||||
},
|
||||
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al unirse al equipo:", error);
|
||||
alert("No se ha podido unir al equipo.");
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
console.error(
|
||||
"Error al unirse al equipo:",
|
||||
error
|
||||
);
|
||||
// 7. Evento: Abandonar Sala
|
||||
// Guardamos temporalmente el botón presionado
|
||||
let botonAbandonarReferencia = null;
|
||||
|
||||
console.error(
|
||||
"Respuesta del servidor:",
|
||||
xhr.responseText
|
||||
);
|
||||
// A. Al hacer clic en el botón "Abandonar sala" de la tarjeta, abrimos el modal
|
||||
$(document).on("click", ".btn-abandonar-sala", function () {
|
||||
botonAbandonarReferencia = $(this);
|
||||
const modal = new bootstrap.Modal(document.getElementById('modalAbandonarSala'));
|
||||
modal.show();
|
||||
});
|
||||
|
||||
// B. Al hacer clic en "Sí, salir" dentro del modal Kahoot
|
||||
$(document).on("click", "#btnConfirmarAbandonar", function () {
|
||||
const modalEl = document.getElementById('modalAbandonarSala');
|
||||
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
||||
|
||||
alert(
|
||||
"No se ha podido unir al equipo."
|
||||
);
|
||||
const btnConfirmar = $(this);
|
||||
btnConfirmar.prop("disabled", true).text("Saliendo...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { orden: "salirDeSala" },
|
||||
success: function (respuesta) {
|
||||
btnConfirmar.prop("disabled", false).text("Sí, salir");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
if (modalInstance) {
|
||||
modalInstance.hide();
|
||||
}
|
||||
|
||||
boton.text("Unirse");
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Restablecemos la interfaz a la lista completa de salas
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
$("#contenedorCrearSala").show();
|
||||
cargarSalas();
|
||||
},
|
||||
error: function (xhr, status, 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");
|
||||
if (modalInstance) {
|
||||
modalInstance.hide();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
);
|
||||
|
||||
// ======================================================
|
||||
// ESCAPAR HTML
|
||||
// ======================================================
|
||||
|
||||
function escapeHTML(texto) {
|
||||
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
|
||||
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// CREAR SALA
|
||||
// ======================================================
|
||||
|
||||
$("#btnCrearSala").on(
|
||||
"click",
|
||||
function () {
|
||||
|
||||
const nombreSala =
|
||||
$("#nombreSala").val().trim();
|
||||
|
||||
const nombreEquipo1 =
|
||||
$("#nombreEquipo1").val().trim();
|
||||
|
||||
const nombreEquipo2 =
|
||||
$("#nombreEquipo2").val().trim();
|
||||
|
||||
});
|
||||
// 8. Evento: Crear Sala
|
||||
$("#btnCrearSala").on("click", function () {
|
||||
const nombreSala = $("#nombreSala").val().trim();
|
||||
const nombreEquipo1 = $("#nombreEquipo1").val().trim();
|
||||
const nombreEquipo2 = $("#nombreEquipo2").val().trim();
|
||||
|
||||
let valido = true;
|
||||
let valido = true;
|
||||
|
||||
|
||||
$(".mensaje-error-sala").remove();
|
||||
$(".input-kahoot").removeClass("is-invalid");
|
||||
|
||||
$(".input-kahoot").removeClass(
|
||||
"is-invalid"
|
||||
);
|
||||
|
||||
|
||||
if (nombreSala === "") {
|
||||
|
||||
if (nombreSala === "" || nombreSala.length < 3) {
|
||||
mostrarError(
|
||||
"#nombreSala",
|
||||
"El nombre de la sala es obligatorio."
|
||||
"El nombre de la sala debe tener al menos 3 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
|
||||
} else if (nombreSala.length < 3) {
|
||||
|
||||
mostrarError(
|
||||
"#nombreSala",
|
||||
"El nombre de la sala debe tener al menos 3 caracteres."
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
|
||||
if (nombreEquipo1 === "") {
|
||||
|
||||
if (nombreEquipo1 === "" || nombreEquipo1.length < 2) {
|
||||
mostrarError(
|
||||
"#nombreEquipo1",
|
||||
"El nombre del equipo 1 es obligatorio."
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
|
||||
} else if (nombreEquipo1.length < 2) {
|
||||
|
||||
mostrarError(
|
||||
"#nombreEquipo1",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres."
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
|
||||
if (nombreEquipo2 === "") {
|
||||
|
||||
if (nombreEquipo2 === "" || nombreEquipo2.length < 2) {
|
||||
mostrarError(
|
||||
"#nombreEquipo2",
|
||||
"El nombre del equipo 2 es obligatorio."
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
|
||||
} else if (nombreEquipo2.length < 2) {
|
||||
|
||||
mostrarError(
|
||||
"#nombreEquipo2",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres."
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
|
||||
if (
|
||||
nombreEquipo1 !== "" &&
|
||||
nombreEquipo2 !== "" &&
|
||||
nombreEquipo1.toLowerCase() ===
|
||||
nombreEquipo2.toLowerCase()
|
||||
nombreEquipo1.toLowerCase() === nombreEquipo2.toLowerCase()
|
||||
) {
|
||||
|
||||
mostrarError(
|
||||
"#nombreEquipo2",
|
||||
"Los dos equipos deben tener nombres diferentes."
|
||||
"Los dos equipos deben tener nombres diferentes.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (!valido) return;
|
||||
|
||||
if (!valido) {
|
||||
const boton = $("#btnCrearSala");
|
||||
boton.prop("disabled", true).text("Creando sala...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "crear",
|
||||
nombrePartida: nombreSala,
|
||||
nombreEquipo1: nombreEquipo1,
|
||||
nombreEquipo2: nombreEquipo2,
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
boton.prop("disabled", false).text("Crear sala");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
console.log("Datos válidos:");
|
||||
|
||||
console.log({
|
||||
nombreSala: nombreSala,
|
||||
nombreEquipo1: nombreEquipo1,
|
||||
nombreEquipo2: nombreEquipo2
|
||||
});
|
||||
if (respuesta.exito) {
|
||||
$("#modalCrearSala").modal("hide");
|
||||
location.reload();
|
||||
}
|
||||
},
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al crear la sala:", error);
|
||||
alert("No se ha podido crear la sala.");
|
||||
boton.prop("disabled", false).text("Crear sala");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
);
|
||||
|
||||
// ======================================================
|
||||
// MOSTRAR ERROR
|
||||
// ======================================================
|
||||
// Auxiliares
|
||||
function escapeHTML(texto) {
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
}
|
||||
|
||||
function mostrarError(selector, mensaje) {
|
||||
|
||||
const input = $(selector);
|
||||
|
||||
input.addClass("is-invalid");
|
||||
|
||||
|
||||
input.after(`
|
||||
<div class="mensaje-error-sala text-danger mt-1 small">
|
||||
|
||||
${mensaje}
|
||||
|
||||
</div>
|
||||
`);
|
||||
|
||||
|
||||
input.after(
|
||||
`<div class="mensaje-error-sala text-danger mt-1 small">${mensaje}</div>`,
|
||||
);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// QUITAR ERROR AL ESCRIBIR
|
||||
// ======================================================
|
||||
|
||||
$(".input-kahoot").on(
|
||||
"input",
|
||||
function () {
|
||||
|
||||
$(this).removeClass(
|
||||
"is-invalid"
|
||||
);
|
||||
|
||||
$(this)
|
||||
.next(".mensaje-error-sala")
|
||||
.remove();
|
||||
}
|
||||
|
||||
|
||||
);
|
||||
$(document).on("input", ".input-kahoot", function () {
|
||||
$(this).removeClass("is-invalid");
|
||||
$(this).next(".mensaje-error-sala").remove();
|
||||
});
|
||||
|
||||
+182
-101
@@ -1,133 +1,214 @@
|
||||
// Registro
|
||||
$("#botonAceptarRegistro").click(function (event) {
|
||||
event.preventDefault();
|
||||
console.log("hola");
|
||||
let nombreUsuario = $("#regNombre").val().trim();
|
||||
let email = $("#regEmail").val().trim();
|
||||
let contrasena = $("#regPassword").val();
|
||||
let contrasenaConfirmacion = $("#regPasswordConfirm").val();
|
||||
$(document).ready(function () {
|
||||
// Comprobar la sesión activa al cargar la página
|
||||
comprobarEstadoSesion();
|
||||
|
||||
// Limpiamos errores anteriores
|
||||
$("#regNombre").removeClass("is-invalid");
|
||||
$("#regEmail").removeClass("is-invalid");
|
||||
$("#regPassword").removeClass("is-invalid");
|
||||
$("#regPasswordConfirm").removeClass("is-invalid");
|
||||
$("#errorRegistro").text("");
|
||||
// Evento Click: Login
|
||||
$('#botonAceptarLogin').on('click', function () {
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
// Comprobamos que las contraseñas coincidan
|
||||
if (contrasena !== contrasenaConfirmacion) {
|
||||
$("#regPassword").addClass("is-invalid");
|
||||
$("#regPasswordConfirm").addClass("is-invalid");
|
||||
// Permitir Submit con tecla Enter en el formulario de Login
|
||||
$('#formLogin').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
$("#errorRegistro").text("Las contraseñas no coinciden.");
|
||||
// Evento Click: Registro
|
||||
$('#botonAceptarRegistro').on('click', function () {
|
||||
ejecutarRegistro();
|
||||
});
|
||||
|
||||
// Permitir Submit con tecla Enter en el formulario de Registro
|
||||
$('#formRegistro').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarRegistro();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Comprueba con el servidor si existe una sesión PHP
|
||||
*/
|
||||
function comprobarEstadoSesion() {
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'comprobarSesion' },
|
||||
success: function (respuesta) {
|
||||
if (respuesta.activa) {
|
||||
renderizarCabeceraConSesion(respuesta.usuario);
|
||||
$('#colBotonJugar').removeClass('d-none');
|
||||
} else {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para iniciar sesión
|
||||
*/
|
||||
function ejecutarLogin() {
|
||||
let email = $('#loginEmail').val().trim();
|
||||
let contrasena = $('#loginPassword').val().trim();
|
||||
$('#errorLogin').text('');
|
||||
|
||||
if (email === '' || contrasena === '') {
|
||||
$('#errorLogin').text('Por favor, rellena todos los campos.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
nombreUsuario: nombreUsuario,
|
||||
orden: 'comprobarUsuario',
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "registrarUsuario",
|
||||
contrasena: contrasena
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
//console.log(respuesta);
|
||||
respuesta = JSON.parse(respuesta);
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$("#errorRegistro").text(respuesta.error);
|
||||
$('#errorLogin').text(respuesta.error);
|
||||
} else if (respuesta.exito) {
|
||||
$('#modalLogin').modal('hide');
|
||||
$('#formLogin')[0].reset();
|
||||
|
||||
// Marcamos los campos si hay error
|
||||
$("#regNombre").addClass("is-invalid");
|
||||
$("#regEmail").addClass("is-invalid");
|
||||
} else {
|
||||
// Registro correcto
|
||||
$("#errorRegistro")
|
||||
.removeClass("text-danger")
|
||||
.addClass("text-success")
|
||||
.text(respuesta.exito);
|
||||
|
||||
// Limpiamos formulario
|
||||
$("#formRegistro")[0].reset();
|
||||
|
||||
// Cerramos modal después de un segundo
|
||||
setTimeout(function () {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
// Cargar datos de la sesión actualizados
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
$('#errorLogin').text('Error al conectar con el servidor.');
|
||||
}
|
||||
}); // Fin función ajax
|
||||
});
|
||||
|
||||
// Login
|
||||
$("#botonAceptarLogin").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let email = $("#loginEmail").val().trim();
|
||||
let contrasena = $("#loginPassword").val();
|
||||
|
||||
// Limpiamos errores anteriores
|
||||
$("#loginEmail").removeClass("is-invalid");
|
||||
$("#loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").text("");
|
||||
|
||||
// Comprobación básica
|
||||
if (email === "" || contrasena === "") {
|
||||
$("#errorLogin").text("Todos los campos son obligatorios.");
|
||||
|
||||
if (email === "") {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
}
|
||||
|
||||
if (contrasena === "") {
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
/**
|
||||
* Petición AJAX para registrar un usuario
|
||||
*/
|
||||
function ejecutarRegistro() {
|
||||
let nombre = $('#regNombre').val().trim();
|
||||
let email = $('#regEmail').val().trim();
|
||||
let pass = $('#regPassword').val().trim();
|
||||
let passConfirm = $('#regPasswordConfirm').val().trim();
|
||||
|
||||
$('#errorRegistro').text('');
|
||||
|
||||
if (nombre === '' || email === '' || pass === '') {
|
||||
$('#errorRegistro').text('Todos los campos son obligatorios.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pass !== passConfirm) {
|
||||
$('#errorRegistro').text('Las contraseñas no coinciden.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
orden: 'registrarUsuario',
|
||||
nombreUsuario: nombre,
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "comprobarUsuario",
|
||||
contrasena: pass
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
//console.log(respuesta);
|
||||
respuesta = JSON.parse(respuesta);
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
|
||||
$("#errorLogin").text(respuesta.error);
|
||||
$('#errorRegistro').text(respuesta.error);
|
||||
} else {
|
||||
location.reload();
|
||||
$('#modalRegistro').modal('hide');
|
||||
$('#formRegistro')[0].reset();
|
||||
|
||||
// Autologin tras registrarse
|
||||
$('#loginEmail').val(email);
|
||||
$('#loginPassword').val(pass);
|
||||
ejecutarLogin();
|
||||
}
|
||||
}); // Fin función ajax
|
||||
});
|
||||
|
||||
// Cerrar sesión
|
||||
$("#botonCerrarSesion").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
orden: "cerrarSesion",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
//console.log(respuesta);
|
||||
respuesta = JSON.parse(respuesta);
|
||||
if (respuesta.error) {
|
||||
console.log(respuesta.error);
|
||||
} else {
|
||||
// Sesión cerrada correctamente
|
||||
error: function () {
|
||||
$('#errorRegistro').text('Error al procesar el registro.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para cerrar la sesión
|
||||
*/
|
||||
function cerrarSesion() {
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'cerrarSesion' },
|
||||
success: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
|
||||
if (window.location.pathname.includes('perfil.php') || window.location.pathname.includes('buscadorSala.php')) {
|
||||
window.location.href = 'index.php';
|
||||
|
||||
}
|
||||
}); // Fin función ajax
|
||||
}); // Fin función click
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza la cabecera cuando HAY sesión iniciada
|
||||
*/
|
||||
function renderizarCabeceraConSesion(usuario) {
|
||||
//Mete el avatar en cabecera
|
||||
let avatarImg = (usuario.avatar && usuario.avatar !== '')
|
||||
? usuario.avatar
|
||||
: 'img/avatars/defaultProfile.jpeg';
|
||||
|
||||
// Refrescar avatar si se cambia
|
||||
let avatarConCacheBuster = avatarImg + '?v=' + new Date().getTime();
|
||||
|
||||
let html = `
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<img src="${avatarConCacheBuster}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
||||
<li>
|
||||
<a class="dropdown-item py-2 fw-semibold" href="perfil.php">
|
||||
<i class="fa-solid fa-user me-2 text-primary"></i>Mi Perfil
|
||||
</a>
|
||||
</li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<button class="dropdown-item py-2 fw-semibold text-danger" onclick="cerrarSesion()">
|
||||
<i class="fa-solid fa-right-from-bracket me-2"></i>Cerrar Sesión
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza los botones en la cabecera cuando NO hay sesión (Iniciar sesión azul)
|
||||
*/
|
||||
function renderizarCabeceraSinSesion() {
|
||||
let html = `
|
||||
<button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
||||
</button>
|
||||
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
<i class="fa-solid fa-user-plus me-1"></i> Registrarse
|
||||
</button>
|
||||
`;
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
}
|
||||
|
||||
function escapeHtml(texto) {
|
||||
return $('<div>').text(texto).html();
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
// Lógica de juego.php
|
||||
// Carga las preguntas de la partida, las muestra de una en una,
|
||||
// guarda cada respuesta en el servidor y al terminar lleva a resultados.php
|
||||
|
||||
const URL_CONTROLADOR = "controladores/ControladorJuego.php";
|
||||
const PAUSA_FEEDBACK = 1800; // ms que se ve si has acertado o fallado
|
||||
|
||||
// Colores y formas de los botones (estilo Kahoot, definidos en juego.css)
|
||||
const ESTILOS_BOTON = [
|
||||
{ color: "red", forma: "triangle" },
|
||||
{ color: "blue", forma: "diamond" },
|
||||
{ color: "yellow", forma: "circle" },
|
||||
{ color: "green", forma: "square" },
|
||||
];
|
||||
|
||||
let idPartida = 0;
|
||||
let preguntas = [];
|
||||
let indice = 0; // pregunta que se está mostrando
|
||||
let bloqueado = false; // true mientras se envía una respuesta o se ve el feedback
|
||||
let numeroAciertos = 0; // número de aciertos del jugador
|
||||
|
||||
$(document).ready(function () {
|
||||
idPartida = parseInt($("body").data("id-partida"), 10);
|
||||
|
||||
// Un solo listener para todos los botones de respuesta
|
||||
$("#respuestas").on("click", ".btn-answer", function () {
|
||||
responder($(this));
|
||||
});
|
||||
|
||||
cargarPreguntas();
|
||||
});
|
||||
|
||||
// 1. Pedir las preguntas al servidor
|
||||
function cargarPreguntas() {
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { orden: "cargarPreguntas", idPartida: idPartida },
|
||||
success: function (datos) {
|
||||
if (datos.error) {
|
||||
mostrarError(datos.error);
|
||||
return;
|
||||
}
|
||||
|
||||
preguntas = datos.preguntas;
|
||||
|
||||
if (preguntas.length === 0) {
|
||||
mostrarError("Esta partida no tiene preguntas.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Retomamos por la primera pregunta sin responder (por si recarga la página)
|
||||
indice = preguntas.findIndex(function (p) {
|
||||
return !p.respondida;
|
||||
});
|
||||
|
||||
if (indice === -1) {
|
||||
irAResultados();
|
||||
return;
|
||||
}
|
||||
|
||||
mostrarPregunta();
|
||||
},
|
||||
error: function () {
|
||||
mostrarError("No se pudo conectar con el servidor.");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Pintar la pregunta actual y sus respuestas
|
||||
function mostrarPregunta() {
|
||||
const pregunta = preguntas[indice];
|
||||
|
||||
bloqueado = false;
|
||||
|
||||
$("#textoPregunta").text(pregunta.nombrePregunta);
|
||||
$("#feedback").text("").removeClass("ok ko");
|
||||
$("#contadorPregunta").text(
|
||||
"Pregunta " + (indice + 1) + " de " + preguntas.length,
|
||||
);
|
||||
$("#barraProgreso").css("width", (indice / preguntas.length) * 100 + "%");
|
||||
|
||||
const $respuestas = $("#respuestas").empty();
|
||||
|
||||
pregunta.respuestas.forEach(function (respuesta, i) {
|
||||
const estilo = ESTILOS_BOTON[i % ESTILOS_BOTON.length];
|
||||
|
||||
// .text() y createTextNode evitan que el texto de la BD se interprete como HTML
|
||||
const $boton = $("<button>")
|
||||
.attr("type", "button")
|
||||
.addClass("btn-answer " + estilo.color)
|
||||
.attr("data-id-respuesta", respuesta.idRespuesta)
|
||||
.append($("<span>").addClass("shape " + estilo.forma))
|
||||
.append(document.createTextNode(respuesta.nombreRespuesta));
|
||||
|
||||
$respuestas.append($boton);
|
||||
});
|
||||
}
|
||||
|
||||
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
|
||||
function responder($botonPulsado) {
|
||||
if (bloqueado) {
|
||||
return;
|
||||
}
|
||||
bloqueado = true;
|
||||
|
||||
const pregunta = preguntas[indice];
|
||||
const idRespuesta = parseInt($botonPulsado.attr("data-id-respuesta"), 10);
|
||||
|
||||
$("#respuestas").addClass("bloqueado");
|
||||
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "responder",
|
||||
idPartida: idPartida,
|
||||
idPartidaxPregunta: pregunta.idPartidaxPregunta,
|
||||
idRespuesta: idRespuesta,
|
||||
},
|
||||
success: function (datos) {
|
||||
if (datos.error) {
|
||||
// No se guardó: dejamos que vuelva a intentarlo
|
||||
$("#feedback").text(datos.error).removeClass("ok").addClass("ko");
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
bloqueado = false;
|
||||
return;
|
||||
}
|
||||
|
||||
pregunta.respondida = true;
|
||||
mostrarFeedback($botonPulsado, datos);
|
||||
|
||||
setTimeout(function () {
|
||||
if (datos.terminada || indice >= preguntas.length - 1) {
|
||||
terminar();
|
||||
} else {
|
||||
indice++;
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
mostrarPregunta();
|
||||
}
|
||||
}, PAUSA_FEEDBACK);
|
||||
},
|
||||
error: function () {
|
||||
$("#feedback")
|
||||
.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 () {
|
||||
const $boton = $(this);
|
||||
const esLaCorrecta =
|
||||
parseInt($boton.attr("data-id-respuesta"), 10) ===
|
||||
datos.idRespuestaCorrecta;
|
||||
|
||||
if (esLaCorrecta) {
|
||||
$boton.addClass("correcta");
|
||||
} else {
|
||||
$boton.addClass("atenuada");
|
||||
}
|
||||
});
|
||||
|
||||
if (datos.acierto) {
|
||||
$("#feedback").text("¡Correcto!").removeClass("ko").addClass("ok");
|
||||
numeroAciertos++;
|
||||
} else {
|
||||
$botonPulsado.addClass("incorrecta");
|
||||
$("#feedback")
|
||||
.text("Respuesta incorrecta. La correcta está marcada.")
|
||||
.removeClass("ok")
|
||||
.addClass("ko");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Última pregunta respondida: se avisa al backend con los aciertos y luego se va a resultados
|
||||
function terminar() {
|
||||
$("#barraProgreso").css("width", "100%");
|
||||
$("#respuestas").empty();
|
||||
$("#contadorPregunta").text("Partida terminada");
|
||||
$("#textoPregunta").text("¡Has terminado! Cargando resultados…");
|
||||
$("#feedback").text("").removeClass("ok ko");
|
||||
|
||||
setTimeout(function () {
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "finalizarPartida",
|
||||
idPartida: idPartida,
|
||||
aciertos: numeroAciertos,
|
||||
},
|
||||
complete: function () {
|
||||
// Se va a resultados tanto si el AJAX ha ido bien como si ha fallado
|
||||
irAResultados();
|
||||
},
|
||||
});
|
||||
}, 1200);
|
||||
}
|
||||
|
||||
function irAResultados() {
|
||||
window.location.href = "resultados.php?idPartida=" + idPartida;
|
||||
}
|
||||
|
||||
function mostrarError(mensaje) {
|
||||
$("#respuestas").empty();
|
||||
$("#textoPregunta").text(mensaje);
|
||||
$("#feedback").html(
|
||||
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
|
||||
);
|
||||
}
|
||||
+145
-7
@@ -26,6 +26,10 @@ $.ajax({
|
||||
function cambiarNombre() {
|
||||
let nuevoNombre = $("#nuevoNombre").val().trim();
|
||||
|
||||
if (nuevoNombre === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
@@ -42,8 +46,13 @@ function cambiarNombre() {
|
||||
// Actualizamos el nombre mostrado en la página
|
||||
$("#nombre").text(respuesta.nombreUsuario);
|
||||
|
||||
// Limpiamos el input
|
||||
|
||||
$("#nuevoNombre").val("");
|
||||
|
||||
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -56,7 +65,6 @@ function borrarNombre() {
|
||||
document.getElementById("nuevoNombre").value = "";
|
||||
}
|
||||
|
||||
|
||||
// =========================
|
||||
// CAMBIAR FOTO
|
||||
// =========================
|
||||
@@ -75,14 +83,11 @@ $("#inputFoto").change(function () {
|
||||
// Comprobamos que sea una imagen
|
||||
if (!archivo.type.startsWith("image/")) {
|
||||
alert("El archivo seleccionado no es una imagen.");
|
||||
|
||||
$("#inputFoto").val("");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let datos = new FormData();
|
||||
|
||||
datos.append("avatar", archivo);
|
||||
datos.append("orden", "cambiarAvatar");
|
||||
|
||||
@@ -98,11 +103,144 @@ $("#inputFoto").change(function () {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
} else {
|
||||
// Actualizamos la imagen sin recargar la página
|
||||
// Actualizamos la imagen en la página de perfil sin recargar
|
||||
$("#fotoPerfil").attr(
|
||||
"src",
|
||||
respuesta.avatar + "?t=" + new Date().getTime(),
|
||||
respuesta.avatar + "?t=" + new Date().getTime()
|
||||
);
|
||||
|
||||
// Actualizamos también el avatar superior en la cabecera
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// =========================
|
||||
// RECOGER CATEGORIAS
|
||||
// =========================
|
||||
|
||||
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||
const selectCategoria = $("#idCategoria");
|
||||
|
||||
// Limpiamos las categorías anteriores
|
||||
selectCategoria.empty();
|
||||
|
||||
// Opción inicial
|
||||
selectCategoria.append('<option value="">Selecciona una categoría</option>');
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorCategoria.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "listarCategorias",
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
console.log("Categorías:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
return;
|
||||
}
|
||||
|
||||
$.each(respuesta, function (index, categoria) {
|
||||
selectCategoria.append(
|
||||
$("<option>", {
|
||||
value: categoria.idCategoria,
|
||||
text: categoria.nombreCategoria,
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al cargar las categorías:", error);
|
||||
console.error("Respuesta del servidor:", xhr.responseText);
|
||||
alert("No se han podido cargar las categorías.");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// =========================
|
||||
// CREAR PREGUNTA
|
||||
// =========================
|
||||
|
||||
$("#formCrearPregunta").on("submit", function (e) {
|
||||
e.preventDefault();
|
||||
|
||||
const boton = $("#btnCrearPregunta");
|
||||
|
||||
const pregunta = $("#pregunta").val().trim();
|
||||
const respuestaCorrecta = $("#respuestaCorrecta").val().trim();
|
||||
const respuestaIncorrecta1 = $("#respuestaIncorrecta1").val().trim();
|
||||
const respuestaIncorrecta2 = $("#respuestaIncorrecta2").val().trim();
|
||||
const respuestaIncorrecta3 = $("#respuestaIncorrecta3").val().trim();
|
||||
|
||||
// Comprobamos que no haya campos vacíos
|
||||
if (
|
||||
pregunta === "" ||
|
||||
respuestaCorrecta === "" ||
|
||||
respuestaIncorrecta1 === "" ||
|
||||
respuestaIncorrecta2 === "" ||
|
||||
respuestaIncorrecta3 === ""
|
||||
) {
|
||||
alert("Todos los campos son obligatorios.");
|
||||
return;
|
||||
}
|
||||
|
||||
boton.prop("disabled", true);
|
||||
boton.text("Creando pregunta...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPregunta.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "crearPregunta",
|
||||
idCategoria: $("#idCategoria").val(),
|
||||
nombrePregunta: pregunta,
|
||||
respuestaCorrecta: respuestaCorrecta,
|
||||
respuestaIncorrecta1: respuestaIncorrecta1,
|
||||
respuestaIncorrecta2: respuestaIncorrecta2,
|
||||
respuestaIncorrecta3: respuestaIncorrecta3,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
console.log("Respuesta del servidor:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear pregunta");
|
||||
return;
|
||||
}
|
||||
|
||||
if (respuesta.exito) {
|
||||
console.log("Pregunta creada:", respuesta.idPregunta);
|
||||
|
||||
// Cerramos el modal
|
||||
$("#modalCrearPregunta").modal("hide");
|
||||
|
||||
// Limpiamos el formulario
|
||||
$("#formCrearPregunta")[0].reset();
|
||||
|
||||
// Volvemos a activar el botón
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear pregunta");
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al crear la pregunta:", error);
|
||||
console.error("Respuesta del servidor:", xhr.responseText);
|
||||
alert("No se ha podido crear la pregunta.");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear pregunta");
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,20 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Hay que estar logueado para jugar
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// La partida llega por la URL: juego.php?idPartida=3
|
||||
$idPartida = filter_input(INPUT_GET, 'idPartida', FILTER_VALIDATE_INT);
|
||||
|
||||
if (!$idPartida || $idPartida < 1) {
|
||||
header('Location: buscadorSala.php');
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
@@ -8,39 +25,27 @@
|
||||
<link rel="stylesheet" href="css/juego.css">
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
</head>
|
||||
<body>
|
||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
||||
|
||||
<!-- Contenedor de la Pregunta -->
|
||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
||||
<div class="game-header">
|
||||
<span id="contadorPregunta">Cargando…</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill" id="barraProgreso"></div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de la Pregunta (lo rellena js/juego.js) -->
|
||||
<div class="question-container">
|
||||
¿Cuál es el planeta más grande de nuestro sistema solar?
|
||||
<div id="textoPregunta">Cargando preguntas…</div>
|
||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot) -->
|
||||
<div class="answers-grid">
|
||||
<button class="btn-answer red" onclick="checkAnswer('Marte')">
|
||||
<span class="shape triangle"></span>
|
||||
Marte
|
||||
</button>
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
||||
<div class="answers-grid" id="respuestas"></div>
|
||||
|
||||
<button class="btn-answer blue" onclick="checkAnswer('Júpiter')">
|
||||
<span class="shape diamond"></span>
|
||||
Júpiter
|
||||
</button>
|
||||
|
||||
<button class="btn-answer yellow" onclick="checkAnswer('Saturno')">
|
||||
<span class="shape circle"></span>
|
||||
Saturno
|
||||
</button>
|
||||
|
||||
<button class="btn-answer green" onclick="checkAnswer('Tierra')">
|
||||
<span class="shape square"></span>
|
||||
Tierra
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
</script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/juego.js"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 120 KiB |
+58
-186
@@ -1,3 +1,17 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Redirección si el usuario no ha iniciado sesión
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: login.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$nombreUsuario = htmlspecialchars($_SESSION['nombreUsuario'] ?? 'Usuario');
|
||||
$avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultProfile.jpeg');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
@@ -9,151 +23,99 @@
|
||||
<title>Perfil</title>
|
||||
|
||||
<!-- Bootstrap -->
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
|
||||
<!-- Bootstrap Icons -->
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
|
||||
<!-- Google Font: Fredoka -->
|
||||
<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 href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Tu CSS -->
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<link rel="stylesheet" href="css/perfil.css">
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
<body>
|
||||
|
||||
<?php
|
||||
include_once 'cabecera.php';
|
||||
?>
|
||||
|
||||
<?php include_once 'cabecera.php'; ?>
|
||||
|
||||
<div class="perfil-container">
|
||||
|
||||
<div class="perfil-card">
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CABECERA -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="perfil-header">
|
||||
<i class="bi bi-person-circle"></i>
|
||||
Mi perfil
|
||||
</div>
|
||||
|
||||
|
||||
<div class="perfil-content">
|
||||
|
||||
<div class="row align-items-center g-5">
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- PERFIL -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="col-md-6 text-center">
|
||||
|
||||
<!-- Nombre -->
|
||||
|
||||
<h1 id="nombre" class="nombre">
|
||||
<?php echo $_SESSION['nombreUsuario'] ?>
|
||||
<?= $nombreUsuario ?>
|
||||
</h1>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- FOTO DE PERFIL -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="foto-container">
|
||||
|
||||
<img
|
||||
id="fotoPerfil"
|
||||
src="<?= htmlspecialchars($_SESSION['avatar'] ?? '') ?>"
|
||||
<img id="fotoPerfil"
|
||||
src="<?= $avatarUsuario ?>"
|
||||
alt="Foto de perfil"
|
||||
class="avatar rounded-circle">
|
||||
|
||||
|
||||
<!-- Botón lápiz -->
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-foto"
|
||||
onclick="seleccionarFoto()"
|
||||
title="Cambiar foto de perfil"
|
||||
aria-label="Cambiar foto de perfil">
|
||||
|
||||
<i class="bi bi-pencil-fill"></i>
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<!-- Input oculto -->
|
||||
|
||||
<input
|
||||
type="file"
|
||||
<input type="file"
|
||||
id="inputFoto"
|
||||
accept="image/*"
|
||||
hidden>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CAMBIAR NOMBRE -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="formulario-nombre">
|
||||
|
||||
<label
|
||||
for="nuevoNombre"
|
||||
class="form-label">
|
||||
|
||||
<label for="nuevoNombre" class="form-label">
|
||||
Cambia tu nombre
|
||||
|
||||
</label>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="nuevoNombre"
|
||||
class="form-control mb-3"
|
||||
placeholder="Escribe tu nuevo nombre">
|
||||
|
||||
|
||||
<div class="d-flex justify-content-center gap-2">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-perfil-cambiar"
|
||||
onclick="cambiarNombre()">
|
||||
|
||||
<i class="bi bi-check-lg"></i>
|
||||
Cambiar nombre
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-perfil-borrar"
|
||||
onclick="borrarNombre()">
|
||||
|
||||
<i class="bi bi-x-lg"></i>
|
||||
Borrar
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
@@ -162,11 +124,7 @@
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- ESTADÍSTICAS -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="col-md-6">
|
||||
|
||||
<div class="estadisticas">
|
||||
@@ -176,60 +134,33 @@
|
||||
Estadísticas
|
||||
</h2>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-victorias">
|
||||
|
||||
<i class="bi bi-trophy-fill"></i>
|
||||
Victorias:
|
||||
|
||||
<strong id="victorias">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="victorias">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-derrotas">
|
||||
|
||||
<i class="bi bi-x-circle-fill"></i>
|
||||
Derrotas:
|
||||
|
||||
<strong id="derrotas">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="derrotas">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-aciertos">
|
||||
|
||||
<i class="bi bi-bullseye"></i>
|
||||
Aciertos:
|
||||
|
||||
<strong id="aciertos">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="aciertos">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CREAR PREGUNTA -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="text-center mt-4">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn btn-play-kahoot"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalCrearPregunta">
|
||||
|
||||
<i class="bi bi-plus-circle-fill"></i>
|
||||
Crear pregunta
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -245,12 +176,8 @@
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ================================================= -->
|
||||
<!-- MODAL CREAR PREGUNTA -->
|
||||
<!-- ================================================= -->
|
||||
|
||||
<div
|
||||
class="modal fade"
|
||||
<div class="modal fade"
|
||||
id="modalCrearPregunta"
|
||||
tabindex="-1"
|
||||
aria-labelledby="modalCrearPreguntaLabel"
|
||||
@@ -260,157 +187,107 @@
|
||||
|
||||
<div class="modal-content modal-kahoot">
|
||||
|
||||
|
||||
<!-- CABECERA DEL MODAL -->
|
||||
|
||||
<div class="modal-header modal-kahoot-header">
|
||||
|
||||
<h5
|
||||
class="modal-title"
|
||||
id="modalCrearPreguntaLabel">
|
||||
|
||||
<h5 class="modal-title" id="modalCrearPreguntaLabel">
|
||||
<i class="bi bi-question-circle-fill me-2"></i>
|
||||
Crear pregunta
|
||||
|
||||
</h5>
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-close btn-close-white"
|
||||
data-bs-dismiss="modal"
|
||||
aria-label="Cerrar">
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- CUERPO DEL MODAL -->
|
||||
|
||||
<div class="modal-body p-4">
|
||||
|
||||
<form id="formCrearPregunta">
|
||||
|
||||
|
||||
<!-- PREGUNTA -->
|
||||
|
||||
<div class="mb-4">
|
||||
|
||||
<label
|
||||
for="pregunta"
|
||||
class="form-label fw-semibold">
|
||||
|
||||
<label for="pregunta" class="form-label fw-semibold">
|
||||
<i class="bi bi-question-lg me-1"></i>
|
||||
Pregunta
|
||||
|
||||
</label>
|
||||
|
||||
<textarea
|
||||
id="pregunta"
|
||||
<textarea id="pregunta"
|
||||
name="pregunta"
|
||||
class="form-control input-kahoot"
|
||||
rows="3"
|
||||
placeholder="Escribe aquí la pregunta..."
|
||||
required></textarea>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- CATEGORÍA -->
|
||||
<div class="mb-4">
|
||||
<label for="idCategoria" class="form-label fw-semibold">
|
||||
<i class="bi bi-folder-fill me-1"></i>
|
||||
Categoría
|
||||
</label>
|
||||
<select id="idCategoria"
|
||||
name="idCategoria"
|
||||
class="form-select input-kahoot"
|
||||
required>
|
||||
<option value="">Selecciona una categoría</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- RESPUESTA CORRECTA -->
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="respuestaCorrecta"
|
||||
class="form-label fw-semibold text-success">
|
||||
|
||||
<label for="respuestaCorrecta" class="form-label fw-semibold text-success">
|
||||
<i class="bi bi-check-circle-fill me-1"></i>
|
||||
Respuesta correcta
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaCorrecta"
|
||||
name="respuestaCorrecta"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Escribe la respuesta correcta..."
|
||||
required>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- RESPUESTAS INCORRECTAS -->
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
class="form-label fw-semibold text-danger">
|
||||
|
||||
<label class="form-label fw-semibold text-danger">
|
||||
<i class="bi bi-x-circle-fill me-1"></i>
|
||||
Respuestas incorrectas
|
||||
|
||||
</label>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta1"
|
||||
name="respuestaIncorrecta1"
|
||||
class="form-control input-kahoot mb-2"
|
||||
placeholder="Respuesta incorrecta 1"
|
||||
required>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta2"
|
||||
name="respuestaIncorrecta2"
|
||||
class="form-control input-kahoot mb-2"
|
||||
placeholder="Respuesta incorrecta 2"
|
||||
required>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta3"
|
||||
name="respuestaIncorrecta3"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Respuesta incorrecta 3"
|
||||
required>
|
||||
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- PIE DEL MODAL -->
|
||||
|
||||
<div class="modal-footer">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
data-bs-dismiss="modal">
|
||||
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
|
||||
<i class="bi bi-x-lg me-1"></i>
|
||||
Cancelar
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
form="formCrearPregunta"
|
||||
class="btn btn-kahoot-login">
|
||||
|
||||
<button type="submit" form="formCrearPregunta" class="btn btn-kahoot-login" id="btnCrearPregunta">
|
||||
<i class="bi bi-check-lg me-1"></i>
|
||||
Crear pregunta
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -420,14 +297,9 @@
|
||||
</div>
|
||||
|
||||
<!-- Bootstrap JS -->
|
||||
|
||||
<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>
|
||||
|
||||
<!-- Tu JavaScript -->
|
||||
|
||||
<script src="js/perfil.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user