Compare commits
71 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c3fbf2f90 | |||
| cd53cba69e | |||
| 5f407ce8f4 | |||
| d20b1fa7d7 | |||
| 02e725e0f3 | |||
| 3856db81ef | |||
| bdc7bef169 | |||
| 963ab50f37 | |||
| 9488d7cee7 | |||
| 0b8045544b | |||
| d67e4d76e2 | |||
| 20131bbe7f | |||
| c624f06b88 | |||
| e879a92ac2 | |||
| c18576e97d | |||
| fd4301d741 | |||
| afff6cfb4a | |||
| 46bfb7ea62 | |||
| cbdbd8bc4b | |||
| 8bea83460b | |||
| 554cf5c52f | |||
| c0207197fb | |||
| 5113b960d2 | |||
| 83b1ae90c6 | |||
| d994f09f7d | |||
| 8453735727 | |||
| 90a2ad1256 | |||
| fdd1ba8272 | |||
| befc6a7cc1 | |||
| e9cf7c8fcf | |||
| 111a101037 | |||
| 71b7337dba | |||
| dc5c04b693 | |||
| 29eb70b626 | |||
| 5bf5b7a3bc | |||
| e8accf949e | |||
| fa883cde39 | |||
| ae213a3d12 | |||
| cd0685f41c | |||
| e3395a017c | |||
| 396aca8b03 | |||
| c6db380ef9 | |||
| 8d5d7da615 | |||
| 7f70112f63 | |||
| a66ac7086d | |||
| eed77db62f | |||
| 83545152bb | |||
| 71fb45b94c | |||
| 5b6352b4ee | |||
| 7e1344a395 | |||
| db5061ec7f | |||
| 737b76e83b | |||
| 3705a9ea9e | |||
| 72134b405c | |||
| 91056a05d9 | |||
| 18a56e0bbd | |||
| ed7067161a | |||
| 2531ef321a | |||
| d3e523ad73 | |||
| 77249ba51b | |||
| 5446352cf9 | |||
| 95f7d8dad6 | |||
| 4f6e15863e | |||
| 2169586cd9 | |||
| 98b383d16f | |||
| 87c8ea871a | |||
| 1980f7582f | |||
| d8837484b0 | |||
| d5cd07b135 | |||
| fc7629143d | |||
| d22a642cca |
@@ -59,7 +59,7 @@ Configuración de acceso al servidor de producción:
|
||||
- SSH/SCP/SFTP:
|
||||
- Host: desarrolloalcala.com
|
||||
- Puerto: 2222
|
||||
- Usuario: alumnado
|
||||
- Usuario: my_webapp
|
||||
- Contraseña: epdsrntr\*\*
|
||||
- Acceso WEB al panel de control:
|
||||
- URL: http://desarrolloalcala.com
|
||||
|
||||
+8
-4
@@ -10,11 +10,12 @@
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<link rel="stylesheet" href="css/buscadorSala.css">
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php include_once("cabecera.php"); ?>
|
||||
<header id="cabecera-container"></header>
|
||||
|
||||
<main class="container py-4">
|
||||
|
||||
@@ -22,7 +23,7 @@
|
||||
<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"/>
|
||||
<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>
|
||||
@@ -71,7 +72,7 @@
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-kahoot-login" id="btnCrearSala">Crear sala</button>
|
||||
<button type="button" class="btn btn-kahoot-register" id="btnCrearSala">Crear sala</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -99,8 +100,11 @@
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/sala.js"></script>
|
||||
<script src="js/buscadorSala.js"></script>
|
||||
<script src="js/cabecera.js"></script>
|
||||
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+110
@@ -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>
|
||||
-110
@@ -1,110 +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>
|
||||
</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>
|
||||
|
||||
<!-- 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>
|
||||
<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>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/triviagmatico/includes/conexionBD.php';
|
||||
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
class Categoria{
|
||||
|
||||
@@ -1,269 +1,269 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
|
||||
class EquipoxUsuario
|
||||
{
|
||||
public $idEquipoxUsuario;
|
||||
public $idUsuario;
|
||||
public $idEquipo;
|
||||
|
||||
public function __construct($idEquipoxUsuario = null, $idUsuario = null, $idEquipo = null)
|
||||
{
|
||||
$this->idEquipoxUsuario = $idEquipoxUsuario;
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->idEquipo = $idEquipo;
|
||||
}
|
||||
|
||||
public function registrarUsuarioEnEquipo()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO equipoxusuario (idUsuario, idEquipo) VALUES (:idUsuario, :idEquipo)";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idUsuario', $this->idUsuario);
|
||||
$consulta->bindParam(':idEquipo', $this->idEquipo);
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
'exito' => 'Usuario vinculado al equipo correctamente.',
|
||||
'exito_tecnico' => $conexion->lastInsertId()
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al unir al usuario con el equipo.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function listarUsuariosPorEquipo($idEquipo)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "SELECT u.* FROM equipoxusuario exu
|
||||
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
|
||||
WHERE exu.idEquipo = :idEquipo";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idEquipo', $idEquipo);
|
||||
$consulta->execute();
|
||||
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener los miembros del equipo.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function obtenerSalaUsuario($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "
|
||||
SELECT
|
||||
exu.idEquipo,
|
||||
exp.idPartida
|
||||
FROM equipoxusuario exu
|
||||
|
||||
INNER JOIN equipoxpartida exp
|
||||
ON exu.idEquipo = exp.idEquipo
|
||||
|
||||
WHERE exu.idUsuario = :idUsuario
|
||||
|
||||
LIMIT 1
|
||||
";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
|
||||
$consulta->bindParam(
|
||||
':idUsuario',
|
||||
$idUsuario,
|
||||
PDO::PARAM_INT
|
||||
);
|
||||
|
||||
$consulta->execute();
|
||||
|
||||
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$resultado) {
|
||||
|
||||
return [
|
||||
'asociado' => false
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'asociado' => true,
|
||||
'idEquipo' => $resultado['idEquipo'],
|
||||
'idPartida' => $resultado['idPartida']
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener la sala del usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function salirDeSala($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// 1. Averiguamos el equipo y la partida del usuario
|
||||
$sql = "SELECT exu.idEquipo, exp.idPartida, p.idUsuario AS idHost FROM equipoxusuario exu INNER JOIN equipoxpartida exp ON exu.idEquipo = exp.idEquipo INNER JOIN partida p ON exp.idPartida = p.idPartida WHERE exu.idUsuario = :idUsuario LIMIT 1";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idUsuario',$idUsuario, PDO::PARAM_INT);
|
||||
$consulta->execute();
|
||||
|
||||
$datosSala = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// El usuario no pertenece a ninguna sala
|
||||
if (!$datosSala) {
|
||||
return [
|
||||
'error' => 'No perteneces a ninguna sala.'
|
||||
];
|
||||
}
|
||||
|
||||
$idEquipo = (int)$datosSala['idEquipo'];
|
||||
$idPartida = (int)$datosSala['idPartida'];
|
||||
$idHost = (int)$datosSala['idHost'];
|
||||
|
||||
// Comenzamos una transacción
|
||||
$conexion->beginTransaction();
|
||||
|
||||
/*
|
||||
* 2. Comprobamos si quien abandona es el HOST
|
||||
*/
|
||||
if ($idUsuario === $idHost) {
|
||||
|
||||
/*
|
||||
* Obtenemos todos los equipos pertenecientes
|
||||
* a esta partida.
|
||||
*/
|
||||
$sqlEquipos = "SELECT idEquipo FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaEquipos = $conexion->prepare($sqlEquipos);
|
||||
$consultaEquipos->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaEquipos->execute();
|
||||
|
||||
$equipos = $consultaEquipos->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
/*
|
||||
* 3. Eliminamos los jugadores de esos equipos
|
||||
* de la tabla equipoxusuario.
|
||||
*/
|
||||
if (!empty($equipos)) {
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||
|
||||
$sqlUsuarios = "DELETE FROM equipoxusuario WHERE idEquipo IN ($placeholders)";
|
||||
|
||||
$consultaUsuarios = $conexion->prepare($sqlUsuarios);
|
||||
$consultaUsuarios->execute($equipos);
|
||||
}
|
||||
|
||||
/*
|
||||
* 4. Eliminamos las relaciones
|
||||
* entre equipos y partida.
|
||||
*/
|
||||
$sqlEquipoxPartida = "DELETE FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaEquipoxPartida = $conexion->prepare($sqlEquipoxPartida);
|
||||
$consultaEquipoxPartida->bindParam(':idPartida', $idPartida,PDO::PARAM_INT);
|
||||
$consultaEquipoxPartida->execute();
|
||||
|
||||
/*
|
||||
* 5. Eliminamos los equipos.
|
||||
*
|
||||
* Los equipos ya no tienen relaciones con
|
||||
* usuarios ni con la partida.
|
||||
*/
|
||||
if (!empty($equipos)) {
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||
|
||||
$sqlEliminarEquipos = "DELETE FROM equipo WHERE idEquipo IN ($placeholders)";
|
||||
$consultaEliminarEquipos = $conexion->prepare($sqlEliminarEquipos);
|
||||
$consultaEliminarEquipos->execute($equipos);
|
||||
}
|
||||
|
||||
/*
|
||||
* 6. Eliminamos las relaciones
|
||||
* entre preguntas y partida.
|
||||
*/
|
||||
$sqlPartidaxPregunta = "DELETE FROM partidaxpregunta WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaPartidaxPregunta = $conexion->prepare($sqlPartidaxPregunta);
|
||||
$consultaPartidaxPregunta->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaPartidaxPregunta->execute();
|
||||
|
||||
/*
|
||||
* 7. Finalmente eliminamos la partida.
|
||||
*/
|
||||
$sqlPartida = "DELETE FROM partida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaPartida = $conexion->prepare($sqlPartida);
|
||||
$consultaPartida->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaPartida->execute();
|
||||
|
||||
// Todo ha ido correctamente
|
||||
$conexion->commit();
|
||||
|
||||
return [
|
||||
'exito' => true,
|
||||
'salaEliminada' => true,
|
||||
'mensaje' => 'La sala ha sido eliminada correctamente.'
|
||||
];
|
||||
}
|
||||
|
||||
/*
|
||||
* 7. Si NO es el host, simplemente abandona
|
||||
* su relación con el equipo.
|
||||
*/
|
||||
$sqlSalir = "DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario";
|
||||
|
||||
$consultaSalir = $conexion->prepare($sqlSalir);
|
||||
$consultaSalir->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
|
||||
$consultaSalir->execute();
|
||||
|
||||
$conexion->commit();
|
||||
|
||||
return [
|
||||
'exito' => true,
|
||||
'salaEliminada' => false,
|
||||
'mensaje' => 'Has abandonado la sala correctamente.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
// Si había una transacción activa, la deshacemos
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al abandonar la sala.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
|
||||
class EquipoxUsuario
|
||||
{
|
||||
public $idEquipoxUsuario;
|
||||
public $idUsuario;
|
||||
public $idEquipo;
|
||||
|
||||
public function __construct($idEquipoxUsuario = null, $idUsuario = null, $idEquipo = null)
|
||||
{
|
||||
$this->idEquipoxUsuario = $idEquipoxUsuario;
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->idEquipo = $idEquipo;
|
||||
}
|
||||
|
||||
public function registrarUsuarioEnEquipo()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO equipoxusuario (idUsuario, idEquipo) VALUES (:idUsuario, :idEquipo)";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idUsuario', $this->idUsuario);
|
||||
$consulta->bindParam(':idEquipo', $this->idEquipo);
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
'exito' => 'Usuario vinculado al equipo correctamente.',
|
||||
'exito_tecnico' => $conexion->lastInsertId()
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al unir al usuario con el equipo.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function listarUsuariosPorEquipo($idEquipo)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "SELECT u.* FROM equipoxusuario exu
|
||||
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
|
||||
WHERE exu.idEquipo = :idEquipo";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idEquipo', $idEquipo);
|
||||
$consulta->execute();
|
||||
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener los miembros del equipo.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function obtenerSalaUsuario($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "
|
||||
SELECT
|
||||
exu.idEquipo,
|
||||
exp.idPartida
|
||||
FROM equipoxusuario exu
|
||||
|
||||
INNER JOIN equipoxpartida exp
|
||||
ON exu.idEquipo = exp.idEquipo
|
||||
|
||||
WHERE exu.idUsuario = :idUsuario
|
||||
|
||||
LIMIT 1
|
||||
";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
|
||||
$consulta->bindParam(
|
||||
':idUsuario',
|
||||
$idUsuario,
|
||||
PDO::PARAM_INT
|
||||
);
|
||||
|
||||
$consulta->execute();
|
||||
|
||||
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if (!$resultado) {
|
||||
|
||||
return [
|
||||
'asociado' => false
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'asociado' => true,
|
||||
'idEquipo' => $resultado['idEquipo'],
|
||||
'idPartida' => $resultado['idPartida']
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener la sala del usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function salirDeSala($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
// 1. Averiguamos el equipo y la partida del usuario
|
||||
$sql = "SELECT exu.idEquipo, exp.idPartida, p.idUsuario AS idHost FROM equipoxusuario exu INNER JOIN equipoxpartida exp ON exu.idEquipo = exp.idEquipo INNER JOIN partida p ON exp.idPartida = p.idPartida WHERE exu.idUsuario = :idUsuario LIMIT 1";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idUsuario',$idUsuario, PDO::PARAM_INT);
|
||||
$consulta->execute();
|
||||
|
||||
$datosSala = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
// El usuario no pertenece a ninguna sala
|
||||
if (!$datosSala) {
|
||||
return [
|
||||
'error' => 'No perteneces a ninguna sala.'
|
||||
];
|
||||
}
|
||||
|
||||
$idEquipo = (int)$datosSala['idEquipo'];
|
||||
$idPartida = (int)$datosSala['idPartida'];
|
||||
$idHost = (int)$datosSala['idHost'];
|
||||
|
||||
// Comenzamos una transacción
|
||||
$conexion->beginTransaction();
|
||||
|
||||
/*
|
||||
* 2. Comprobamos si quien abandona es el HOST
|
||||
*/
|
||||
if ($idUsuario === $idHost) {
|
||||
|
||||
/*
|
||||
* Obtenemos todos los equipos pertenecientes
|
||||
* a esta partida.
|
||||
*/
|
||||
$sqlEquipos = "SELECT idEquipo FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaEquipos = $conexion->prepare($sqlEquipos);
|
||||
$consultaEquipos->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaEquipos->execute();
|
||||
|
||||
$equipos = $consultaEquipos->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
/*
|
||||
* 3. Eliminamos los jugadores de esos equipos
|
||||
* de la tabla equipoxusuario.
|
||||
*/
|
||||
if (!empty($equipos)) {
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||
|
||||
$sqlUsuarios = "DELETE FROM equipoxusuario WHERE idEquipo IN ($placeholders)";
|
||||
|
||||
$consultaUsuarios = $conexion->prepare($sqlUsuarios);
|
||||
$consultaUsuarios->execute($equipos);
|
||||
}
|
||||
|
||||
/*
|
||||
* 4. Eliminamos las relaciones
|
||||
* entre equipos y partida.
|
||||
*/
|
||||
$sqlEquipoxPartida = "DELETE FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaEquipoxPartida = $conexion->prepare($sqlEquipoxPartida);
|
||||
$consultaEquipoxPartida->bindParam(':idPartida', $idPartida,PDO::PARAM_INT);
|
||||
$consultaEquipoxPartida->execute();
|
||||
|
||||
/*
|
||||
* 5. Eliminamos los equipos.
|
||||
*
|
||||
* Los equipos ya no tienen relaciones con
|
||||
* usuarios ni con la partida.
|
||||
*/
|
||||
if (!empty($equipos)) {
|
||||
|
||||
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||
|
||||
$sqlEliminarEquipos = "DELETE FROM equipo WHERE idEquipo IN ($placeholders)";
|
||||
$consultaEliminarEquipos = $conexion->prepare($sqlEliminarEquipos);
|
||||
$consultaEliminarEquipos->execute($equipos);
|
||||
}
|
||||
|
||||
/*
|
||||
* 6. Eliminamos las relaciones
|
||||
* entre preguntas y partida.
|
||||
*/
|
||||
$sqlPartidaxPregunta = "DELETE FROM partidaxpregunta WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaPartidaxPregunta = $conexion->prepare($sqlPartidaxPregunta);
|
||||
$consultaPartidaxPregunta->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaPartidaxPregunta->execute();
|
||||
|
||||
/*
|
||||
* 7. Finalmente eliminamos la partida.
|
||||
*/
|
||||
$sqlPartida = "DELETE FROM partida WHERE idPartida = :idPartida";
|
||||
|
||||
$consultaPartida = $conexion->prepare($sqlPartida);
|
||||
$consultaPartida->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||
$consultaPartida->execute();
|
||||
|
||||
// Todo ha ido correctamente
|
||||
$conexion->commit();
|
||||
|
||||
return [
|
||||
'exito' => true,
|
||||
'salaEliminada' => true,
|
||||
'mensaje' => 'La sala ha sido eliminada correctamente.'
|
||||
];
|
||||
}
|
||||
|
||||
/*
|
||||
* 7. Si NO es el host, simplemente abandona
|
||||
* su relación con el equipo.
|
||||
*/
|
||||
$sqlSalir = "DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario";
|
||||
|
||||
$consultaSalir = $conexion->prepare($sqlSalir);
|
||||
$consultaSalir->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
|
||||
$consultaSalir->execute();
|
||||
|
||||
$conexion->commit();
|
||||
|
||||
return [
|
||||
'exito' => true,
|
||||
'salaEliminada' => false,
|
||||
'mensaje' => 'Has abandonado la sala correctamente.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
// Si había una transacción activa, la deshacemos
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al abandonar la sala.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
require_once __DIR__ . '/ClaseRespuestaAlmacenada.php';
|
||||
require_once __DIR__ . '/claseRespuestaAlmacenada.php';
|
||||
|
||||
/**
|
||||
* Lógica de la dinámica de juego (la usa juego.php a través de ControladorJuego.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
|
||||
@@ -229,7 +229,13 @@ class Juego
|
||||
* - la respuesta pertenece a esa pregunta
|
||||
* - el usuario no ha respondido ya esa pregunta
|
||||
*/
|
||||
public static function registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta)
|
||||
public static function registrarRespuesta(
|
||||
$idPartida,
|
||||
$idUsuario,
|
||||
$idPartidaxPregunta,
|
||||
$idRespuesta,
|
||||
$tiempoRespuesta
|
||||
)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
@@ -298,7 +304,8 @@ class Juego
|
||||
null,
|
||||
$idPartidaxPregunta,
|
||||
$idUsuario,
|
||||
$idRespuesta
|
||||
$idRespuesta,
|
||||
$tiempoRespuesta
|
||||
);
|
||||
$guardado = $almacenada->guardarRespuesta();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
@@ -8,17 +7,27 @@ class Partida
|
||||
public $idPartida;
|
||||
public $nombrePartida;
|
||||
public $idUsuario;
|
||||
public $fechaCreacion;
|
||||
public $fechaInicio;
|
||||
public $fechaFin;
|
||||
|
||||
public function __construct(
|
||||
$idPartida = null,
|
||||
$nombrePartida = null,
|
||||
$idUsuario = null
|
||||
$idUsuario = null,
|
||||
$fechaCreacion = null,
|
||||
$fechaInicio = null,
|
||||
$fechaFin = null
|
||||
) {
|
||||
$this->idPartida = $idPartida;
|
||||
$this->nombrePartida = $nombrePartida;
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->fechaCreacion = $fechaCreacion;
|
||||
$this->fechaInicio = $fechaInicio;
|
||||
$this->fechaFin = $fechaFin;
|
||||
}
|
||||
|
||||
|
||||
public function insertar()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
@@ -26,12 +35,7 @@ class Partida
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
INSERT INTO partida
|
||||
(nombrePartida,idUsuario)
|
||||
VALUES
|
||||
(:nombrePartida,:idUsuario)
|
||||
");
|
||||
$consulta = $conexion->prepare("INSERT INTO partida (nombrePartida,idUsuario) VALUES (:nombrePartida,:idUsuario)");
|
||||
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||
$consulta->execute();
|
||||
@@ -47,8 +51,7 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function listar()
|
||||
{
|
||||
public function listar(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
@@ -65,18 +68,13 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function buscar()
|
||||
{
|
||||
public function buscar(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT *
|
||||
FROM partida
|
||||
WHERE idPartida=:idPartida
|
||||
");
|
||||
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idPartida=:idPartida");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
return $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
@@ -88,20 +86,14 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function editar()
|
||||
{
|
||||
|
||||
public function editar(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
UPDATE partida
|
||||
SET
|
||||
nombrePartida=:nombrePartida,
|
||||
idUsuario=:idUsuario
|
||||
WHERE idPartida=:idPartida
|
||||
");
|
||||
$consulta = $conexion->prepare("UPDATE partida SET nombrePartida=:nombrePartida, idUsuario=:idUsuario WHERE idPartida=:idPartida");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||
@@ -118,17 +110,13 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function eliminar()
|
||||
{
|
||||
public function eliminar(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
DELETE FROM partida
|
||||
WHERE idPartida=:idPartida
|
||||
");
|
||||
$consulta = $conexion->prepare("DELETE FROM partida WHERE idPartida=:idPartida");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
return [
|
||||
@@ -143,48 +131,52 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function iniciar()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
UPDATE partida
|
||||
SET fechaInicio = NOW()
|
||||
WHERE idPartida = :idPartida
|
||||
AND fechaInicio IS NULL
|
||||
");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
return [
|
||||
"exito" => "La partida se inició correctamente.",
|
||||
"exito_tecnico" => $this->idPartida
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "No se pudo iniciar la partida.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
|
||||
public function iniciarPartida()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
public function finalizar()
|
||||
{
|
||||
$consulta = $conexion->prepare("
|
||||
UPDATE partida
|
||||
SET fechaInicio = NOW()
|
||||
WHERE idPartida = :idPartida
|
||||
AND fechaInicio IS NULL
|
||||
");
|
||||
|
||||
$consulta->bindParam(
|
||||
":idPartida",
|
||||
$this->idPartida
|
||||
);
|
||||
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
"exito" => "La partida ha comenzado.",
|
||||
"exito_tecnico" => $this->idPartida
|
||||
];
|
||||
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
"error" => "ERROR REAL: " . $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function finalizar(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
UPDATE partida
|
||||
SET fechaFin = NOW()
|
||||
WHERE idPartida = :idPartida
|
||||
AND fechaInicio IS NOT NULL
|
||||
AND fechaFin IS NULL
|
||||
");
|
||||
$consulta = $conexion->prepare("UPDATE partida SET fechaFin=NOW() WHERE idPartida=:idPartida AND fechaFin IS NULL");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
return [
|
||||
@@ -193,30 +185,83 @@ class Partida
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "No se pudo finalizar la partida.",
|
||||
"error" => "Ocurrió un error al finalizar la partida.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//true si la partida ya tiene fecha de fin (fechaFin no es NULL)
|
||||
//Devuelve false si la partida no existe
|
||||
|
||||
public function estaFinalizada() {
|
||||
$datos = $this->buscar();
|
||||
if (is_array($datos) && isset($datos["error"])) {
|
||||
return $datos;
|
||||
}
|
||||
if (!$datos) {
|
||||
return false;
|
||||
}
|
||||
return $datos["fechaFin"] !== null;
|
||||
}
|
||||
|
||||
public function getPreguntas()
|
||||
{
|
||||
|
||||
//Devuelve la partida más reciente del usuario que aún no ha
|
||||
//terminado (fechaFin NULL), o false si no tiene ninguna.
|
||||
//Incluye también las salas que todavía no han empezado.
|
||||
|
||||
public function partidaEnCursoDeUsuario(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT
|
||||
pxp.idPartidaxPregunta,
|
||||
p.*
|
||||
FROM partidaxpregunta pxp
|
||||
INNER JOIN pregunta p
|
||||
ON pxp.idPregunta=p.idPregunta
|
||||
WHERE pxp.idPartida=:idPartida
|
||||
ORDER BY pxp.idPartidaxPregunta
|
||||
");
|
||||
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idUsuario=:idUsuario AND fechaFin IS NULL ORDER BY idPartida DESC LIMIT 1");
|
||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||
$consulta->execute();
|
||||
return $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "Ocurrió un error al buscar la partida en curso.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function listarSalasAbiertas() {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("SELECT p.idPartida, p.nombrePartida, e.idEquipo, e.nombreEquipo, u.idUsuario, u.nombreUsuario
|
||||
FROM partida p INNER JOIN equipoxpartida exp ON exp.idPartida=p.idPartida INNER JOIN equipo e ON e.idEquipo=exp.idEquipo
|
||||
LEFT JOIN equipoxusuario exu ON exu.idEquipo=e.idEquipo LEFT JOIN usuario u ON u.idUsuario=exu.idUsuario WHERE p.fechaInicio IS NULL
|
||||
AND p.fechaFin IS NULL ORDER BY p.idPartida DESC, e.idEquipo ASC");
|
||||
$consulta->execute();
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "Ocurrió un error al recuperar las salas abiertas.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve las preguntas asignadas a la partida, junto con el
|
||||
* idPartidaxPregunta (necesario para guardar respuestas después).
|
||||
*/
|
||||
public function getPreguntas(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("SELECT pxp.idPartidaxPregunta, p.* FROM partidaxpregunta pxp INNER JOIN pregunta p ON pxp.idPregunta=p.idPregunta
|
||||
WHERE pxp.idPartida=:idPartida ORDER BY pxp.idPartidaxPregunta");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
@@ -228,20 +273,14 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function asignarPregunta($idPregunta)
|
||||
{
|
||||
|
||||
public function asignarPregunta($idPregunta) {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
INSERT INTO partidaxpregunta
|
||||
(idPartida,idPregunta)
|
||||
VALUES
|
||||
(:idPartida,:idPregunta)
|
||||
");
|
||||
$consulta = $conexion->prepare("INSERT INTO partidaxpregunta (idPartida,idPregunta) VALUES (:idPartida,:idPregunta)");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->bindParam(":idPregunta", $idPregunta);
|
||||
$consulta->execute();
|
||||
@@ -257,18 +296,13 @@ class Partida
|
||||
}
|
||||
}
|
||||
//Cuenta cuántas preguntas tiene la partida en total. Es la primera mitad de la comprobación "¿ha terminado el usuario de jugar?".
|
||||
public function contarPreguntasAsignadas()
|
||||
{
|
||||
public function contarPreguntasAsignadas() {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) AS total
|
||||
FROM partidaxpregunta
|
||||
WHERE idPartida=:idPartida
|
||||
");
|
||||
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM partidaxpregunta WHERE idPartida=:idPartida");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
$fila = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
@@ -281,21 +315,14 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function contarRespuestasUsuario($idUsuario)
|
||||
{
|
||||
public function contarRespuestasUsuario($idUsuario){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) AS total
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON ra.idPartidaxPregunta=pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida=:idPartida
|
||||
AND ra.idUsuario=:idUsuario
|
||||
");
|
||||
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM respuestaalmacenada ra INNER JOIN partidaxpregunta pxp
|
||||
ON ra.idPartidaxPregunta=pxp.idPartidaxPregunta WHERE pxp.idPartida=:idPartida AND ra.idUsuario=:idUsuario");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->bindParam(":idUsuario", $idUsuario);
|
||||
$consulta->execute();
|
||||
@@ -310,11 +337,11 @@ class Partida
|
||||
}
|
||||
|
||||
/**
|
||||
* Sustituye al antiguo campo `terminada`: compara cuántas preguntas
|
||||
* tiene la partida contra cuántas ha respondido este usuario.
|
||||
* Indica si ESTE usuario ya ha respondido todas las preguntas:
|
||||
* compara cuántas preguntas tiene la partida contra cuántas ha
|
||||
* respondido él. (La partida completa se marca con finalizar().)
|
||||
*/
|
||||
public function estaFinalizadaParaUsuario($idUsuario)
|
||||
{
|
||||
public function estaFinalizadaParaUsuario($idUsuario){
|
||||
$totalPreguntas = $this->contarPreguntasAsignadas();
|
||||
if (is_array($totalPreguntas)) {
|
||||
return $totalPreguntas;
|
||||
@@ -329,19 +356,13 @@ class Partida
|
||||
/**
|
||||
* Partidas creadas por un usuario, de más reciente a más antigua.
|
||||
*/
|
||||
public function listarDelUsuario()
|
||||
{
|
||||
public function listarDelUsuario(){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT *
|
||||
FROM partida
|
||||
WHERE idUsuario=:idUsuario
|
||||
ORDER BY idPartida DESC
|
||||
");
|
||||
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idUsuario=:idUsuario ORDER BY idPartida DESC");
|
||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||
$consulta->execute();
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
@@ -353,22 +374,13 @@ class Partida
|
||||
}
|
||||
}
|
||||
|
||||
public function preguntaAsignada($idPregunta)
|
||||
{
|
||||
public function preguntaAsignada($idPregunta) {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) AS total
|
||||
FROM partidaxpregunta
|
||||
WHERE idPartida=:idPartida
|
||||
AND idPregunta=:idPregunta
|
||||
");
|
||||
|
||||
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM partidaxpregunta WHERE idPartida=:idPartida AND idPregunta=:idPregunta");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->bindParam(":idPregunta", $idPregunta);
|
||||
$consulta->execute();
|
||||
@@ -388,24 +400,13 @@ class Partida
|
||||
* Vincula un equipo a esta partida en la tabla intermedia 'equipoxpartida'.
|
||||
* Permite registrar qué grupos están participando en este torneo.
|
||||
*/
|
||||
public function registrarEquipoEnPartida($idEquipo)
|
||||
{
|
||||
$conexion = conexionBD(); // Obtenemos la conexión modular del proyecto
|
||||
|
||||
public function registrarEquipoEnPartida($idEquipo){
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion; // Si hay error en la conexión, lo devuelve
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
// Preparamos la consulta para insertar la relación en la tabla intermedia real
|
||||
$consulta = $conexion->prepare("
|
||||
INSERT INTO equipoxpartida
|
||||
(idPartida, idEquipo)
|
||||
VALUES
|
||||
(:idPartida, :idEquipo)
|
||||
");
|
||||
|
||||
// Vinculamos los parámetros con el objeto de la partida actual y el equipo recibido
|
||||
$consulta = $conexion->prepare("INSERT INTO equipoxpartida (idPartida, idEquipo) VALUES (:idPartida, :idEquipo)");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->bindParam(":idEquipo", $idEquipo);
|
||||
$consulta->execute();
|
||||
@@ -415,7 +416,6 @@ class Partida
|
||||
"exito_tecnico" => $conexion->lastInsertId()
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
// Capturamos el error extrayendo solo el mensaje de texto limpio
|
||||
return [
|
||||
"error" => "Ocurrió un error al asignar el equipo a la partida.",
|
||||
"error_tecnico" => $error->getMessage()
|
||||
@@ -427,28 +427,14 @@ class Partida
|
||||
* Obtiene todos los equipos que están compitiendo en esta partida.
|
||||
* Es útil para mostrar la lista de rivales antes de empezar a responder.
|
||||
*/
|
||||
public function getEquiposParticipantes()
|
||||
{
|
||||
public function getEquiposParticipantes(){
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
// Hacemos un INNER JOIN para traer los nombres de los equipos desde la tabla intermedia
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT
|
||||
exp.idEquipoxPartida,
|
||||
e.idEquipo,
|
||||
e.nombreEquipo
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipo e
|
||||
ON exp.idEquipo = e.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
ORDER BY e.nombreEquipo ASC
|
||||
");
|
||||
|
||||
try {
|
||||
$consulta = $conexion->prepare("SELECT exp.idEquipoxPartida, e.idEquipo, e.nombreEquipo FROM equipoxpartida exp
|
||||
INNER JOIN equipo e ON exp.idEquipo = e.idEquipo WHERE exp.idPartida = :idPartida ORDER BY e.nombreEquipo ASC");
|
||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||
$consulta->execute();
|
||||
|
||||
@@ -465,78 +451,29 @@ class Partida
|
||||
* Obtiene todos los jugadores reales (Usuarios) que están jugando en esta partida.
|
||||
* Utiliza la tabla 'equipoxusuario' en SQL para cruzar los datos.
|
||||
*/
|
||||
public function getJugadoresDeLaPartida()
|
||||
{
|
||||
public function getJugadoresDeLaPartida(){
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT DISTINCT
|
||||
u.idUsuario,
|
||||
u.nombreUsuario,
|
||||
u.email,
|
||||
e.idEquipo,
|
||||
e.nombreEquipo
|
||||
FROM equipoxpartida exp
|
||||
|
||||
INNER JOIN equipoxusuario exu
|
||||
ON exp.idEquipo = exu.idEquipo
|
||||
|
||||
INNER JOIN usuario u
|
||||
ON exu.idUsuario = u.idUsuario
|
||||
|
||||
INNER JOIN equipo e
|
||||
ON exu.idEquipo = e.idEquipo
|
||||
|
||||
WHERE exp.idPartida = :idPartida
|
||||
|
||||
ORDER BY e.nombreEquipo ASC,
|
||||
u.nombreUsuario ASC
|
||||
");
|
||||
|
||||
$consulta = $conexion->prepare("SELECT DISTINCT u.idUsuario, u.nombreUsuario, u.email, e.idEquipo, e.nombreEquipo
|
||||
FROM equipoxpartida exp INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo INNER JOIN usuario u
|
||||
ON exu.idUsuario = u.idUsuario INNER JOIN equipo e ON exu.idEquipo = e.idEquipo WHERE exp.idPartida = :idPartida
|
||||
ORDER BY e.nombreEquipo ASC, u.nombreUsuario ASC");
|
||||
$consulta->bindParam(
|
||||
":idPartida",
|
||||
$this->idPartida
|
||||
);
|
||||
|
||||
$consulta->execute();
|
||||
|
||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
"error" =>
|
||||
"Ocurrió un error al obtener la lista de jugadores.",
|
||||
|
||||
"error_tecnico" =>
|
||||
$error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function contar()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$sql="SELECT COUNT(*) AS total FROM partida";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->execute();
|
||||
return (int) $consulta->fetchColumn();
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "Ocurrió un error al obtener el listado.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,132 +1,132 @@
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
|
||||
class Pregunta {
|
||||
private ?int $idPregunta;
|
||||
private int $idCategoria;
|
||||
private string $nombrePregunta;
|
||||
private array $respuestas;
|
||||
|
||||
public function __construct(int $idCategoria = 0, string $nombrePregunta = "", ?int $idPregunta = null) {
|
||||
$this->idPregunta = $idPregunta;
|
||||
$this->idCategoria = $idCategoria;
|
||||
$this->nombrePregunta = $nombrePregunta;
|
||||
$this->respuestas = [];
|
||||
}
|
||||
|
||||
public function getIdPregunta(): ?int { return $this->idPregunta; }
|
||||
|
||||
public function getIdCategoria(): int { return $this->idCategoria; }
|
||||
public function setIdCategoria(int $idCategoria): void { $this->idCategoria = $idCategoria; }
|
||||
|
||||
public function getNombrePregunta(): string { return $this->nombrePregunta; }
|
||||
public function setNombrePregunta(string $nombrePregunta): void { $this->nombrePregunta = $nombrePregunta; }
|
||||
|
||||
public function getRespuestas(): array { return $this->respuestas; }
|
||||
|
||||
public function guardar() {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO pregunta (idCategoria, nombrePregunta) VALUES (:idCat, :texto)";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':idCat' => $this->idCategoria,
|
||||
':texto' => $this->nombrePregunta
|
||||
]);
|
||||
|
||||
$this->idPregunta = (int)$conexion->lastInsertId();
|
||||
|
||||
return [
|
||||
'exito' => 'Pregunta guardada correctamente',
|
||||
'exito_tecnico' => $this->idPregunta
|
||||
];
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la pregunta.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function cargarRespuestas() {
|
||||
if ($this->idPregunta === null) return;
|
||||
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT idRespuesta, nombreRespuesta, correcta FROM respuesta WHERE idPregunta = :idPreg";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':idPreg' => $this->idPregunta]);
|
||||
|
||||
$this->respuestas = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al cargar las respuestas.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function obtenerPorCategoria(int $idCategoria, int $limite = 10) {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM pregunta WHERE idCategoria = :idCat ORDER BY RAND() LIMIT :limite";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->bindValue(':idCat', $idCategoria, PDO::PARAM_INT);
|
||||
$stmt->bindValue(':limite', $limite, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$preguntas = [];
|
||||
while ($datos = $stmt->fetch(PDO::FETCH_ASSOC)) {
|
||||
$preg = new Pregunta((int)$datos['idCategoria'], $datos['nombrePregunta'], (int)$datos['idPregunta']);
|
||||
$preg->cargarRespuestas();
|
||||
$preguntas[] = $preg;
|
||||
}
|
||||
return $preguntas;
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener las preguntas aleatorias.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function getTodosIds()//devuelve solamente los id de todas las preguntas
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("SELECT idPregunta FROM pregunta");
|
||||
$consulta->execute();
|
||||
return $consulta->fetchAll(PDO::FETCH_COLUMN);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "Ocurrió un error al obtener el listado.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
|
||||
class Pregunta {
|
||||
private ?int $idPregunta;
|
||||
private int $idCategoria;
|
||||
private string $nombrePregunta;
|
||||
private array $respuestas;
|
||||
|
||||
public function __construct(int $idCategoria = 0, string $nombrePregunta = "", ?int $idPregunta = null) {
|
||||
$this->idPregunta = $idPregunta;
|
||||
$this->idCategoria = $idCategoria;
|
||||
$this->nombrePregunta = $nombrePregunta;
|
||||
$this->respuestas = [];
|
||||
}
|
||||
|
||||
public function getIdPregunta(): ?int { return $this->idPregunta; }
|
||||
|
||||
public function getIdCategoria(): int { return $this->idCategoria; }
|
||||
public function setIdCategoria(int $idCategoria): void { $this->idCategoria = $idCategoria; }
|
||||
|
||||
public function getNombrePregunta(): string { return $this->nombrePregunta; }
|
||||
public function setNombrePregunta(string $nombrePregunta): void { $this->nombrePregunta = $nombrePregunta; }
|
||||
|
||||
public function getRespuestas(): array { return $this->respuestas; }
|
||||
|
||||
public function guardar() {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO pregunta (idCategoria, nombrePregunta) VALUES (:idCat, :texto)";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':idCat' => $this->idCategoria,
|
||||
':texto' => $this->nombrePregunta
|
||||
]);
|
||||
|
||||
$this->idPregunta = (int)$conexion->lastInsertId();
|
||||
|
||||
return [
|
||||
'exito' => 'Pregunta guardada correctamente',
|
||||
'exito_tecnico' => $this->idPregunta
|
||||
];
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la pregunta.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function cargarRespuestas() {
|
||||
if ($this->idPregunta === null) return;
|
||||
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT idRespuesta, nombreRespuesta, correcta FROM respuesta WHERE idPregunta = :idPreg";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':idPreg' => $this->idPregunta]);
|
||||
|
||||
$this->respuestas = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al cargar las respuestas.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function obtenerPorCategoria(int $idCategoria, int $limite = 10) {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM pregunta WHERE idCategoria = :idCat ORDER BY RAND() LIMIT :limite";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->bindValue(':idCat', $idCategoria, PDO::PARAM_INT);
|
||||
$stmt->bindValue(':limite', $limite, PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
|
||||
$preguntas = [];
|
||||
while ($datos = $stmt->fetch(PDO::FETCH_ASSOC)) {
|
||||
$preg = new Pregunta((int)$datos['idCategoria'], $datos['nombrePregunta'], (int)$datos['idPregunta']);
|
||||
$preg->cargarRespuestas();
|
||||
$preguntas[] = $preg;
|
||||
}
|
||||
return $preguntas;
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al obtener las preguntas aleatorias.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function getTodosIds()//devuelve solamente los id de todas las preguntas
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
try {
|
||||
$consulta = $conexion->prepare("SELECT idPregunta FROM pregunta");
|
||||
$consulta->execute();
|
||||
return $consulta->fetchAll(PDO::FETCH_COLUMN);
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
"error" => "Ocurrió un error al obtener el listado.",
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ class Respuesta{
|
||||
$consulta->bindParam(':idPregunta', $this->idPregunta);
|
||||
$consulta->bindParam(':nombreRespuesta', $this->nombreRespuesta);
|
||||
$consulta->bindParam(':correcta', $this->correcta);
|
||||
|
||||
|
||||
$consulta->execute();
|
||||
$respuesta = [
|
||||
'exito' => 'La respuesta se guardó correctamente.',
|
||||
@@ -1,76 +1,86 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
// Clase encargada de registrar las respuestas de los jugadores en tiempo real durante la partida
|
||||
class RespuestaAlmacenada {
|
||||
public $idRespuestaAlmacenada;
|
||||
public $idPartidaxPregunta;
|
||||
public $idUsuario;
|
||||
public $idRespuesta;
|
||||
|
||||
public function __construct($idRespuestaAlmacenada = null, $idPartidaxPregunta = null, $idUsuario = null, $idRespuesta = null) {
|
||||
$this->idRespuestaAlmacenada = $idRespuestaAlmacenada;
|
||||
$this->idPartidaxPregunta = $idPartidaxPregunta;
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->idRespuesta = $idRespuesta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda la respuesta que ha seleccionado un usuario en una pregunta de la partida.
|
||||
*/
|
||||
public function guardarRespuesta() {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO respuestaalmacenada (idPartidaxPregunta, idUsuario, idRespuesta)
|
||||
VALUES (:idPartidaxPregunta, :idUsuario, :idRespuesta)";
|
||||
$consulta = $conexion->prepare($sql);
|
||||
|
||||
$consulta->bindParam(':idPartidaxPregunta', $this->idPartidaxPregunta);
|
||||
$consulta->bindParam(':idUsuario', $this->idUsuario);
|
||||
$consulta->bindParam(':idRespuesta', $this->idRespuesta);
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
'exito' => 'Respuesta del usuario almacenada correctamente.',
|
||||
'exito_tecnico' => $conexion->lastInsertId()
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la respuesta del jugador.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene los aciertos totales de un usuario en una partida específica.
|
||||
* Útil para calcular las estadísticas individuales al terminar el juego.
|
||||
*/
|
||||
public static function obtenerAciertosUsuarioEnPartida($idPartida, $idUsuario) {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "SELECT COUNT(*) AS aciertos
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario AND r.correcta = 1";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idPartida', $idPartida);
|
||||
$consulta->bindParam(':idUsuario', $idUsuario);
|
||||
$consulta->execute();
|
||||
|
||||
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
return (int)$resultado['aciertos'];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al calcular los aciertos.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
// clase encargada de registrar las respuestas de los jugadores en tiempo real durante la partida
|
||||
class RespuestaAlmacenada {
|
||||
public $idRespuestaAlmacenada;
|
||||
public $idPartidaxPregunta;
|
||||
public $idUsuario;
|
||||
public $idRespuesta;
|
||||
public $tiempoRespuesta;
|
||||
|
||||
public function __construct($idRespuestaAlmacenada = null, $idPartidaxPregunta = null, $idUsuario = null, $idRespuesta = null, $tiempoRespuesta = null) {
|
||||
$this->idRespuestaAlmacenada = $idRespuestaAlmacenada;
|
||||
$this->idPartidaxPregunta = $idPartidaxPregunta;
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->idRespuesta = $idRespuesta;
|
||||
$this->tiempoRespuesta = $tiempoRespuesta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda la respuesta que ha seleccionado un usuario en una pregunta de la partida.
|
||||
*/
|
||||
public function guardarRespuesta() {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO respuestaalmacenada
|
||||
(idPartidaxPregunta, idUsuario, idRespuesta, tiempoRespuesta)
|
||||
VALUES
|
||||
(:idPartidaxPregunta, :idUsuario, :idRespuesta, :tiempoRespuesta)";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
|
||||
$consulta->bindParam(':idPartidaxPregunta', $this->idPartidaxPregunta);
|
||||
$consulta->bindParam(':idUsuario', $this->idUsuario);
|
||||
$consulta->bindParam(':idRespuesta', $this->idRespuesta);
|
||||
$consulta->bindParam(':tiempoRespuesta', $this->tiempoRespuesta);
|
||||
|
||||
$consulta->execute();
|
||||
|
||||
return [
|
||||
'exito' => 'Respuesta almacenada correctamente.'
|
||||
];
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la respuesta.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene los aciertos totales de un usuario en una partida específica.
|
||||
* Útil para calcular las estadísticas individuales al terminar el juego.
|
||||
*/
|
||||
public static function obtenerAciertosUsuarioEnPartida($idPartida, $idUsuario) {
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return $conexion;
|
||||
|
||||
try {
|
||||
$sql = "SELECT COUNT(*) AS aciertos
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario AND r.correcta = 1";
|
||||
|
||||
$consulta = $conexion->prepare($sql);
|
||||
$consulta->bindParam(':idPartida', $idPartida);
|
||||
$consulta->bindParam(':idUsuario', $idUsuario);
|
||||
$consulta->execute();
|
||||
|
||||
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||
return (int)$resultado['aciertos'];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al calcular los aciertos.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,474 +1,474 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
class Usuario
|
||||
{
|
||||
private ?int $idUsuario;
|
||||
private string $nombreUsuario;
|
||||
private string $contrasena;
|
||||
private string $email;
|
||||
private ?string $avatar;
|
||||
private ?string $cookie;
|
||||
private int $aciertos;
|
||||
private int $victorias;
|
||||
private int $derrotas;
|
||||
|
||||
public function __construct(
|
||||
string $nombreUsuario = "",
|
||||
string $contrasena = "",
|
||||
string $email = "",
|
||||
?string $avatar = null,
|
||||
?string $cookie = null,
|
||||
int $aciertos = 0,
|
||||
int $victorias = 0,
|
||||
int $derrotas = 0,
|
||||
?int $idUsuario = null
|
||||
) {
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->nombreUsuario = $nombreUsuario;
|
||||
$this->contrasena = $contrasena;
|
||||
$this->email = $email;
|
||||
$this->avatar = $avatar;
|
||||
$this->cookie = $cookie;
|
||||
$this->aciertos = $aciertos;
|
||||
$this->victorias = $victorias;
|
||||
$this->derrotas = $derrotas;
|
||||
}
|
||||
|
||||
public function getIdUsuario(): ?int
|
||||
{
|
||||
return $this->idUsuario;
|
||||
}
|
||||
|
||||
public function getNombreUsuario(): string
|
||||
{
|
||||
return $this->nombreUsuario;
|
||||
}
|
||||
public function setNombreUsuario(string $nombreUsuario): void
|
||||
{
|
||||
$this->nombreUsuario = $nombreUsuario;
|
||||
}
|
||||
|
||||
public function getContrasena(): string
|
||||
{
|
||||
return $this->contrasena;
|
||||
}
|
||||
public function setContrasena(string $contrasena): void
|
||||
{
|
||||
$this->contrasena = $contrasena;
|
||||
}
|
||||
|
||||
public function getEmail(): string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
public function setEmail(string $email): void
|
||||
{
|
||||
$this->email = $email;
|
||||
}
|
||||
|
||||
public function getAvatar(): ?string
|
||||
{
|
||||
return $this->avatar;
|
||||
}
|
||||
public function setAvatar(?string $avatar): void
|
||||
{
|
||||
$this->avatar = $avatar;
|
||||
}
|
||||
|
||||
public function getCookie(): ?string
|
||||
{
|
||||
return $this->cookie;
|
||||
}
|
||||
public function setCookie(?string $cookie): void
|
||||
{
|
||||
$this->cookie = $cookie;
|
||||
}
|
||||
|
||||
public function getAciertos(): int
|
||||
{
|
||||
return $this->aciertos;
|
||||
}
|
||||
public function setAciertos(int $aciertos): void
|
||||
{
|
||||
$this->aciertos = $aciertos;
|
||||
}
|
||||
|
||||
public function getVictorias(): int
|
||||
{
|
||||
return $this->victorias;
|
||||
}
|
||||
public function setVictorias(int $victorias): void
|
||||
{
|
||||
$this->victorias = $victorias;
|
||||
}
|
||||
|
||||
public function getDerrotas(): int
|
||||
{
|
||||
return $this->derrotas;
|
||||
}
|
||||
public function setDerrotas(int $derrotas): void
|
||||
{
|
||||
$this->derrotas = $derrotas;
|
||||
}
|
||||
|
||||
public function registrar()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO usuario (nombreUsuario, contrasena, email, avatar, cookie, aciertos, victorias, derrotas)
|
||||
VALUES (:nombre, :pass, :email, :avatar, :cookie, :aciertos, :victorias, :derrotas)";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$passHash = password_hash($this->contrasena, PASSWORD_BCRYPT);
|
||||
|
||||
$stmt->execute([
|
||||
':nombre' => $this->nombreUsuario,
|
||||
':pass' => $passHash,
|
||||
':email' => $this->email,
|
||||
':avatar' => $this->avatar,
|
||||
':cookie' => $this->cookie,
|
||||
':aciertos' => $this->aciertos,
|
||||
':victorias' => $this->victorias,
|
||||
':derrotas' => $this->derrotas
|
||||
]);
|
||||
|
||||
$this->idUsuario = (int)$conexion->lastInsertId();
|
||||
|
||||
return [
|
||||
'exito' => 'Usuario registrado correctamente',
|
||||
'exito_tecnico' => $this->idUsuario
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al registrar el usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorId($id)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE idUsuario = :id";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':id' => $id]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'error' => 'No se encontró ningún usuario con ese ID.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al buscar el usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorEmail($email)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE email = :email";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':email' => $email]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
|
||||
return null; // No existe usuario con ese email
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al buscar el usuario por email.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function login($email, $contrasena)
|
||||
{
|
||||
$usuario = self::buscarPorEmail($email);
|
||||
|
||||
// El usuario no existe
|
||||
if (!($usuario instanceof Usuario)) {
|
||||
|
||||
// Limpiamos posibles datos de sesión anteriores
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Comprobamos la contraseña
|
||||
if (password_verify($contrasena, $usuario->getContrasena())) {
|
||||
|
||||
// Usuario validado correctamente
|
||||
$_SESSION['idUsuario'] = $usuario->getIdUsuario();
|
||||
$_SESSION['email'] = $usuario->getEmail();
|
||||
$_SESSION['nombreUsuario'] = $usuario->getNombreUsuario();
|
||||
$_SESSION['avatar'] = $usuario->getAvatar();
|
||||
|
||||
// Devolvemos el usuario como hasta ahora
|
||||
return $usuario;
|
||||
}
|
||||
|
||||
// Contraseña incorrecta
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cookies
|
||||
|
||||
public static function guardarCookieToken($idUsuario, $token)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return false;
|
||||
|
||||
try {
|
||||
$sql = "UPDATE usuario SET cookie = :token WHERE idUsuario = :id";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
return $stmt->execute([
|
||||
':token' => $token,
|
||||
':id' => $idUsuario
|
||||
]);
|
||||
} catch (PDOException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorCookie($token)
|
||||
{
|
||||
if (empty($token)) return null;
|
||||
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return null;
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE cookie = :token AND cookie IS NOT NULL";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':token' => $token]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
return null;
|
||||
} catch (PDOException $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function cambiarNombre($nuevoNombre)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "UPDATE usuario
|
||||
SET nombreUsuario = :nombre
|
||||
WHERE idUsuario = :id";
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':nombre' => $nuevoNombre,
|
||||
':id' => $this->idUsuario
|
||||
]);
|
||||
|
||||
// Actualizamos también el objeto actual
|
||||
$this->nombreUsuario = $nuevoNombre;
|
||||
|
||||
return [
|
||||
'exito' => 'Nombre actualizado correctamente.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al actualizar el nombre.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function cambiarAvatar($archivo)
|
||||
{
|
||||
$carpeta = __DIR__ . '/../img/avatars/';
|
||||
|
||||
// Creamos la carpeta si no existe
|
||||
if (!is_dir($carpeta)) {
|
||||
mkdir($carpeta, 0755, true);
|
||||
}
|
||||
|
||||
// Obtenemos la extensión según el tipo MIME
|
||||
$tipo = mime_content_type($archivo['tmp_name']);
|
||||
|
||||
$extensiones = [
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/png' => 'png',
|
||||
'image/gif' => 'gif',
|
||||
'image/webp' => 'webp'
|
||||
];
|
||||
|
||||
if (!isset($extensiones[$tipo])) {
|
||||
|
||||
return [
|
||||
'error' => 'Formato de imagen no permitido.'
|
||||
];
|
||||
}
|
||||
|
||||
$extension = $extensiones[$tipo];
|
||||
|
||||
// Nombre único para evitar conflictos
|
||||
$nombreArchivo = 'avatar_' . $this->idUsuario . '.' . $extension;
|
||||
|
||||
$rutaCompleta = $carpeta . $nombreArchivo;
|
||||
|
||||
// Guardamos la imagen
|
||||
if (!move_uploaded_file($archivo['tmp_name'], $rutaCompleta)) {
|
||||
|
||||
return [
|
||||
'error' => 'No se pudo guardar la imagen.'
|
||||
];
|
||||
}
|
||||
|
||||
// Ruta que utilizará el HTML
|
||||
$rutaAvatar = 'img/avatars/' . $nombreArchivo;
|
||||
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "UPDATE usuario
|
||||
SET avatar = :avatar
|
||||
WHERE idUsuario = :id";
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':avatar' => $rutaAvatar,
|
||||
':id' => $this->idUsuario
|
||||
]);
|
||||
|
||||
// Actualizamos también el objeto actual
|
||||
$this->avatar = $rutaAvatar;
|
||||
|
||||
return [
|
||||
'exito' => 'Avatar actualizado correctamente.',
|
||||
'avatar' => $rutaAvatar
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al actualizar el avatar.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function obtenerRanking($limite = 10)
|
||||
{
|
||||
try {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
$sql = "SELECT
|
||||
idUsuario,
|
||||
nombreUsuario,
|
||||
avatar,
|
||||
aciertos,
|
||||
victorias,
|
||||
derrotas,
|
||||
CASE
|
||||
WHEN (victorias + derrotas) > 0
|
||||
THEN ROUND((victorias / (victorias + derrotas)) * 100, 0)
|
||||
ELSE 0
|
||||
END AS porcentajeVictoria
|
||||
FROM usuario
|
||||
ORDER BY victorias DESC, aciertos DESC
|
||||
LIMIT " . (int)$limite;
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute();
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
class Usuario
|
||||
{
|
||||
private ?int $idUsuario;
|
||||
private string $nombreUsuario;
|
||||
private string $contrasena;
|
||||
private string $email;
|
||||
private ?string $avatar;
|
||||
private ?string $cookie;
|
||||
private int $aciertos;
|
||||
private int $victorias;
|
||||
private int $derrotas;
|
||||
|
||||
public function __construct(
|
||||
string $nombreUsuario = "",
|
||||
string $contrasena = "",
|
||||
string $email = "",
|
||||
?string $avatar = null,
|
||||
?string $cookie = null,
|
||||
int $aciertos = 0,
|
||||
int $victorias = 0,
|
||||
int $derrotas = 0,
|
||||
?int $idUsuario = null
|
||||
) {
|
||||
$this->idUsuario = $idUsuario;
|
||||
$this->nombreUsuario = $nombreUsuario;
|
||||
$this->contrasena = $contrasena;
|
||||
$this->email = $email;
|
||||
$this->avatar = $avatar;
|
||||
$this->cookie = $cookie;
|
||||
$this->aciertos = $aciertos;
|
||||
$this->victorias = $victorias;
|
||||
$this->derrotas = $derrotas;
|
||||
}
|
||||
|
||||
public function getIdUsuario(): ?int
|
||||
{
|
||||
return $this->idUsuario;
|
||||
}
|
||||
|
||||
public function getNombreUsuario(): string
|
||||
{
|
||||
return $this->nombreUsuario;
|
||||
}
|
||||
public function setNombreUsuario(string $nombreUsuario): void
|
||||
{
|
||||
$this->nombreUsuario = $nombreUsuario;
|
||||
}
|
||||
|
||||
public function getContrasena(): string
|
||||
{
|
||||
return $this->contrasena;
|
||||
}
|
||||
public function setContrasena(string $contrasena): void
|
||||
{
|
||||
$this->contrasena = $contrasena;
|
||||
}
|
||||
|
||||
public function getEmail(): string
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
public function setEmail(string $email): void
|
||||
{
|
||||
$this->email = $email;
|
||||
}
|
||||
|
||||
public function getAvatar(): ?string
|
||||
{
|
||||
return $this->avatar;
|
||||
}
|
||||
public function setAvatar(?string $avatar): void
|
||||
{
|
||||
$this->avatar = $avatar;
|
||||
}
|
||||
|
||||
public function getCookie(): ?string
|
||||
{
|
||||
return $this->cookie;
|
||||
}
|
||||
public function setCookie(?string $cookie): void
|
||||
{
|
||||
$this->cookie = $cookie;
|
||||
}
|
||||
|
||||
public function getAciertos(): int
|
||||
{
|
||||
return $this->aciertos;
|
||||
}
|
||||
public function setAciertos(int $aciertos): void
|
||||
{
|
||||
$this->aciertos = $aciertos;
|
||||
}
|
||||
|
||||
public function getVictorias(): int
|
||||
{
|
||||
return $this->victorias;
|
||||
}
|
||||
public function setVictorias(int $victorias): void
|
||||
{
|
||||
$this->victorias = $victorias;
|
||||
}
|
||||
|
||||
public function getDerrotas(): int
|
||||
{
|
||||
return $this->derrotas;
|
||||
}
|
||||
public function setDerrotas(int $derrotas): void
|
||||
{
|
||||
$this->derrotas = $derrotas;
|
||||
}
|
||||
|
||||
public function registrar()
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "INSERT INTO usuario (nombreUsuario, contrasena, email, avatar, cookie, aciertos, victorias, derrotas)
|
||||
VALUES (:nombre, :pass, :email, :avatar, :cookie, :aciertos, :victorias, :derrotas)";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$passHash = password_hash($this->contrasena, PASSWORD_BCRYPT);
|
||||
|
||||
$stmt->execute([
|
||||
':nombre' => $this->nombreUsuario,
|
||||
':pass' => $passHash,
|
||||
':email' => $this->email,
|
||||
':avatar' => $this->avatar,
|
||||
':cookie' => $this->cookie,
|
||||
':aciertos' => $this->aciertos,
|
||||
':victorias' => $this->victorias,
|
||||
':derrotas' => $this->derrotas
|
||||
]);
|
||||
|
||||
$this->idUsuario = (int)$conexion->lastInsertId();
|
||||
|
||||
return [
|
||||
'exito' => 'Usuario registrado correctamente',
|
||||
'exito_tecnico' => $this->idUsuario
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al registrar el usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorId($id)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE idUsuario = :id";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':id' => $id]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
'error' => 'No se encontró ningún usuario con ese ID.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al buscar el usuario.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorEmail($email)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE email = :email";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':email' => $email]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
|
||||
return null; // No existe usuario con ese email
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al buscar el usuario por email.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function login($email, $contrasena)
|
||||
{
|
||||
$usuario = self::buscarPorEmail($email);
|
||||
|
||||
// El usuario no existe
|
||||
if (!($usuario instanceof Usuario)) {
|
||||
|
||||
// Limpiamos posibles datos de sesión anteriores
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Comprobamos la contraseña
|
||||
if (password_verify($contrasena, $usuario->getContrasena())) {
|
||||
|
||||
// Usuario validado correctamente
|
||||
$_SESSION['idUsuario'] = $usuario->getIdUsuario();
|
||||
$_SESSION['email'] = $usuario->getEmail();
|
||||
$_SESSION['nombreUsuario'] = $usuario->getNombreUsuario();
|
||||
$_SESSION['avatar'] = $usuario->getAvatar();
|
||||
|
||||
// Devolvemos el usuario como hasta ahora
|
||||
return $usuario;
|
||||
}
|
||||
|
||||
// Contraseña incorrecta
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Cookies
|
||||
|
||||
public static function guardarCookieToken($idUsuario, $token)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return false;
|
||||
|
||||
try {
|
||||
$sql = "UPDATE usuario SET cookie = :token WHERE idUsuario = :id";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
return $stmt->execute([
|
||||
':token' => $token,
|
||||
':id' => $idUsuario
|
||||
]);
|
||||
} catch (PDOException $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static function buscarPorCookie($token)
|
||||
{
|
||||
if (empty($token)) return null;
|
||||
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) return null;
|
||||
|
||||
try {
|
||||
$sql = "SELECT * FROM usuario WHERE cookie = :token AND cookie IS NOT NULL";
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute([':token' => $token]);
|
||||
|
||||
$datos = $stmt->fetch(PDO::FETCH_ASSOC);
|
||||
|
||||
if ($datos) {
|
||||
return new Usuario(
|
||||
$datos['nombreUsuario'],
|
||||
$datos['contrasena'],
|
||||
$datos['email'],
|
||||
$datos['avatar'],
|
||||
$datos['cookie'],
|
||||
(int)$datos['aciertos'],
|
||||
(int)$datos['victorias'],
|
||||
(int)$datos['derrotas'],
|
||||
(int)$datos['idUsuario']
|
||||
);
|
||||
}
|
||||
return null;
|
||||
} catch (PDOException $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public function cambiarNombre($nuevoNombre)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "UPDATE usuario
|
||||
SET nombreUsuario = :nombre
|
||||
WHERE idUsuario = :id";
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':nombre' => $nuevoNombre,
|
||||
':id' => $this->idUsuario
|
||||
]);
|
||||
|
||||
// Actualizamos también el objeto actual
|
||||
$this->nombreUsuario = $nuevoNombre;
|
||||
|
||||
return [
|
||||
'exito' => 'Nombre actualizado correctamente.'
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al actualizar el nombre.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function cambiarAvatar($archivo)
|
||||
{
|
||||
$carpeta = __DIR__ . '/../img/avatars/';
|
||||
|
||||
// Creamos la carpeta si no existe
|
||||
if (!is_dir($carpeta)) {
|
||||
mkdir($carpeta, 0755, true);
|
||||
}
|
||||
|
||||
// Obtenemos la extensión según el tipo MIME
|
||||
$tipo = mime_content_type($archivo['tmp_name']);
|
||||
|
||||
$extensiones = [
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/png' => 'png',
|
||||
'image/gif' => 'gif',
|
||||
'image/webp' => 'webp'
|
||||
];
|
||||
|
||||
if (!isset($extensiones[$tipo])) {
|
||||
|
||||
return [
|
||||
'error' => 'Formato de imagen no permitido.'
|
||||
];
|
||||
}
|
||||
|
||||
$extension = $extensiones[$tipo];
|
||||
|
||||
// Nombre único para evitar conflictos
|
||||
$nombreArchivo = 'avatar_' . $this->idUsuario . '.' . $extension;
|
||||
|
||||
$rutaCompleta = $carpeta . $nombreArchivo;
|
||||
|
||||
// Guardamos la imagen
|
||||
if (!move_uploaded_file($archivo['tmp_name'], $rutaCompleta)) {
|
||||
|
||||
return [
|
||||
'error' => 'No se pudo guardar la imagen.'
|
||||
];
|
||||
}
|
||||
|
||||
// Ruta que utilizará el HTML
|
||||
$rutaAvatar = 'img/avatars/' . $nombreArchivo;
|
||||
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
$sql = "UPDATE usuario
|
||||
SET avatar = :avatar
|
||||
WHERE idUsuario = :id";
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
|
||||
$stmt->execute([
|
||||
':avatar' => $rutaAvatar,
|
||||
':id' => $this->idUsuario
|
||||
]);
|
||||
|
||||
// Actualizamos también el objeto actual
|
||||
$this->avatar = $rutaAvatar;
|
||||
|
||||
return [
|
||||
'exito' => 'Avatar actualizado correctamente.',
|
||||
'avatar' => $rutaAvatar
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
'error' => 'Ocurrió un error al actualizar el avatar.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public static function obtenerRanking($limite = 10)
|
||||
{
|
||||
try {
|
||||
$conexion = conexionBD();
|
||||
|
||||
if (is_array($conexion)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
$sql = "SELECT
|
||||
idUsuario,
|
||||
nombreUsuario,
|
||||
avatar,
|
||||
aciertos,
|
||||
victorias,
|
||||
derrotas,
|
||||
CASE
|
||||
WHEN (victorias + derrotas) > 0
|
||||
THEN ROUND((victorias / (victorias + derrotas)) * 100, 0)
|
||||
ELSE 0
|
||||
END AS porcentajeVictoria
|
||||
FROM usuario
|
||||
ORDER BY victorias DESC, aciertos DESC
|
||||
LIMIT " . (int)$limite;
|
||||
|
||||
$stmt = $conexion->prepare($sql);
|
||||
$stmt->execute();
|
||||
return $stmt->fetchAll(PDO::FETCH_ASSOC);
|
||||
} catch (PDOException $e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
<?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;
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/triviagmatico/includes/conexionBD.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Sesión no iniciada']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
||||
$orden = $_POST['orden'] ?? '';
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode(['error' => 'Partida no válida']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
echo json_encode($conexion);
|
||||
exit;
|
||||
}
|
||||
|
||||
switch ($orden) {
|
||||
case 'comprobarEstado':
|
||||
try {
|
||||
// Contar jugadores totales apuntados en los equipos de esta partida
|
||||
$stmt = $conexion->prepare("
|
||||
SELECT COUNT(exu.idUsuario) AS total_jugadores
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmt->execute([':idPartida' => $idPartida]);
|
||||
$totalJugadores = (int)$stmt->fetchColumn();
|
||||
|
||||
$preguntasTotalesEsperadas = $totalJugadores * 10;
|
||||
|
||||
// Contar respuestas dadas en la partida
|
||||
$stmtRespuestas = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
");
|
||||
$stmtRespuestas->execute([':idPartida' => $idPartida]);
|
||||
$respuestasRespondidas = (int)$stmtRespuestas->fetchColumn();
|
||||
|
||||
$terminada = ($respuestasRespondidas >= $preguntasTotalesEsperadas && $preguntasTotalesEsperadas > 0);
|
||||
|
||||
// Cuando la partida finaliza, se actualizan los históricos
|
||||
if ($terminada && !isset($_SESSION['partidas_procesadas'][$idPartida])) {
|
||||
|
||||
$conexion->beginTransaction();
|
||||
|
||||
// CÁLCULO DE VELOCIDAD PREGUNTA A PREGUNTA EN SESIÓN
|
||||
if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) {
|
||||
$_SESSION['primeros_en_acertar'][$idPartida] = [];
|
||||
}
|
||||
|
||||
// Vemos quién fue el primero
|
||||
$stmtVelocidad = $conexion->prepare("
|
||||
SELECT ra.idPartidaxPregunta, ra.idUsuario
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida AND r.correcta = 1
|
||||
ORDER BY ra.idRespuestaAlmacenada ASC
|
||||
");
|
||||
$stmtVelocidad->execute([':idPartida' => $idPartida]);
|
||||
$todosLosAciertos = $stmtVelocidad->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
foreach ($todosLosAciertos as $acierto) {
|
||||
$idPxp = $acierto['idPartidaxPregunta'];
|
||||
$idU = $acierto['idUsuario'];
|
||||
|
||||
if (!isset($_SESSION['primeros_en_acertar'][$idPartida][$idPxp])) {
|
||||
$_SESSION['primeros_en_acertar'][$idPartida][$idPxp] = $idU;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualizamos la base de datos
|
||||
// Buscamos los aciertos de cada jugador en la partida actual
|
||||
$stmtAciertos = $conexion->prepare("
|
||||
SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
INNER JOIN equipoxusuario exu ON ra.idUsuario = exu.idUsuario
|
||||
WHERE pxp.idPartida = :idPartida AND r.correcta = 1
|
||||
GROUP BY ra.idUsuario
|
||||
");
|
||||
$stmtAciertos->execute([':idPartida' => $idPartida]);
|
||||
$jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateAciertosGlobales = $conexion->prepare("
|
||||
UPDATE usuario
|
||||
SET aciertos = aciertos + :nuevos_aciertos
|
||||
WHERE idUsuario = :idUsuario
|
||||
");
|
||||
|
||||
$puntosEquipos = [];
|
||||
foreach ($jugadoresPartida as $jp) {
|
||||
$idU = (int)$jp['idUsuario'];
|
||||
$idE = (int)$jp['idEquipo'];
|
||||
$nuevosAciertos = (int)$jp['aciertos_partida'];
|
||||
|
||||
// Sumamos los aciertos al perfil del usuario
|
||||
$updateAciertos->execute([
|
||||
':nuevos_aciertos' => $nuevosAciertos,
|
||||
':idUsuario' => $idU
|
||||
]);
|
||||
|
||||
if (!isset($puntosEquipos[$idE])) {
|
||||
$puntosEquipos[$idE] = 0;
|
||||
}
|
||||
$puntosEquipos[$idE] += $nuevosAciertos;
|
||||
}
|
||||
|
||||
// Determinamos qué equipo ha obtenido más aciertos en la partida
|
||||
arsort($puntosEquipos);
|
||||
$idEquipoGanador = key($puntosEquipos);
|
||||
|
||||
// Obtenemos todos los usuarios de la partida para asignar victorias/derrotas
|
||||
$stmtMiembros = $conexion->prepare("
|
||||
SELECT exu.idUsuario, exu.idEquipo
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmtMiembros->execute([':idPartida' => $idPartida]);
|
||||
$todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateVictoria = $conexion->prepare("UPDATE usuario SET victorias = victorias + 1 WHERE idUsuario = :idUsuario");
|
||||
$updateDerrota = $conexion->prepare("UPDATE usuario SET derrotas = derrotas + 1 WHERE idUsuario = :idUsuario");
|
||||
|
||||
foreach ($todosLosMiembros as $miembro) {
|
||||
$idU = (int)$miembro['idUsuario'];
|
||||
$idE = (int)$miembro['idEquipo'];
|
||||
|
||||
if ($idE === $idEquipoGanador) {
|
||||
$updateVictoria->execute([':idUsuario' => $idU]);
|
||||
} else {
|
||||
$updateDerrota->execute([':idUsuario' => $idU]);
|
||||
}
|
||||
}
|
||||
|
||||
$conexion->commit();
|
||||
$_SESSION['partidas_procesadas'][$idPartida] = true;
|
||||
}
|
||||
|
||||
echo json_encode(['terminada' => $terminada]);
|
||||
} catch (PDOException $e) {
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
echo json_encode(['error' => $e->getMessage()]);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
echo json_encode(['error' => 'Acción no permitida']);
|
||||
break;
|
||||
}
|
||||
@@ -1,55 +1,55 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseCategoria.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearCategoria':
|
||||
|
||||
$nombreCategoria = trim($_POST['nombreCategoria'] ?? '');
|
||||
|
||||
if ($nombreCategoria == '') {
|
||||
echo json_encode(['error' => 'El nombre de la categoría es obligatorio']);
|
||||
break;
|
||||
}
|
||||
|
||||
$categoria = new Categoria(null, $nombreCategoria);
|
||||
$resultado = $categoria->crear();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarCategorias':
|
||||
|
||||
$categoria = new Categoria();
|
||||
$resultado = $categoria->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'buscarCategoria':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
|
||||
$categoria = new Categoria($idCategoria);
|
||||
$resultado = $categoria->buscar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarCategoria':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
|
||||
$categoria = new Categoria($idCategoria);
|
||||
$resultado = $categoria->borrar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/claseCategoria.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearCategoria':
|
||||
|
||||
$nombreCategoria = trim($_POST['nombreCategoria'] ?? '');
|
||||
|
||||
if ($nombreCategoria == '') {
|
||||
echo json_encode(['error' => 'El nombre de la categoría es obligatorio']);
|
||||
break;
|
||||
}
|
||||
|
||||
$categoria = new Categoria(null, $nombreCategoria);
|
||||
$resultado = $categoria->crear();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarCategorias':
|
||||
|
||||
$categoria = new Categoria();
|
||||
$resultado = $categoria->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'buscarCategoria':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
|
||||
$categoria = new Categoria($idCategoria);
|
||||
$resultado = $categoria->buscar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarCategoria':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
|
||||
$categoria = new Categoria($idCategoria);
|
||||
$resultado = $categoria->borrar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
}
|
||||
@@ -1,55 +1,55 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseEquipo.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearEquipo':
|
||||
|
||||
$nombreEquipo = trim($_POST['nombreEquipo'] ?? '');
|
||||
|
||||
if ($nombreEquipo == '') {
|
||||
echo json_encode(['error' => 'El nombre del equipo es obligatorio']);
|
||||
break;
|
||||
}
|
||||
|
||||
$equipo = new Equipo(null, $nombreEquipo);
|
||||
$resultado = $equipo->crear();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarEquipos':
|
||||
|
||||
$equipo = new Equipo();
|
||||
$resultado = $equipo->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'buscarEquipo':
|
||||
|
||||
$idEquipo = intval($_POST['idEquipo'] ?? 0);
|
||||
|
||||
$equipo = new Equipo($idEquipo);
|
||||
$resultado = $equipo->buscar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarEquipo':
|
||||
|
||||
$idEquipo = intval($_POST['idEquipo'] ?? 0);
|
||||
|
||||
$equipo = new Equipo($idEquipo);
|
||||
$resultado = $equipo->borrar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/claseEquipo.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearEquipo':
|
||||
|
||||
$nombreEquipo = trim($_POST['nombreEquipo'] ?? '');
|
||||
|
||||
if ($nombreEquipo == '') {
|
||||
echo json_encode(['error' => 'El nombre del equipo es obligatorio']);
|
||||
break;
|
||||
}
|
||||
|
||||
$equipo = new Equipo(null, $nombreEquipo);
|
||||
$resultado = $equipo->crear();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarEquipos':
|
||||
|
||||
$equipo = new Equipo();
|
||||
$resultado = $equipo->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'buscarEquipo':
|
||||
|
||||
$idEquipo = intval($_POST['idEquipo'] ?? 0);
|
||||
|
||||
$equipo = new Equipo($idEquipo);
|
||||
$resultado = $equipo->buscar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarEquipo':
|
||||
|
||||
$idEquipo = intval($_POST['idEquipo'] ?? 0);
|
||||
|
||||
$equipo = new Equipo($idEquipo);
|
||||
$resultado = $equipo->borrar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
}
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseEquipoxUsuario.php';
|
||||
require_once '../clases/claseEquipoxUsuario.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
require_once '../clases/claseJuego.php';
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// Comprobamos que haya un usuario conectado
|
||||
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode([
|
||||
'error' => 'Debes iniciar sesión para jugar.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$idUsuario = (int) $_SESSION['idUsuario'];
|
||||
|
||||
// Comprobamos que se haya indicado la partida
|
||||
|
||||
if (!isset($_POST['idPartida'])) {
|
||||
echo json_encode([
|
||||
'error' => 'No se ha indicado la partida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$idPartida = intval($_POST['idPartida']);
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode([
|
||||
'error' => 'La partida indicada no es válida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// Comprobamos que el usuario pertenezca a la partida
|
||||
|
||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida,$idUsuario);
|
||||
|
||||
if (is_array($perteneceAPartida)) {
|
||||
echo json_encode($perteneceAPartida);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
if (!$perteneceAPartida) {
|
||||
echo json_encode([
|
||||
'error' => 'No formas parte de esta partida.'
|
||||
]);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// Comprobamos la orden
|
||||
|
||||
$orden = $_POST['orden'] ?? '';
|
||||
|
||||
switch ($orden) {
|
||||
|
||||
// CARGAR LAS PREGUNTAS DE LA PARTIDA
|
||||
|
||||
case 'cargarPreguntas':
|
||||
|
||||
$resultado = Juego::cargarPreguntas($idPartida, $idUsuario);
|
||||
echo json_encode($resultado);
|
||||
|
||||
break;
|
||||
|
||||
// REGISTRAR RESPUESTA
|
||||
|
||||
case 'responder':
|
||||
|
||||
if (
|
||||
!isset($_POST['idPartidaxPregunta']) ||
|
||||
!isset($_POST['idRespuesta']) ||
|
||||
!isset($_POST['tiempoRespuesta'])
|
||||
) {
|
||||
echo json_encode([
|
||||
'error' => 'Faltan datos para registrar la respuestfdfa.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta']);
|
||||
$idRespuesta = intval($_POST['idRespuesta']);
|
||||
$tiempoRespuesta = intval($_POST['tiempoRespuesta']);
|
||||
|
||||
if (
|
||||
$idPartidaxPregunta <= 0 ||
|
||||
$idRespuesta <= 0 ||
|
||||
$tiempoRespuesta < 0
|
||||
) {
|
||||
echo json_encode([
|
||||
'error' => 'Los datos de la respuesta no son válidos.'
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// Registramos la respuesta del usuario junto con su tiempo de respuesta
|
||||
|
||||
$resultado = Juego::registrarRespuesta(
|
||||
$idPartida,
|
||||
$idUsuario,
|
||||
$idPartidaxPregunta,
|
||||
$idRespuesta,
|
||||
$tiempoRespuesta
|
||||
);
|
||||
|
||||
echo json_encode($resultado);
|
||||
|
||||
break;
|
||||
|
||||
// Finalizar la partida y registrar los aciertos del usuario
|
||||
|
||||
case 'finalizarPartida':
|
||||
|
||||
$aciertos = intval($_POST['aciertos'] ?? 0);
|
||||
|
||||
// Guardamos los aciertos en la sesión
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
?>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,153 +1,153 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClasePregunta.php';
|
||||
require_once '../clases/ClaseRespuesta.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearPregunta':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
$nombrePregunta = trim($_POST['nombrePregunta'] ?? '');
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* 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':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
$limite = intval($_POST['limite'] ?? 10);
|
||||
|
||||
$preguntas = Pregunta::obtenerPorCategoria($idCategoria, $limite);
|
||||
|
||||
// Si ha devuelto un array de errores (formato ['error'=>...]) lo mandamos tal cual
|
||||
if (isset($preguntas['error'])) {
|
||||
echo json_encode($preguntas);
|
||||
break;
|
||||
}
|
||||
|
||||
// Convertimos cada objeto Pregunta en un array simple para poder mandarlo en JSON
|
||||
$listado = [];
|
||||
foreach ($preguntas as $p) {
|
||||
$listado[] = [
|
||||
'idPregunta' => $p->getIdPregunta(),
|
||||
'idCategoria' => $p->getIdCategoria(),
|
||||
'nombrePregunta' => $p->getNombrePregunta(),
|
||||
'respuestas' => $p->getRespuestas()
|
||||
];
|
||||
}
|
||||
|
||||
echo json_encode($listado);
|
||||
break;
|
||||
}
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/clasePregunta.php';
|
||||
require_once '../clases/claseRespuesta.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearPregunta':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
$nombrePregunta = trim($_POST['nombrePregunta'] ?? '');
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* 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':
|
||||
|
||||
$idCategoria = intval($_POST['idCategoria'] ?? 0);
|
||||
$limite = intval($_POST['limite'] ?? 10);
|
||||
|
||||
$preguntas = Pregunta::obtenerPorCategoria($idCategoria, $limite);
|
||||
|
||||
// Si ha devuelto un array de errores (formato ['error'=>...]) lo mandamos tal cual
|
||||
if (isset($preguntas['error'])) {
|
||||
echo json_encode($preguntas);
|
||||
break;
|
||||
}
|
||||
|
||||
// Convertimos cada objeto Pregunta en un array simple para poder mandarlo en JSON
|
||||
$listado = [];
|
||||
foreach ($preguntas as $p) {
|
||||
$listado[] = [
|
||||
'idPregunta' => $p->getIdPregunta(),
|
||||
'idCategoria' => $p->getIdCategoria(),
|
||||
'nombrePregunta' => $p->getNombrePregunta(),
|
||||
'respuestas' => $p->getRespuestas()
|
||||
];
|
||||
}
|
||||
|
||||
echo json_encode($listado);
|
||||
break;
|
||||
}
|
||||
@@ -1,71 +1,71 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseRespuesta.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearRespuesta':
|
||||
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
$nombreRespuesta = trim($_POST['nombreRespuesta'] ?? '');
|
||||
$correcta = intval($_POST['correcta'] ?? 0);
|
||||
|
||||
if ($idPregunta <= 0 || $nombreRespuesta == '') {
|
||||
echo json_encode(['error' => 'La pregunta y el texto de la respuesta son obligatorios']);
|
||||
break;
|
||||
}
|
||||
|
||||
$respuesta = new Respuesta(null, $idPregunta, $nombreRespuesta, $correcta);
|
||||
$resultado = $respuesta->insertar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarRespuestas':
|
||||
|
||||
$respuesta = new Respuesta();
|
||||
$resultado = $respuesta->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarRespuestasPorPregunta':
|
||||
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta(null, $idPregunta);
|
||||
$resultado = $respuesta->listarPorPregunta();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'editarRespuesta':
|
||||
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
$nombreRespuesta = trim($_POST['nombreRespuesta'] ?? '');
|
||||
$correcta = intval($_POST['correcta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta($idRespuesta, $idPregunta, $nombreRespuesta, $correcta);
|
||||
$resultado = $respuesta->editar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarRespuesta':
|
||||
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta($idRespuesta);
|
||||
$resultado = $respuesta->eliminar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
}
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/claseRespuesta.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'crearRespuesta':
|
||||
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
$nombreRespuesta = trim($_POST['nombreRespuesta'] ?? '');
|
||||
$correcta = intval($_POST['correcta'] ?? 0);
|
||||
|
||||
if ($idPregunta <= 0 || $nombreRespuesta == '') {
|
||||
echo json_encode(['error' => 'La pregunta y el texto de la respuesta son obligatorios']);
|
||||
break;
|
||||
}
|
||||
|
||||
$respuesta = new Respuesta(null, $idPregunta, $nombreRespuesta, $correcta);
|
||||
$resultado = $respuesta->insertar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarRespuestas':
|
||||
|
||||
$respuesta = new Respuesta();
|
||||
$resultado = $respuesta->listar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'listarRespuestasPorPregunta':
|
||||
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta(null, $idPregunta);
|
||||
$resultado = $respuesta->listarPorPregunta();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'editarRespuesta':
|
||||
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
$idPregunta = intval($_POST['idPregunta'] ?? 0);
|
||||
$nombreRespuesta = trim($_POST['nombreRespuesta'] ?? '');
|
||||
$correcta = intval($_POST['correcta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta($idRespuesta, $idPregunta, $nombreRespuesta, $correcta);
|
||||
$resultado = $respuesta->editar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
|
||||
case 'borrarRespuesta':
|
||||
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
|
||||
$respuesta = new Respuesta($idRespuesta);
|
||||
$resultado = $respuesta->eliminar();
|
||||
|
||||
echo json_encode($resultado);
|
||||
break;
|
||||
|
||||
}
|
||||
+64
-64
@@ -1,65 +1,65 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseRespuestaAlmacenada.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'guardarRespuesta':
|
||||
|
||||
// Comprobamos que haya una sesión iniciada
|
||||
if (isset($_SESSION['idUsuario'])) {
|
||||
|
||||
$respuestaAlmacenada = new RespuestaAlmacenada();
|
||||
|
||||
// Recogemos los datos de la respuesta
|
||||
$respuestaAlmacenada->idPartidaxPregunta = $_POST['idPartidaxPregunta'];
|
||||
$respuestaAlmacenada->idUsuario = $_SESSION['idUsuario'];
|
||||
$respuestaAlmacenada->idRespuesta = $_POST['idRespuesta'];
|
||||
|
||||
// Guardamos la respuesta
|
||||
$respuesta = $respuestaAlmacenada->guardarRespuesta();
|
||||
|
||||
} else {
|
||||
|
||||
$respuesta = [
|
||||
'error' => 'No hay ninguna sesión iniciada.'
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
echo json_encode($respuesta);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case 'obtenerAciertosUsuarioEnPartida':
|
||||
|
||||
// Comprobamos que haya una sesión iniciada
|
||||
if (isset($_SESSION['idUsuario'])) {
|
||||
|
||||
$idPartida = $_POST['idPartida'];
|
||||
$idUsuario = $_SESSION['idUsuario'];
|
||||
|
||||
// Obtenemos los aciertos del usuario en esa partida
|
||||
$respuesta = RespuestaAlmacenada::obtenerAciertosUsuarioEnPartida(
|
||||
$idPartida,
|
||||
$idUsuario
|
||||
);
|
||||
|
||||
} else {
|
||||
|
||||
$respuesta = [
|
||||
'error' => 'No hay ninguna sesión iniciada.'
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
echo json_encode($respuesta);
|
||||
|
||||
break;
|
||||
|
||||
}//fin switch
|
||||
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/claseRespuestaAlmacenada.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
case 'guardarRespuesta':
|
||||
|
||||
// Comprobamos que haya una sesión iniciada
|
||||
if (isset($_SESSION['idUsuario'])) {
|
||||
|
||||
$respuestaAlmacenada = new RespuestaAlmacenada();
|
||||
|
||||
// Recogemos los datos de la respuesta
|
||||
$respuestaAlmacenada->idPartidaxPregunta = $_POST['idPartidaxPregunta'];
|
||||
$respuestaAlmacenada->idUsuario = $_SESSION['idUsuario'];
|
||||
$respuestaAlmacenada->idRespuesta = $_POST['idRespuesta'];
|
||||
|
||||
// Guardamos la respuesta
|
||||
$respuesta = $respuestaAlmacenada->guardarRespuesta();
|
||||
|
||||
} else {
|
||||
|
||||
$respuesta = [
|
||||
'error' => 'No hay ninguna sesión iniciada.'
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
echo json_encode($respuesta);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case 'obtenerAciertosUsuarioEnPartida':
|
||||
|
||||
// Comprobamos que haya una sesión iniciada
|
||||
if (isset($_SESSION['idUsuario'])) {
|
||||
|
||||
$idPartida = $_POST['idPartida'];
|
||||
$idUsuario = $_SESSION['idUsuario'];
|
||||
|
||||
// Obtenemos los aciertos del usuario en esa partida
|
||||
$respuesta = RespuestaAlmacenada::obtenerAciertosUsuarioEnPartida(
|
||||
$idPartida,
|
||||
$idUsuario
|
||||
);
|
||||
|
||||
} else {
|
||||
|
||||
$respuesta = [
|
||||
'error' => 'No hay ninguna sesión iniciada.'
|
||||
];
|
||||
|
||||
}
|
||||
|
||||
echo json_encode($respuesta);
|
||||
|
||||
break;
|
||||
|
||||
}//fin switch
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Sesión no iniciada']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
||||
$orden = $_POST['orden'] ?? '';
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode(['error' => 'Partida no válida']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
echo json_encode($conexion);
|
||||
exit;
|
||||
}
|
||||
|
||||
switch ($orden) {
|
||||
case 'comprobarEstado':
|
||||
try {
|
||||
// 1. Contar cuántos jugadores hay asignados en esta partida
|
||||
$stmt = $conexion->prepare("
|
||||
SELECT COUNT(exu.idUsuario) AS total_jugadores
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmt->execute([':idPartida' => $idPartida]);
|
||||
$totalJugadores = (int)$stmt->fetchColumn();
|
||||
|
||||
$preguntasTotalesEsperadas = $totalJugadores * 10;
|
||||
|
||||
// 2. Contar cuántas respuestas reales se han guardado
|
||||
$stmtRespuestas = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
");
|
||||
$stmtRespuestas->execute([':idPartida' => $idPartida]);
|
||||
$respuestasRespondidas = (int)$stmtRespuestas->fetchColumn();
|
||||
|
||||
$terminada = ($respuestasRespondidas >= $preguntasTotalesEsperadas && $preguntasTotalesEsperadas > 0);
|
||||
|
||||
// 3. Si ha terminado, guardamos los datos históricos una sola vez
|
||||
if ($terminada && !isset($_SESSION['partidas_procesadas'][$idPartida])) {
|
||||
|
||||
$conexion->beginTransaction();
|
||||
|
||||
// --- CÁLCULO DE VELOCIDAD ---
|
||||
if (!isset($_SESSION['primeros_en_acertar'][$idPartida])) {
|
||||
$_SESSION['primeros_en_acertar'][$idPartida] = [];
|
||||
}
|
||||
|
||||
$stmtVelocidad = $conexion->prepare("
|
||||
SELECT ra.idPartidaxPregunta, ra.idUsuario
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida AND r.correcta = 1
|
||||
ORDER BY ra.idRespuestaAlmacenada ASC
|
||||
");
|
||||
$stmtVelocidad->execute([':idPartida' => $idPartida]);
|
||||
$todosLosAciertos = $stmtVelocidad->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
foreach ($todosLosAciertos as $acierto) {
|
||||
$idPxp = $acierto['idPartidaxPregunta'];
|
||||
$idU = $acierto['idUsuario'];
|
||||
|
||||
if (!isset($_SESSION['primeros_en_acertar'][$idPartida][$idPxp])) {
|
||||
$_SESSION['primeros_en_acertar'][$idPartida][$idPxp] = $idU;
|
||||
}
|
||||
}
|
||||
|
||||
// Consulta de aciertos
|
||||
$stmtAciertos = $conexion->prepare("
|
||||
SELECT ra.idUsuario, exu.idEquipo, COUNT(*) as aciertos_partida
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
|
||||
INNER JOIN equipoxusuario exu ON ra.idUsuario = exu.idUsuario
|
||||
WHERE pxp.idPartida = :idPartida AND r.correcta = 1
|
||||
GROUP BY ra.idUsuario, exu.idEquipo
|
||||
");
|
||||
$stmtAciertos->execute([':idPartida' => $idPartida]);
|
||||
$jugadoresPartida = $stmtAciertos->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateAciertos = $conexion->prepare("
|
||||
UPDATE usuario
|
||||
SET aciertos = aciertos + :nuevos_aciertos
|
||||
WHERE idUsuario = :idUsuario
|
||||
");
|
||||
|
||||
$puntosEquipos = [];
|
||||
foreach ($jugadoresPartida as $jp) {
|
||||
$idU = (int)$jp['idUsuario'];
|
||||
$idE = (int)$jp['idEquipo'];
|
||||
$nuevosAciertos = (int)$jp['aciertos_partida'];
|
||||
|
||||
$updateAciertos->execute([
|
||||
':nuevos_aciertos' => $nuevosAciertos,
|
||||
':idUsuario' => $idU
|
||||
]);
|
||||
|
||||
if (!isset($puntosEquipos[$idE])) {
|
||||
$puntosEquipos[$idE] = 0;
|
||||
}
|
||||
$puntosEquipos[$idE] += $nuevosAciertos;
|
||||
}
|
||||
|
||||
if (!empty($puntosEquipos)) {
|
||||
arsort($puntosEquipos);
|
||||
$idEquipoGanador = key($puntosEquipos);
|
||||
|
||||
$stmtMiembros = $conexion->prepare("
|
||||
SELECT exu.idUsuario, exu.idEquipo
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmtMiembros->execute([':idPartida' => $idPartida]);
|
||||
$todosLosMiembros = $stmtMiembros->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
$updateVictoria = $conexion->prepare("UPDATE usuario SET victorias = victorias + 1 WHERE idUsuario = :idUsuario");
|
||||
$updateDerrota = $conexion->prepare("UPDATE usuario SET derrotas = derrotas + 1 WHERE idUsuario = :idUsuario");
|
||||
|
||||
foreach ($todosLosMiembros as $miembro) {
|
||||
$idU = (int)$miembro['idUsuario'];
|
||||
$idE = (int)$miembro['idEquipo'];
|
||||
|
||||
if ($idE === $idEquipoGanador) {
|
||||
$updateVictoria->execute([':idUsuario' => $idU]);
|
||||
} else {
|
||||
$updateDerrota->execute([':idUsuario' => $idU]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Marcar fecha fin de la partida para los históricos globales del grupo
|
||||
$stmtFinalizar = $conexion->prepare("
|
||||
UPDATE partida
|
||||
SET fechaFin = NOW()
|
||||
WHERE idPartida = :idPartida AND fechaFin IS NULL
|
||||
");
|
||||
$stmtFinalizar->execute([':idPartida' => $idPartida]);
|
||||
|
||||
$conexion->commit();
|
||||
$_SESSION['partidas_procesadas'][$idPartida] = true;
|
||||
}
|
||||
|
||||
echo json_encode(['terminada' => $terminada]);
|
||||
} catch (PDOException $e) {
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
echo json_encode(['error' => $e->getMessage()]);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'registrarSalidaUsuario':
|
||||
try {
|
||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
||||
$conexion->beginTransaction();
|
||||
|
||||
// A. LIBERACIÓN INMEDIATA DEL JUGADOR ACTUAL: Lo borramos de su equipo
|
||||
$stmtSalir = $conexion->prepare("DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario");
|
||||
$stmtSalir->execute([':idUsuario' => $idUsuario]);
|
||||
|
||||
// B. CONTADOR DE ALUMNOS QUEDAN: Contamos cuántas personas quedan en los equipos de esta partida
|
||||
$stmtContarQuedan = $conexion->prepare("
|
||||
SELECT COUNT(exu.idUsuario)
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
");
|
||||
$stmtContarQuedan->execute([':idPartida' => $idPartida]);
|
||||
$jugadoresRestantes = (int)$stmtContarQuedan->fetchColumn();
|
||||
|
||||
// C. DESTRUCCIÓN EN CADENA AUTOMÁTICA ATÓMICA (Si da 0, somos los últimos en salir)
|
||||
if ($jugadoresRestantes === 0) {
|
||||
// 1. Limpiar las respuestas almacenadas
|
||||
$stmtBorrarRespuestas = $conexion->prepare("
|
||||
DELETE ra FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
");
|
||||
$stmtBorrarRespuestas->execute([':idPartida' => $idPartida]);
|
||||
|
||||
// 2. Limpiar las preguntas vinculadas a la partida
|
||||
$stmtBorrarPreguntas = $conexion->prepare("DELETE FROM partidaxpregunta WHERE idPartida = :idPartida");
|
||||
$stmtBorrarPreguntas->execute([':idPartida' => $idPartida]);
|
||||
|
||||
// 3. NUEVO: Obtener los IDs de los dos equipos que jugaban en esta partida antes de borrar la relación
|
||||
$stmtObtenerEquipos = $conexion->prepare("SELECT idEquipo FROM equipoxpartida WHERE idPartida = :idPartida");
|
||||
$stmtObtenerEquipos->execute([':idPartida' => $idPartida]);
|
||||
$equiposDeLaPartida = $stmtObtenerEquipos->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
// 4. Limpiar la relación de equipos de la partida (tabla intermedia)
|
||||
$stmtBorrarEquiposPartida = $conexion->prepare("DELETE FROM equipoxpartida WHERE idPartida = :idPartida");
|
||||
$stmtBorrarEquiposPartida = $conexion->prepare("DELETE FROM equipoxpartida WHERE idPartida = :idPartida");
|
||||
$stmtBorrarEquiposPartida->execute([':idPartida' => $idPartida]);
|
||||
|
||||
// 5. NUEVO: Borrar físicamente los equipos de la tabla 'equipo' si existen
|
||||
if (!empty($equiposDeLaPartida)) {
|
||||
// Creamos los marcadores (?, ?) de forma dinámica según los equipos que devuelva
|
||||
$inQuery = implode(',', array_fill(0, count($equiposDeLaPartida), '?'));
|
||||
$stmtBorrarEquiposFisicos = $conexion->prepare("DELETE FROM equipo WHERE idEquipo IN ($inQuery)");
|
||||
$stmtBorrarEquiposFisicos->execute($equiposDeLaPartida);
|
||||
}
|
||||
|
||||
// 6. Borrar físicamente la fila de la partida principal
|
||||
$stmtBorrarSala = $conexion->prepare("DELETE FROM partida WHERE idPartida = :idPartida");
|
||||
$stmtBorrarSala->execute([':idPartida' => $idPartida]);
|
||||
}
|
||||
|
||||
$conexion->commit();
|
||||
echo json_encode(['exito' => true, 'usuarios_quedan' => $jugadoresRestantes]);
|
||||
} catch (PDOException $e) {
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
echo json_encode(['error' => $e->getMessage()]);
|
||||
}
|
||||
break;
|
||||
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseUsuario.php';
|
||||
require_once '../clases/claseUsuario.php';
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
|
||||
@@ -77,8 +77,9 @@
|
||||
}
|
||||
|
||||
.btn-unirse:hover {
|
||||
background-color: #0f56ab;
|
||||
background-color: #1f6f09;
|
||||
color: white;
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.modal-kahoot {
|
||||
|
||||
@@ -121,6 +121,7 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 15px;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.btn-play-kahoot:hover {
|
||||
|
||||
@@ -401,3 +401,18 @@
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
.modal-kahoot {
|
||||
border: none;
|
||||
border-radius: 20px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.modal-kahoot-header {
|
||||
background-color: var(--kahoot-purple);
|
||||
color: white;
|
||||
border-bottom: none;
|
||||
}
|
||||
+377
-114
@@ -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;
|
||||
padding: 0;
|
||||
box-shadow: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
||||
background-color: #f0f4f8;
|
||||
color: #2c3e50;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
font-family: 'Fredoka', sans-serif;
|
||||
background-color: var(--background);
|
||||
color: var(--text-dark);
|
||||
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 {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border: 6px solid #e2e8f0;
|
||||
border-top: 6px solid #3182ce;
|
||||
border-radius: 50%;
|
||||
width: 65px;
|
||||
height: 65px;
|
||||
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 {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ==========================================================================
|
||||
TABLAS DE CLASIFICACIÓN (RANKING)
|
||||
CABECERA DE RESULTADOS
|
||||
========================================================================== */
|
||||
.tabla-ranking {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.05rem;
|
||||
|
||||
#pantalla-resultados {
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
.tabla-ranking th,
|
||||
.tabla-ranking td {
|
||||
padding: 16px 20px;
|
||||
#pantalla-resultados h1 {
|
||||
text-align: center;
|
||||
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;
|
||||
}
|
||||
|
||||
.tabla-ranking th {
|
||||
background-color: #2d3748;
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
font-size: 0.9rem;
|
||||
letter-spacing: 0.5px;
|
||||
.tabla-ranking thead th:first-child {
|
||||
border-top-left-radius: 12px;
|
||||
}
|
||||
|
||||
/* Alinear los puntos y aciertos a la derecha para mejor lectura numérica */
|
||||
.tabla-ranking th:last-child,
|
||||
.tabla-ranking td:last-child {
|
||||
text-align: right;
|
||||
.tabla-ranking thead th:last-child {
|
||||
border-top-right-radius: 12px;
|
||||
}
|
||||
|
||||
.tabla-ranking tr {
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
transition: background-color 0.2s;
|
||||
|
||||
/* Celdas */
|
||||
|
||||
.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 {
|
||||
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 tr.top-player {
|
||||
background-color: #fefcbf !important; /* Amarillo suave */
|
||||
font-weight: bold;
|
||||
|
||||
.tabla-ranking tbody td:first-child {
|
||||
font-weight: 700;
|
||||
color: var(--kahoot-purple);
|
||||
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 {
|
||||
color: #b7791f;
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
/* ==========================================================================
|
||||
PUNTOS
|
||||
========================================================================== */
|
||||
|
||||
.tabla-ranking td strong {
|
||||
color: #2f855a; /* Verde para destacar los aciertos conseguidos */
|
||||
font-size: 1.1rem;
|
||||
color: var(--kahoot-green);
|
||||
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 {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
margin-top: 40px;
|
||||
padding-top: 20px;
|
||||
text-align: center;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
|
||||
/* Botón */
|
||||
|
||||
.btn-inicio {
|
||||
display: inline-block;
|
||||
background-color: #3182ce; /* Azul corporativo */
|
||||
color: #ffffff;
|
||||
padding: 14px 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
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-weight: 600;
|
||||
font-weight: 700;
|
||||
|
||||
text-decoration: none;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 6px rgba(49, 130, 206, 0.2);
|
||||
transition: background-color 0.2s, transform 0.2s, box-shadow 0.2s;
|
||||
|
||||
box-shadow: 0 5px 10px rgba(19, 104, 206, 0.25);
|
||||
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
|
||||
/* Hover */
|
||||
|
||||
.btn-inicio:hover {
|
||||
background-color: #2b6cb0; /* Azul ligeramente más oscuro al pasar el cursor */
|
||||
box-shadow: 0 6px 12px rgba(43, 108, 176, 0.3);
|
||||
transform: translateY(-2px); /* Pequeño salto hacia arriba */
|
||||
background-color: #0f56ab;
|
||||
color: white;
|
||||
|
||||
transform: translateY(-3px);
|
||||
|
||||
box-shadow: 0 8px 15px rgba(19, 104, 206, 0.30);
|
||||
}
|
||||
|
||||
|
||||
/* Click */
|
||||
|
||||
.btn-inicio:active {
|
||||
transform: translateY(0); /* Vuelve a su posición normal al pulsar */
|
||||
box-shadow: 0 2px 4px rgba(43, 108, 176, 0.2);
|
||||
transform: translateY(3px);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,17 @@
|
||||
<?php
|
||||
//CARGA DE ARCHIVOS .ENV CON PHPDOTENV
|
||||
//CARGA DE ARCHIVOS .ENV CON PHPDOTENV VERSION LOCAL
|
||||
require('c:/laragon/vendor/autoload.php');//Se carga el módulo instalado con composer
|
||||
$dotenv = Dotenv\Dotenv::createImmutable('c:/laragon/', 'triviagmatico.env');//leemos el archivo. El primer parámetro es la ruta para llegar y el segundo el nombre del archivo .env
|
||||
$dotenv->load();
|
||||
|
||||
//CARGA DE ARCHIVOS .ENV CON PHPDOTENV VERSION SERVIDOR
|
||||
/*
|
||||
require('/var/vendor/autoload.php');//Se carga el módulo instalado con composer
|
||||
$dotenv = Dotenv\Dotenv::createImmutable('/var/', 'triviagmatico.env');//leemos el archivo. El primer parámetro es la ruta para llegar y el segundo el nombre del archivo .env
|
||||
$dotenv->load();
|
||||
*/
|
||||
|
||||
|
||||
function conexionBD (){
|
||||
try{
|
||||
$servidor = 'mysql:host='.$_ENV['bDatosServer'].';dbname='.$_ENV['bDatos'];
|
||||
|
||||
@@ -4,13 +4,20 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Triviagmático</title>
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
<!-- Bootstrap 5 CSS -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<!-- FontAwesome para iconos -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
|
||||
<!-- Google Fonts para estilo Kahoot -->
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;600;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php include 'cabecera.php'; ?>
|
||||
<header id="cabecera-container"></header>
|
||||
|
||||
<div class="container my-5">
|
||||
<div class="row justify-content-center align-items-center g-4">
|
||||
@@ -46,6 +53,7 @@
|
||||
<!-- JS de Bootstrap -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/index.js"></script>
|
||||
<script src="js/cabecera.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+366
-292
@@ -1,435 +1,509 @@
|
||||
let usuarioYaEstaEnEquipo = false;
|
||||
let intervaloBuscadorSalas = null;
|
||||
let cargandoSalas = false;
|
||||
|
||||
$(document).ready(function () {
|
||||
comprobarSalaUsuario();
|
||||
});
|
||||
function iniciarActualizacionSalas() {
|
||||
if (intervaloBuscadorSalas) {
|
||||
clearInterval(intervaloBuscadorSalas);
|
||||
}
|
||||
|
||||
// 1. Comprobar si el usuario actual ya pertenece a una sala
|
||||
function comprobarSalaUsuario() {
|
||||
$("#cargandoSalas").remove();
|
||||
cargarSalas();
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { orden: "obtenerSalaUsuario" },
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error || !respuesta.asociado) {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
$("#contenedorCrearSala").show();
|
||||
cargarSalas();
|
||||
} else {
|
||||
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);
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
intervaloBuscadorSalas = setInterval(function () {
|
||||
if (!usuarioYaEstaEnEquipo) {
|
||||
cargarSalas();
|
||||
},
|
||||
});
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// 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 },
|
||||
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);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Cargar la lista completa de todas las salas
|
||||
function cargarSalas() {
|
||||
if (cargandoSalas) {
|
||||
return;
|
||||
}
|
||||
|
||||
cargandoSalas = true;
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { orden: "listar" },
|
||||
data: {
|
||||
orden: "listar",
|
||||
},
|
||||
|
||||
success: function (partidas) {
|
||||
const contenedor = $("#contenedorSalas");
|
||||
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 actualmente.</p>
|
||||
</div>
|
||||
`);
|
||||
$(".sala-item").remove();
|
||||
|
||||
if ($("#mensajeSinSalas").length === 0) {
|
||||
contenedor.append(`
|
||||
<div
|
||||
id="mensajeSinSalas"
|
||||
class="col-12 text-center">
|
||||
|
||||
<p class="text-muted">
|
||||
No hay salas disponibles actualmente.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$("#mensajeSinSalas").remove();
|
||||
|
||||
const idsPartidas = partidas.map(function (partida) {
|
||||
return String(partida.idPartida);
|
||||
});
|
||||
|
||||
$(".sala-item").each(function () {
|
||||
const idPartida = String($(this).data("id-partida"));
|
||||
|
||||
if (!idsPartidas.includes(idPartida)) {
|
||||
$(this).remove();
|
||||
}
|
||||
});
|
||||
|
||||
partidas.forEach(function (partida) {
|
||||
cargarInformacionSala(partida);
|
||||
cargarSalaBuscador(partida);
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener las partidas:", error);
|
||||
console.error(
|
||||
"Error al obtener las partidas:",
|
||||
error
|
||||
);
|
||||
},
|
||||
|
||||
complete: function () {
|
||||
cargandoSalas = false;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Obtener equipos y jugadores asociados a una sala concreta
|
||||
function cargarInformacionSala(partida) {
|
||||
function cargarSalaBuscador(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 },
|
||||
success: function (jugadores) {
|
||||
mostrarSala(partida, equipos, jugadores);
|
||||
data: {
|
||||
orden: "getJugadores",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
success: function (jugadores) {
|
||||
if (
|
||||
!Array.isArray(jugadores) ||
|
||||
jugadores.length === 0
|
||||
) {
|
||||
$(
|
||||
`.sala-item[data-id-partida="${partida.idPartida}"]`
|
||||
).remove();
|
||||
|
||||
comprobarSiNoHaySalas();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
actualizarSalaBuscador(
|
||||
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");
|
||||
function comprobarSiNoHaySalas() {
|
||||
if ($(".sala-item").length === 0) {
|
||||
if ($("#mensajeSinSalas").length === 0) {
|
||||
$("#contenedorSalas").append(`
|
||||
<div
|
||||
id="mensajeSinSalas"
|
||||
class="col-12 text-center">
|
||||
|
||||
<p class="text-muted">
|
||||
No hay salas disponibles actualmente.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function actualizarSalaBuscador(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
) {
|
||||
$("#mensajeSinSalas").remove();
|
||||
|
||||
const selectorSala =
|
||||
`.sala-item[data-id-partida="${partida.idPartida}"]`;
|
||||
|
||||
const salaExistente = $(selectorSala);
|
||||
|
||||
if (salaExistente.length === 0) {
|
||||
crearSalaBuscador(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const equiposHTML =
|
||||
generarEquiposHTML(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
);
|
||||
|
||||
salaExistente
|
||||
.find(".equipos")
|
||||
.html(equiposHTML);
|
||||
}
|
||||
|
||||
function crearSalaBuscador(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
) {
|
||||
$("#mensajeSinSalas").remove();
|
||||
|
||||
const equiposHTML =
|
||||
generarEquiposHTML(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
);
|
||||
|
||||
const salaHTML = `
|
||||
<div
|
||||
class="col-12 col-md-10 col-lg-8 sala-item"
|
||||
data-id-partida="${partida.idPartida}">
|
||||
|
||||
<div class="sala card p-3 shadow-sm mb-4">
|
||||
|
||||
<div
|
||||
class="sala-header h4 text-center mb-3 text-white">
|
||||
|
||||
${escapeHTML(partida.nombrePartida)}
|
||||
|
||||
</div>
|
||||
|
||||
<div class="sala-body">
|
||||
|
||||
<div class="equipos d-flex justify-content-around">
|
||||
|
||||
${equiposHTML}
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
|
||||
$("#contenedorSalas").append(salaHTML);
|
||||
}
|
||||
|
||||
function generarEquiposHTML(
|
||||
partida,
|
||||
equipos,
|
||||
jugadores
|
||||
) {
|
||||
let equiposHTML = "";
|
||||
|
||||
equipos.forEach(function (equipo) {
|
||||
const jugadoresEquipo = jugadores.filter(function (jugador) {
|
||||
return jugador.idEquipo == equipo.idEquipo;
|
||||
});
|
||||
const jugadoresEquipo =
|
||||
jugadores.filter(function (jugador) {
|
||||
return (
|
||||
jugador.idEquipo ==
|
||||
equipo.idEquipo
|
||||
);
|
||||
});
|
||||
|
||||
let jugadoresHTML = "";
|
||||
|
||||
if (jugadoresEquipo.length > 0) {
|
||||
jugadoresEquipo.forEach(function (jugador) {
|
||||
const esHost = jugador.idUsuario == partida.idUsuario;
|
||||
const esHost =
|
||||
jugador.idUsuario ==
|
||||
partida.idUsuario;
|
||||
|
||||
jugadoresHTML += `
|
||||
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${
|
||||
esHost ? "jugador-host" : ""
|
||||
}">
|
||||
<div>
|
||||
<span class="avatar">${esHost ? '<i class="bi bi-award-fill"></i>' : '<i class="bi bi-person-fill"></i>'}</span>
|
||||
${escapeHTML(jugador.nombreUsuario)}
|
||||
</div>
|
||||
<div
|
||||
class="jugador border border-2 d-flex align-items-center justify-content-between">
|
||||
|
||||
${
|
||||
esHost
|
||||
? `<span class="badge bg-warning text-dark ms-2">HOST</span>`
|
||||
: ""
|
||||
}
|
||||
</div>
|
||||
`;
|
||||
<div>
|
||||
|
||||
<span class="avatar">
|
||||
|
||||
${
|
||||
esHost
|
||||
? '<i class="bi bi-award-fill"></i>'
|
||||
: '<i class="bi bi-person-fill"></i>'
|
||||
}
|
||||
|
||||
</span>
|
||||
|
||||
${escapeHTML(
|
||||
jugador.nombreUsuario
|
||||
)}
|
||||
|
||||
</div>
|
||||
|
||||
${
|
||||
esHost
|
||||
? `
|
||||
<span
|
||||
class="badge bg-warning text-dark ms-2">
|
||||
|
||||
HOST
|
||||
|
||||
</span>
|
||||
`
|
||||
: ""
|
||||
}
|
||||
|
||||
</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-unirse w-100 btn-unirse-equipo mt-2"
|
||||
data-id-partida="${partida.idPartida}"
|
||||
data-id-equipo="${equipo.idEquipo}">
|
||||
<button
|
||||
type="button"
|
||||
class="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 me-2 ms-2 p-3 border rounded">
|
||||
<h6>${escapeHTML(equipo.nombreEquipo)}</h6>
|
||||
<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
|
||||
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
||||
let accionesSalaHTML = "";
|
||||
|
||||
if (usuarioYaEstaEnEquipo) {
|
||||
const esHost = partida.idUsuario == idUsuarioSesion;
|
||||
let botonIniciarHTML = "";
|
||||
|
||||
// Solo el host puede iniciar la partida
|
||||
if (esHost) {
|
||||
botonIniciarHTML = `
|
||||
<a href="juego.php?idPartida=${partida.idPartida}"
|
||||
class="btn btn-success btn-lg px-4">
|
||||
<i class="bi bi-controller"></i> ¡Iniciar Partida!
|
||||
</a>
|
||||
`;
|
||||
}
|
||||
|
||||
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}"
|
||||
data-es-host="${esHost}">
|
||||
Abandonar sala
|
||||
</button>
|
||||
|
||||
${botonIniciarHTML}
|
||||
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const salaHTML = `
|
||||
<div class="col-12 col-md-10 col-lg-8">
|
||||
<div class="sala card p-3 shadow-sm mb-4">
|
||||
<div class="sala-header h4 text-center mb-3 text-white">
|
||||
${escapeHTML(partida.nombrePartida)}
|
||||
</div>
|
||||
<div class="sala-body">
|
||||
<div class="equipos d-flex justify-content-around">
|
||||
${equiposHTML}
|
||||
</div>
|
||||
${accionesSalaHTML}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
contenedor.append(salaHTML);
|
||||
return equiposHTML;
|
||||
}
|
||||
|
||||
// 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).text("Uniéndose...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "registrarUsuarioEnEquipo",
|
||||
idEquipo: idEquipo,
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
return;
|
||||
}
|
||||
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
$("#contenedorCrearSala").hide();
|
||||
$("#contenedorSalas").empty();
|
||||
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");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// 7. Evento: Abandonar Sala
|
||||
// Guardamos temporalmente el botón presionado
|
||||
let botonAbandonarReferencia = null;
|
||||
|
||||
// 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 esHost = $(this).data("es-host") === true || $(this).data("es-host") === "true";
|
||||
const titulo = $("#modalAbandonarSalaLabel");
|
||||
const mensaje = $("#modalAbandonarSalaMensaje");
|
||||
const botonConfirmar = $("#btnConfirmarAbandonar");
|
||||
|
||||
if (esHost) {
|
||||
titulo.text("¿Abandonar la sala?");
|
||||
mensaje.text(
|
||||
"Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.",
|
||||
);
|
||||
botonConfirmar.text("Sí, abandonar");
|
||||
} else {
|
||||
titulo.text("¿Abandonar la sala?");
|
||||
mensaje.text(
|
||||
"Si sales de la sala, perderás tu lugar en el equipo.",
|
||||
);
|
||||
botonConfirmar.text("Sí, salir");
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
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");
|
||||
|
||||
if (modalInstance) {
|
||||
modalInstance.hide();
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
// 8. Evento: Crear Sala
|
||||
$("#btnCrearSala").on("click", function () {
|
||||
const nombreSala = $("#nombreSala").val().trim();
|
||||
const nombreEquipo1 = $("#nombreEquipo1").val().trim();
|
||||
const nombreEquipo2 = $("#nombreEquipo2").val().trim();
|
||||
const nombreSala =
|
||||
$("#nombreSala").val().trim();
|
||||
|
||||
const nombreEquipo1 =
|
||||
$("#nombreEquipo1").val().trim();
|
||||
|
||||
const nombreEquipo2 =
|
||||
$("#nombreEquipo2").val().trim();
|
||||
|
||||
let valido = true;
|
||||
$(".mensaje-error-sala").remove();
|
||||
$(".input-kahoot").removeClass("is-invalid");
|
||||
|
||||
if (nombreSala === "" || nombreSala.length < 3) {
|
||||
$(".mensaje-error-sala").remove();
|
||||
|
||||
$(".input-kahoot")
|
||||
.removeClass("is-invalid");
|
||||
|
||||
if (
|
||||
nombreSala === "" ||
|
||||
nombreSala.length < 3
|
||||
) {
|
||||
mostrarError(
|
||||
"#nombreSala",
|
||||
"El nombre de la sala debe tener al menos 3 caracteres.",
|
||||
"El nombre de la sala debe tener al menos 3 caracteres."
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (nombreEquipo1 === "" || nombreEquipo1.length < 2) {
|
||||
if (
|
||||
nombreEquipo1 === "" ||
|
||||
nombreEquipo1.length < 2
|
||||
) {
|
||||
mostrarError(
|
||||
"#nombreEquipo1",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres."
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (nombreEquipo2 === "" || nombreEquipo2.length < 2) {
|
||||
if (
|
||||
nombreEquipo2 === "" ||
|
||||
nombreEquipo2.length < 2
|
||||
) {
|
||||
mostrarError(
|
||||
"#nombreEquipo2",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
"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) {
|
||||
return;
|
||||
}
|
||||
|
||||
const boton = $("#btnCrearSala");
|
||||
boton.prop("disabled", true).text("Creando sala...");
|
||||
|
||||
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");
|
||||
|
||||
boton
|
||||
.prop("disabled", false)
|
||||
.text("Crear sala");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
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");
|
||||
console.error(
|
||||
"Error al crear la sala:",
|
||||
error
|
||||
);
|
||||
|
||||
alert(
|
||||
"No se ha podido crear la sala."
|
||||
);
|
||||
|
||||
boton
|
||||
.prop("disabled", false)
|
||||
.text("Crear sala");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Auxiliares
|
||||
function escapeHTML(texto) {
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
}
|
||||
|
||||
function mostrarError(selector, mensaje) {
|
||||
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>
|
||||
`);
|
||||
}
|
||||
|
||||
$(document).on("input", ".input-kahoot", 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();
|
||||
}
|
||||
);
|
||||
+127
-109
@@ -1,14 +1,19 @@
|
||||
let idUsuarioSesion = null;
|
||||
|
||||
$(document).ready(function () {
|
||||
comprobarSesion();
|
||||
// Cargar la cabecera HTML e iniciar comprobación de sesión SOLO al terminar de cargar
|
||||
$("#cabecera-container").load("cabecera.html", function (response, status, xhr) {
|
||||
if (status === "error") {
|
||||
console.error("Error al cargar cabecera.html:", xhr.status, xhr.statusText);
|
||||
} else {
|
||||
comprobarSesion();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Función auxiliar para escapar texto HTML
|
||||
function escapeHTML(str) {
|
||||
return $("<div>")
|
||||
.text(str ?? "")
|
||||
.html();
|
||||
return $("<div>").text(str ?? "").html();
|
||||
}
|
||||
|
||||
// Comprobar estado de sesión al cargar la página
|
||||
@@ -16,81 +21,88 @@ function comprobarSesion() {
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
dataType: "json",
|
||||
data: { orden: "comprobarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
try {
|
||||
if (typeof respuesta === "string") {
|
||||
respuesta = JSON.parse(respuesta);
|
||||
})
|
||||
.done(function (respuesta) {
|
||||
const contenedor = $("#contenedorUsuarioCabecera");
|
||||
if (!contenedor.length) return; // Si aún no existe el contenedor en HTML, cancelamos
|
||||
|
||||
contenedor.empty();
|
||||
|
||||
if (respuesta && respuesta.activa && respuesta.usuario) {
|
||||
// Guardar idUsuario globalmente
|
||||
idUsuarioSesion = respuesta.usuario.idUsuario;
|
||||
const avatarUrl = respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg";
|
||||
|
||||
// Usuario autenticado: Menú desplegable
|
||||
const htmlUsuario = `
|
||||
<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">
|
||||
<img src="${escapeHTML(avatarUrl)}" alt="Avatar" class="rounded-circle" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHTML(respuesta.usuario.nombreUsuario)}</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>
|
||||
`;
|
||||
contenedor.html(htmlUsuario);
|
||||
|
||||
// Si estamos en la página de perfil, rellenamos nombre y foto
|
||||
if ($("#nombre").length) {
|
||||
$("#nombre").text(respuesta.usuario.nombreUsuario);
|
||||
// ?t= evita que el navegador enseñe la foto antigua en caché
|
||||
$("#fotoPerfil").attr("src", avatarUrl + "?t=" + new Date().getTime());
|
||||
}
|
||||
|
||||
const contenedor = $("#contenedorUsuarioCabecera");
|
||||
contenedor.empty();
|
||||
|
||||
if (respuesta.activa && respuesta.usuario) {
|
||||
// Obtenemos la ruta del avatar o la de por defecto
|
||||
const avatarUrl =
|
||||
respuesta.usuario.avatar || "img/avatars/defaultProfile.jpeg";
|
||||
|
||||
// Usuario autenticado: Mostrar Menú Dropdown con el avatar
|
||||
const htmlUsuario = `
|
||||
<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">
|
||||
<img src="${escapeHTML(avatarUrl)}" alt="Avatar" class="rounded-circle" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHTML(respuesta.usuario.nombreUsuario)}</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>
|
||||
`;
|
||||
contenedor.html(htmlUsuario);
|
||||
|
||||
// Si estamos en la página principal, mostramos el botón JUGAR
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").removeClass("d-none");
|
||||
$("#colRanking")
|
||||
.removeClass("col-lg-8")
|
||||
.addClass("col-lg-7 col-xl-8");
|
||||
}
|
||||
} else {
|
||||
// No hay sesión: Mostrar botones de Login y Registro
|
||||
const htmlInvitado = `
|
||||
<button type="button" class="btn btn-kahoot-login rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar Sesión
|
||||
</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>
|
||||
`;
|
||||
contenedor.html(htmlInvitado);
|
||||
|
||||
// Si estamos en la página principal, ocultamos el botón JUGAR
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").addClass("d-none");
|
||||
$("#colRanking")
|
||||
.removeClass("col-lg-7 col-xl-8")
|
||||
.addClass("col-lg-8");
|
||||
}
|
||||
// Si estamos en la página principal, mostramos el botón JUGAR
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").removeClass("d-none");
|
||||
$("#colRanking").removeClass("col-lg-8").addClass("col-lg-7 col-xl-8");
|
||||
}
|
||||
} else {
|
||||
// Si estamos en el perfil y no hay sesión, volvemos al inicio
|
||||
if ($("#nombre").length) {
|
||||
window.location.href = "index.php";
|
||||
return;
|
||||
}
|
||||
|
||||
// No hay sesión: Botones de Login y Registro
|
||||
const htmlInvitado = `
|
||||
<button type="button" class="btn btn-kahoot-login rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar Sesión
|
||||
</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>
|
||||
`;
|
||||
contenedor.html(htmlInvitado);
|
||||
|
||||
if ($("#colBotonJugar").length) {
|
||||
$("#colBotonJugar").addClass("d-none");
|
||||
$("#colRanking").removeClass("col-lg-7 col-xl-8").addClass("col-lg-8");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Error al procesar la respuesta de la sesión:", e);
|
||||
}
|
||||
})
|
||||
.fail(function (xhr, status, error) {
|
||||
console.error("Error en comprobarSesion AJAX:", error, xhr.responseText);
|
||||
});
|
||||
}
|
||||
|
||||
// Registro
|
||||
$("#botonAceptarRegistro").click(function (event) {
|
||||
// Registro de usuario
|
||||
$(document).on("click", "#botonAceptarRegistro", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let nombreUsuario = $("#regNombre").val().trim();
|
||||
@@ -98,61 +110,64 @@ $("#botonAceptarRegistro").click(function (event) {
|
||||
let contrasena = $("#regPassword").val();
|
||||
let contrasenaConfirmacion = $("#regPasswordConfirm").val();
|
||||
|
||||
$("#regNombre").removeClass("is-invalid");
|
||||
$("#regEmail").removeClass("is-invalid");
|
||||
$("#regPassword").removeClass("is-invalid");
|
||||
$("#regPasswordConfirm").removeClass("is-invalid");
|
||||
$("#errorRegistro").text("");
|
||||
// Resetear estados visuales
|
||||
$("#regNombre, #regEmail, #regPassword, #regPasswordConfirm").removeClass("is-invalid");
|
||||
$("#errorRegistro").removeClass("text-danger text-success").text("").show();
|
||||
|
||||
if (contrasena !== contrasenaConfirmacion) {
|
||||
$("#regPassword").addClass("is-invalid");
|
||||
$("#regPasswordConfirm").addClass("is-invalid");
|
||||
$("#errorRegistro").text("Las contraseñas no coinciden.");
|
||||
$("#regPassword, #regPasswordConfirm").addClass("is-invalid");
|
||||
$("#errorRegistro").addClass("text-danger").text("Las contraseñas no coinciden.");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
dataType: "json",
|
||||
data: {
|
||||
nombreUsuario: nombreUsuario,
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "registrarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
})
|
||||
.done(function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$("#errorRegistro").text(respuesta.error);
|
||||
$("#regNombre").addClass("is-invalid");
|
||||
$("#regEmail").addClass("is-invalid");
|
||||
$("#errorRegistro").addClass("text-danger").text(respuesta.error);
|
||||
$("#regNombre, #regEmail").addClass("is-invalid");
|
||||
} else {
|
||||
// Mostrar mensaje de confirmación
|
||||
$("#errorRegistro")
|
||||
.removeClass("text-danger")
|
||||
.addClass("text-success")
|
||||
.text(respuesta.exito);
|
||||
.addClass("text-success fw-bold")
|
||||
.text(respuesta.exito || "¡Registro completado con éxito!");
|
||||
|
||||
$("#formRegistro")[0].reset();
|
||||
if ($("#formRegistro").length) {
|
||||
$("#formRegistro")[0].reset();
|
||||
}
|
||||
|
||||
// Recargar para iniciar sesión tras 1.5 segundos
|
||||
setTimeout(function () {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
}, 1500);
|
||||
}
|
||||
})
|
||||
.fail(function (xhr, status, error) {
|
||||
console.error("Error en el registro:", error, xhr.responseText);
|
||||
$("#errorRegistro").addClass("text-danger").text("Error de conexión con el servidor.");
|
||||
});
|
||||
});
|
||||
|
||||
// Login
|
||||
$("#botonAceptarLogin").click(function (event) {
|
||||
// Login de usuario
|
||||
$(document).on("click", "#botonAceptarLogin", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let email = $("#loginEmail").val().trim();
|
||||
let contrasena = $("#loginPassword").val();
|
||||
let recuerdame = $("#recordar").is(":checked");
|
||||
|
||||
$("#loginEmail").removeClass("is-invalid");
|
||||
$("#loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").text("");
|
||||
$("#loginEmail, #loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").removeClass("text-success").addClass("text-danger").text("").show();
|
||||
|
||||
if (email === "" || contrasena === "") {
|
||||
$("#errorLogin").text("Todos los campos son obligatorios.");
|
||||
@@ -164,40 +179,43 @@ $("#botonAceptarLogin").click(function (event) {
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
dataType: "json",
|
||||
data: {
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
recuerdame: recuerdame,
|
||||
orden: "comprobarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
})
|
||||
.done(function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
$("#loginEmail, #loginPassword").addClass("is-invalid");
|
||||
$("#errorLogin").text(respuesta.error);
|
||||
} else {
|
||||
// Login correcto: Recargar la vista
|
||||
location.reload();
|
||||
}
|
||||
})
|
||||
.fail(function (xhr, status, error) {
|
||||
console.error("Error en el login:", error, xhr.responseText);
|
||||
$("#errorLogin").text("Error de conexión o respuesta no válida del servidor.");
|
||||
});
|
||||
});
|
||||
|
||||
// Cerrar sesión
|
||||
// Cerrar sesión
|
||||
$(document).on("click", "#botonCerrarSesion", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
dataType: "json",
|
||||
data: { orden: "cerrarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
console.log(respuesta.error);
|
||||
} else {
|
||||
window.location.href = "index.php";
|
||||
}
|
||||
})
|
||||
.done(function (respuesta) {
|
||||
window.location.href = "index.php";
|
||||
})
|
||||
.fail(function () {
|
||||
window.location.href = "index.php";
|
||||
});
|
||||
});
|
||||
});
|
||||
+5
-5
@@ -36,11 +36,11 @@ function renderizarTablaRanking(jugadores) {
|
||||
<thead class="table-dark">
|
||||
<tr>
|
||||
<th scope="col" style="width: 10%;">#</th>
|
||||
<th scope="col" class="text-start" style="width: 35%;">Jugador</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-trophy text-warning me-1"></i> Vic</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-xmark text-danger me-1"></i> Der</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-bullseye text-success me-1"></i> Aciertos</th>
|
||||
<th scope="col" style="width: 10%;"><i class="fa-solid fa-percent text-info me-1"></i> % Vic</th>
|
||||
<th scope="col" class="text-start" style="width: 30%;"><i class="fa-solid fa-user"></i> <br> Jugador</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-trophy text-warning me-1"></i> <br> Victorias</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-xmark text-danger me-1"></i> <br> Derrotas</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-bullseye text-success me-1"></i> <br> Aciertos</th>
|
||||
<th scope="col" style="width: 15%;"><i class="fa-solid fa-medal text-info me-1"></i> <br> Efectividad</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
+111
-12
@@ -2,7 +2,7 @@
|
||||
// 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 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)
|
||||
@@ -18,9 +18,21 @@ let preguntas = [];
|
||||
let indice = 0; // pregunta que se está mostrando
|
||||
let bloqueado = false; // true mientras se envía una respuesta o se ve el feedback
|
||||
let numeroAciertos = 0; // número de aciertos del jugador
|
||||
let tiempoRespuesta = 0;
|
||||
let intervaloTiempo;
|
||||
|
||||
$(document).ready(function () {
|
||||
idPartida = parseInt($("body").data("id-partida"), 10);
|
||||
// Obtenemos el idPartida de la URL
|
||||
// Ejemplo: juego.php?idPartida=3
|
||||
|
||||
const parametros = new URLSearchParams(window.location.search);
|
||||
|
||||
idPartida = parseInt(parametros.get("idPartida"), 10);
|
||||
|
||||
if (!idPartida || idPartida < 1) {
|
||||
mostrarError("La partida indicada no es válida.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Un solo listener para todos los botones de respuesta
|
||||
$("#respuestas").on("click", ".btn-answer", function () {
|
||||
@@ -72,6 +84,11 @@ function cargarPreguntas() {
|
||||
function mostrarPregunta() {
|
||||
const pregunta = preguntas[indice];
|
||||
|
||||
tiempoRespuesta = 0;
|
||||
intervaloTiempo = setInterval(function () {
|
||||
tiempoRespuesta++;
|
||||
}, 100);
|
||||
|
||||
bloqueado = false;
|
||||
|
||||
$("#textoPregunta").text(pregunta.nombrePregunta);
|
||||
@@ -100,13 +117,44 @@ function mostrarPregunta() {
|
||||
|
||||
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
|
||||
function responder($botonPulsado) {
|
||||
clearInterval(intervaloTiempo);
|
||||
|
||||
console.log(
|
||||
"Tiempo de respuesta: " +
|
||||
tiempoRespuesta / 10 +
|
||||
" segundos"
|
||||
);
|
||||
|
||||
if (bloqueado) {
|
||||
return;
|
||||
}
|
||||
|
||||
bloqueado = true;
|
||||
|
||||
const pregunta = preguntas[indice];
|
||||
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");
|
||||
|
||||
@@ -114,45 +162,96 @@ function responder($botonPulsado) {
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "responder",
|
||||
idPartida: idPartida,
|
||||
idPartidaxPregunta: pregunta.idPartidaxPregunta,
|
||||
idRespuesta: idRespuesta,
|
||||
tiempoRespuesta: tiempoRespuesta
|
||||
},
|
||||
|
||||
success: function (datos) {
|
||||
|
||||
console.log("RESPUESTA DEL SERVIDOR:", datos);
|
||||
|
||||
if (datos.error) {
|
||||
// No se guardó: dejamos que vuelva a intentarlo
|
||||
$("#feedback").text(datos.error).removeClass("ok").addClass("ko");
|
||||
|
||||
$("#feedback")
|
||||
.text(datos.error)
|
||||
.removeClass("ok")
|
||||
.addClass("ko");
|
||||
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
|
||||
bloqueado = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
pregunta.respondida = true;
|
||||
mostrarFeedback($botonPulsado, datos);
|
||||
|
||||
mostrarFeedback(
|
||||
$botonPulsado,
|
||||
datos
|
||||
);
|
||||
|
||||
setTimeout(function () {
|
||||
if (datos.terminada || indice >= preguntas.length - 1) {
|
||||
|
||||
if (
|
||||
datos.terminada ||
|
||||
indice >= preguntas.length - 1
|
||||
) {
|
||||
terminar();
|
||||
} else {
|
||||
|
||||
indice++;
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
|
||||
$("#respuestas")
|
||||
.removeClass("bloqueado");
|
||||
|
||||
mostrarPregunta();
|
||||
}
|
||||
|
||||
}, PAUSA_FEEDBACK);
|
||||
},
|
||||
error: function () {
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
|
||||
console.error(
|
||||
"ERROR AJAX RESPONDER"
|
||||
);
|
||||
|
||||
console.error(
|
||||
"HTTP:",
|
||||
xhr.status
|
||||
);
|
||||
|
||||
console.error(
|
||||
"ERROR:",
|
||||
error
|
||||
);
|
||||
|
||||
console.error(
|
||||
"RESPUESTA:",
|
||||
xhr.responseText
|
||||
);
|
||||
|
||||
$("#feedback")
|
||||
.text("No se pudo guardar la respuesta. Inténtalo de nuevo.")
|
||||
.text(
|
||||
"No se pudo guardar la respuesta. Inténtalo de nuevo."
|
||||
)
|
||||
.removeClass("ok")
|
||||
.addClass("ko");
|
||||
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
|
||||
bloqueado = false;
|
||||
},
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Marca la respuesta correcta en verde y atenúa el resto
|
||||
function mostrarFeedback($botonPulsado, datos) {
|
||||
$("#respuestas .btn-answer").each(function () {
|
||||
@@ -216,4 +315,4 @@ function mostrarError(mensaje) {
|
||||
$("#feedback").html(
|
||||
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-6
@@ -50,10 +50,9 @@ function cambiarNombre() {
|
||||
$("#nuevoNombre").val("");
|
||||
|
||||
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
comprobarSesion();
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -71,6 +70,7 @@ function borrarNombre() {
|
||||
|
||||
function seleccionarFoto() {
|
||||
$("#inputFoto").click();
|
||||
|
||||
}
|
||||
|
||||
$("#inputFoto").change(function () {
|
||||
@@ -79,6 +79,7 @@ $("#inputFoto").change(function () {
|
||||
if (!archivo) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// Comprobamos que sea una imagen
|
||||
if (!archivo.type.startsWith("image/")) {
|
||||
@@ -110,9 +111,8 @@ $("#inputFoto").change(function () {
|
||||
);
|
||||
|
||||
// Actualizamos también el avatar superior en la cabecera
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
|
||||
comprobarSesion();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+72
-30
@@ -1,38 +1,80 @@
|
||||
$(document).ready(function () {
|
||||
const idPartida = $("body").data("id-partida");
|
||||
|
||||
comprobarEstadoPartida(idPartida);
|
||||
// Captura segura del ID de la partida desde el body de la página
|
||||
const idPartida =
|
||||
$("body").attr("data-id-partida") || $("body").data("id-partida");
|
||||
|
||||
const intervalo = setInterval(function () {
|
||||
comprobarEstadoPartida(idPartida, intervalo);
|
||||
}, 3000);
|
||||
comprobarEstadoPartida(idPartida);
|
||||
|
||||
const intervalo = setInterval(function () {
|
||||
comprobarEstadoPartida(idPartida, intervalo);
|
||||
}, 3000);
|
||||
});
|
||||
|
||||
function comprobarEstadoPartida(idPartida, intervalo = null) {
|
||||
$.ajax({
|
||||
url: "controladores/ControladorResultados.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "comprobarEstado",
|
||||
idPartida: idPartida
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
console.error("Error:", respuesta.error);
|
||||
return;
|
||||
}
|
||||
if (!idPartida || idPartida <= 0) return;
|
||||
|
||||
if (respuesta.terminada) {
|
||||
if (intervalo !== null) clearInterval(intervalo);
|
||||
|
||||
$("#pantalla-espera").fadeOut(400, function() {
|
||||
location.reload();
|
||||
});
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
console.log("Error de comunicación con el controlador.");
|
||||
$.ajax({
|
||||
url: "controladores/controladorResultados.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "comprobarEstado",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
console.error("Error del controlador:", respuesta.error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (respuesta.terminada === true || respuesta.terminada === "true") {
|
||||
if (intervalo !== null) {
|
||||
clearInterval(intervalo);
|
||||
}
|
||||
});
|
||||
|
||||
$("#pantalla-espera").hide();
|
||||
$("#pantalla-resultados").show();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
console.log("Esperando conexión con el servidor del Trivial...");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// INTERCEPTOR DE SALIDA: Saca al usuario y destruye la sala en cascada
|
||||
$(document).on("click", "#btnVolverInicio", function (e) {
|
||||
e.preventDefault(); // Congelamos un instante la redirección
|
||||
|
||||
const urlDestino = $(this).attr("href");
|
||||
// Leemos el ID de forma científica directamente desde el botón pulsado
|
||||
const idPartida = $(this).attr("data-id");
|
||||
|
||||
if (!idPartida) {
|
||||
window.location.href = urlDestino;
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorResultados.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "registrarSalidaUsuario",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
success: function (response) {
|
||||
console.log(
|
||||
"Servidor procesó la salida. Usuarios restantes: " +
|
||||
response.usuarios_quedan,
|
||||
);
|
||||
},
|
||||
error: function (error) {
|
||||
console.error("Error técnico al salir de la sala:", error);
|
||||
},
|
||||
complete: function () {
|
||||
// Rompemos la pausa y mandamos al jugador al menú de inicio limpio
|
||||
window.location.href = urlDestino;
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
+619
@@ -0,0 +1,619 @@
|
||||
let usuarioYaEstaEnEquipo = false;
|
||||
let intervaloSala = null;
|
||||
let botonAbandonarReferencia = null;
|
||||
|
||||
$(document).ready(function () {
|
||||
comprobarSalaUsuario();
|
||||
});
|
||||
|
||||
function comprobarSalaUsuario() {
|
||||
$("#cargandoSalas").remove();
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "obtenerSalaUsuario",
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error || !respuesta.asociado) {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
$("#contenedorCrearSala").show();
|
||||
|
||||
iniciarActualizacionSalas();
|
||||
} else {
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
|
||||
cargarSalaUsuario(respuesta.idPartida);
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
if (intervaloSala) {
|
||||
clearInterval(intervaloSala);
|
||||
intervaloSala = null;
|
||||
}
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
$("#contenedorCrearSala").show();
|
||||
|
||||
iniciarActualizacionSalas();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function cargarSalaUsuario(idPartida) {
|
||||
cargarSalaCompleta(idPartida);
|
||||
|
||||
if (intervaloSala) {
|
||||
clearInterval(intervaloSala);
|
||||
}
|
||||
|
||||
intervaloSala = setInterval(function () {
|
||||
actualizarSalaUsuario(idPartida);
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
function cargarSalaCompleta(idPartida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "buscar",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
|
||||
success: function (partida) {
|
||||
if (partida.error) {
|
||||
console.error(partida.error);
|
||||
return;
|
||||
}
|
||||
|
||||
cargarInformacionSalaCompleta(partida);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener la sala:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function cargarInformacionSalaCompleta(partida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getEquipos",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
success: function (equipos) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getJugadores",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
success: function (jugadores) {
|
||||
mostrarSala(partida, equipos, jugadores);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener jugadores:", error);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener equipos:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function actualizarSalaUsuario(idPartida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "buscar",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
|
||||
success: function (partida) {
|
||||
if (partida.error) {
|
||||
console.error(partida.error);
|
||||
return;
|
||||
}
|
||||
|
||||
cargarInformacionSala(partida);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al actualizar la sala:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function cargarInformacionSala(partida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getEquipos",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
success: function (equipos) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getJugadores",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
success: function (jugadores) {
|
||||
mostrarEquipos(partida, equipos, jugadores);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener jugadores:", error);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener equipos:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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) {
|
||||
const esHost = jugador.idUsuario == partida.idUsuario;
|
||||
|
||||
jugadoresHTML += `
|
||||
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${
|
||||
esHost ? "jugador-host" : ""
|
||||
}">
|
||||
|
||||
<div>
|
||||
<span class="avatar">
|
||||
${
|
||||
esHost
|
||||
? '<i class="bi bi-award-fill"></i>'
|
||||
: '<i class="bi bi-person-fill"></i>'
|
||||
}
|
||||
</span>
|
||||
|
||||
${escapeHTML(jugador.nombreUsuario)}
|
||||
</div>
|
||||
|
||||
${
|
||||
esHost
|
||||
? `<span class="badge bg-warning text-dark ms-2">
|
||||
HOST
|
||||
</span>`
|
||||
: ""
|
||||
}
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} else {
|
||||
jugadoresHTML = `
|
||||
<div class="text-muted small">
|
||||
Sin jugadores
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
equiposHTML += `
|
||||
<div class="equipo me-2 ms-2 p-3 border rounded">
|
||||
|
||||
<h6>
|
||||
${escapeHTML(equipo.nombreEquipo)}
|
||||
</h6>
|
||||
|
||||
<div class="jugadores mb-2">
|
||||
${jugadoresHTML}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
const esHost = partida.idUsuario == idUsuarioSesion;
|
||||
|
||||
let botonIniciarHTML = "";
|
||||
|
||||
if (esHost) {
|
||||
botonIniciarHTML = `
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-success btn-lg px-4 btn-iniciar-partida"
|
||||
data-id-partida="${partida.idPartida}">
|
||||
|
||||
<i class="bi bi-controller"></i>
|
||||
¡Iniciar Partida!
|
||||
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
const salaHTML = `
|
||||
<div class="col-12 col-md-10 col-lg-8">
|
||||
|
||||
<div class="sala card p-3 shadow-sm mb-4">
|
||||
|
||||
<div class="sala-header h4 text-center mb-3 text-white">
|
||||
${escapeHTML(partida.nombrePartida)}
|
||||
</div>
|
||||
|
||||
<div class="sala-body">
|
||||
|
||||
<div class="equipos d-flex justify-content-around">
|
||||
${equiposHTML}
|
||||
</div>
|
||||
|
||||
<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}"
|
||||
data-es-host="${esHost}">
|
||||
|
||||
Abandonar sala
|
||||
|
||||
</button>
|
||||
|
||||
${esHost ? botonIniciarHTML : ""}
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
|
||||
contenedor.html(salaHTML);
|
||||
if (!partida.fechaInicio) {
|
||||
iniciarComprobacionPartida(partida.idPartida);
|
||||
}
|
||||
}
|
||||
|
||||
let intervaloComprobarPartida = null;
|
||||
|
||||
function iniciarComprobacionPartida(idPartida) {
|
||||
if (intervaloComprobarPartida) {
|
||||
clearInterval(intervaloComprobarPartida);
|
||||
}
|
||||
|
||||
intervaloComprobarPartida = setInterval(function () {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
|
||||
type: "POST",
|
||||
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "comprobarInicio",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
if (respuesta.iniciada) {
|
||||
clearInterval(intervaloComprobarPartida);
|
||||
|
||||
window.location.href = "juego.php?idPartida=" + idPartida;
|
||||
}
|
||||
},
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
$(document).on("click", ".btn-iniciar-partida", function () {
|
||||
const boton = $(this);
|
||||
|
||||
const idPartida = boton.data("id-partida");
|
||||
|
||||
boton.prop("disabled", true);
|
||||
|
||||
boton.html(`
|
||||
<span class="spinner-border spinner-border-sm"></span>
|
||||
Iniciando...
|
||||
`);
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
|
||||
type: "POST",
|
||||
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "iniciar",
|
||||
|
||||
idPartida: idPartida,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false);
|
||||
|
||||
boton.html(`
|
||||
<i class="bi bi-controller"></i>
|
||||
¡Iniciar Partida!
|
||||
`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// El host entra directamente
|
||||
window.location.href = "juego.php?idPartida=" + idPartida;
|
||||
},
|
||||
|
||||
error: function () {
|
||||
alert("Ocurrió un error al iniciar la partida.");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
|
||||
boton.html(`
|
||||
<i class="bi bi-controller"></i>
|
||||
¡Iniciar Partida!
|
||||
`);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on("click", ".btn-unirse-equipo", function () {
|
||||
const boton = $(this);
|
||||
|
||||
const idEquipo = boton.data("id-equipo");
|
||||
const idPartida = boton.data("id-partida");
|
||||
|
||||
boton.prop("disabled", true).text("Uniéndose...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "registrarUsuarioEnEquipo",
|
||||
idEquipo: idEquipo,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
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");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
$(document).on("click", ".btn-abandonar-sala", function () {
|
||||
botonAbandonarReferencia = $(this);
|
||||
|
||||
const esHost =
|
||||
$(this).data("es-host") === true || $(this).data("es-host") === "true";
|
||||
|
||||
const titulo = $("#modalAbandonarSalaLabel");
|
||||
|
||||
const mensaje = $("#modalAbandonarSalaMensaje");
|
||||
|
||||
const botonConfirmar = $("#btnConfirmarAbandonar");
|
||||
|
||||
if (esHost) {
|
||||
titulo.text("¿Abandonar la sala?");
|
||||
|
||||
mensaje.text(
|
||||
"Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.",
|
||||
);
|
||||
|
||||
botonConfirmar.text("Sí, terminar partida");
|
||||
} else {
|
||||
titulo.text("¿Abandonar la sala?");
|
||||
|
||||
mensaje.text("Si sales de la sala, perderás tu lugar en el equipo.");
|
||||
|
||||
botonConfirmar.text("Sí, salir");
|
||||
}
|
||||
|
||||
const modal = new bootstrap.Modal(
|
||||
document.getElementById("modalAbandonarSala"),
|
||||
);
|
||||
|
||||
modal.show();
|
||||
});
|
||||
|
||||
$(document).on("click", "#btnConfirmarAbandonar", function () {
|
||||
const modalEl = document.getElementById("modalAbandonarSala");
|
||||
|
||||
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
||||
|
||||
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");
|
||||
|
||||
if (modalInstance) {
|
||||
modalInstance.hide();
|
||||
}
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
return;
|
||||
}
|
||||
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
if (intervaloSala) {
|
||||
clearInterval(intervaloSala);
|
||||
intervaloSala = null;
|
||||
}
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
$("#contenedorCrearSala").show();
|
||||
|
||||
iniciarActualizacionSalas();
|
||||
},
|
||||
|
||||
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();
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
function escapeHTML(texto) {
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
}
|
||||
|
||||
function mostrarEquipos(partida, equipos, jugadores) {
|
||||
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) {
|
||||
const esHost = jugador.idUsuario == partida.idUsuario;
|
||||
|
||||
jugadoresHTML += `
|
||||
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${
|
||||
esHost ? "jugador-host" : ""
|
||||
}">
|
||||
|
||||
<div>
|
||||
<span class="avatar">
|
||||
${
|
||||
esHost
|
||||
? '<i class="bi bi-award-fill"></i>'
|
||||
: '<i class="bi bi-person-fill"></i>'
|
||||
}
|
||||
</span>
|
||||
|
||||
${escapeHTML(jugador.nombreUsuario)}
|
||||
</div>
|
||||
|
||||
${
|
||||
esHost
|
||||
? `<span class="badge bg-warning text-dark ms-2">
|
||||
HOST
|
||||
</span>`
|
||||
: ""
|
||||
}
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
} else {
|
||||
jugadoresHTML = `
|
||||
<div class="text-muted small">
|
||||
Sin jugadores
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
equiposHTML += `
|
||||
<div class="equipo me-2 ms-2 p-3 border rounded">
|
||||
|
||||
<h6>
|
||||
${escapeHTML(equipo.nombreEquipo)}
|
||||
</h6>
|
||||
|
||||
<div class="jugadores mb-2">
|
||||
${jugadoresHTML}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
$("#contenedorSalas .equipos").html(equiposHTML);
|
||||
}
|
||||
@@ -1,22 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Hay que estar logueado para jugar
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// La partida llega por la URL: juego.php?idPartida=3
|
||||
$idPartida = filter_input(INPUT_GET, 'idPartida', FILTER_VALIDATE_INT);
|
||||
|
||||
if (!$idPartida || $idPartida < 1) {
|
||||
header('Location: buscadorSala.php');
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
@@ -24,28 +8,48 @@ if (!$idPartida || $idPartida < 1) {
|
||||
<title>Proyecto Trivial</title>
|
||||
<link rel="stylesheet" href="css/juego.css">
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
|
||||
</head>
|
||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
||||
|
||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
||||
<body>
|
||||
|
||||
<!-- CABECERA Y PROGRESO -->
|
||||
|
||||
<div class="game-header">
|
||||
<span id="contadorPregunta">Cargando…</span>
|
||||
|
||||
<span id="contadorPregunta">
|
||||
Cargando…
|
||||
</span>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="progress-track">
|
||||
|
||||
<div class="progress-fill" id="barraProgreso"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de la Pregunta (lo rellena js/juego.js) -->
|
||||
<!-- PREGUNTA -->
|
||||
|
||||
<div class="question-container">
|
||||
<div id="textoPregunta">Cargando preguntas…</div>
|
||||
|
||||
<div id="textoPregunta">
|
||||
Cargando preguntas…
|
||||
</div>
|
||||
|
||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
||||
<!-- RESPUESTAS -->
|
||||
|
||||
<div class="answers-grid" id="respuestas"></div>
|
||||
|
||||
<!-- JAVASCRIPT -->
|
||||
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/juego.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
||||
+1476
-2248
File diff suppressed because it is too large
Load Diff
+5
-21
@@ -1,17 +1,3 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Redirección si el usuario no ha iniciado sesión
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: login.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$nombreUsuario = htmlspecialchars($_SESSION['nombreUsuario'] ?? 'Usuario');
|
||||
$avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultProfile.jpeg');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
@@ -41,7 +27,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
|
||||
|
||||
<body>
|
||||
|
||||
<?php include_once 'cabecera.php'; ?>
|
||||
<header id="cabecera-container"></header>
|
||||
|
||||
<div class="perfil-container">
|
||||
|
||||
@@ -61,15 +47,13 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
|
||||
<div class="col-md-6 text-center">
|
||||
|
||||
<!-- Nombre -->
|
||||
<h1 id="nombre" class="nombre">
|
||||
<?= $nombreUsuario ?>
|
||||
</h1>
|
||||
<h1 id="nombre" class="nombre"></h1>
|
||||
|
||||
<!-- FOTO DE PERFIL -->
|
||||
<div class="foto-container">
|
||||
|
||||
<img id="fotoPerfil"
|
||||
src="<?= $avatarUsuario ?>"
|
||||
src="img/avatars/defaultProfile.jpeg"
|
||||
alt="Foto de perfil"
|
||||
class="avatar rounded-circle">
|
||||
|
||||
@@ -293,7 +277,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
|
||||
Cancelar
|
||||
</button>
|
||||
|
||||
<button type="submit" form="formCrearPregunta" class="btn btn-kahoot-login" id="btnCrearPregunta">
|
||||
<button type="submit" form="formCrearPregunta" class="btn btn-kahoot-register" id="btnCrearPregunta">
|
||||
<i class="bi bi-check-lg me-1"></i>
|
||||
Crear pregunta
|
||||
</button>
|
||||
@@ -310,7 +294,7 @@ $avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultPro
|
||||
|
||||
<!-- Tu JavaScript -->
|
||||
<script src="js/perfil.js"></script>
|
||||
|
||||
<script src="js/cabecera.js"></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+16
-11
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once $_SERVER['DOCUMENT_ROOT'] . '/triviagmatico/includes/conexionBD.php';
|
||||
require_once __DIR__ . '/includes/conexionBD.php';
|
||||
|
||||
$idPartida = intval($_GET['idPartida'] ?? 0);
|
||||
if ($idPartida <= 0) {
|
||||
@@ -29,7 +29,7 @@ $primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
|
||||
$jugadoresFinales = [];
|
||||
$equiposFinales = [];
|
||||
|
||||
// Respuestas de velocidad (+2 o +1)
|
||||
// Respuestas de velocidad (+2 o +1) procesadas en la capa de la vista
|
||||
foreach ($listaJugadoresRaw as $jugador) {
|
||||
$idU = (int)$jugador['idUsuario'];
|
||||
$idE = (int)$jugador['idEquipo'];
|
||||
@@ -52,7 +52,6 @@ foreach ($listaJugadoresRaw as $jugador) {
|
||||
$aciertos++;
|
||||
$idPxp = $resp['idPartidaxPregunta'];
|
||||
|
||||
// Si el ID de usuario coincide con el primero guardado de esa pregunta se lleva 2 puntos
|
||||
if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) {
|
||||
$puntosTotalesJugador += 2;
|
||||
} else {
|
||||
@@ -77,7 +76,6 @@ foreach ($listaJugadoresRaw as $jugador) {
|
||||
$equiposFinales[$idE]['puntos'] += $puntosTotalesJugador;
|
||||
}
|
||||
|
||||
// Ordenar según la puntuación final de mayor a menor
|
||||
usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
|
||||
usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
|
||||
?>
|
||||
@@ -88,19 +86,24 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Resultados - Trivial</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<link rel="stylesheet" href="css/resultados.css">
|
||||
<script src="https://jquery.com"></script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
</head>
|
||||
<body data-id-partida="<?php echo $idPartida; ?>">
|
||||
|
||||
<div id="pantalla-espera" class="contenedor">
|
||||
<h2>⌛ Esperando a que todos los jugadores terminen...</h2>
|
||||
<h2> <i class="bi bi-hourglass"></i> Esperando a que todos los jugadores terminen...</h2>
|
||||
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
|
||||
<div class="loader"></div>
|
||||
</div>
|
||||
|
||||
<div id="pantalla-resultados" class="contenedor" style="display:none;">
|
||||
<h1>🏆 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>
|
||||
<table class="tabla-ranking">
|
||||
@@ -146,11 +149,13 @@ usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos'];
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div class="contenedor-boton">
|
||||
<a href="/triviagmatico/buscadorSala.php" class="btn-inicio">Volver al Inicio 🏠</a>
|
||||
</div>
|
||||
|
||||
<div class="contenedor-boton">
|
||||
<a href="<?= $_ENV['urlBase'] ?>/" id="btnVolverInicio" data-id="<?php echo $idPartida; ?>" class="btn btn-play-kahoot"> <i class="bi bi-arrow-left"></i> Volver al Inicio <i class="bi bi-house-fill"></i> </a>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="js/resultados.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
bDatosServer="localhost"
|
||||
bDatos="my_webapp"
|
||||
bDatosUser="my_webapp"
|
||||
bDatosPass="07tCqBO3B6Q3cncKMF2FHcpgsLjFTx"
|
||||
urlBase="http://triviagmatico.test"
|
||||
dirBase="/var/www/my_webapp/www"
|
||||
Reference in New Issue
Block a user