Compare commits
19 Commits
07c1f79474
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 30dd4a0e2f | |||
| bdebd32f80 | |||
| 49f950bbd0 | |||
| b8f977e437 | |||
| c8c0792bd7 | |||
| 534c20a45d | |||
| c8199aa261 | |||
| f5a354025e | |||
| 449cb1d976 | |||
| 94bfe480cb | |||
| 7661343572 | |||
| e97586b033 | |||
| 14e2fd48a1 | |||
| 42cc1489e9 | |||
| a694f19667 | |||
| 3cc0dfb122 | |||
| 4efb831b7a | |||
| 22f38f924f | |||
| 01aa2643f6 |
+49
-154
@@ -4,24 +4,20 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<title>Trivial - Lobby</title>
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet">
|
||||
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="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">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php
|
||||
include_once("cabecera.php");
|
||||
?>
|
||||
<?php include_once("cabecera.php"); ?>
|
||||
|
||||
<main class="container py-4">
|
||||
|
||||
<main class="container py-5">
|
||||
<!-- Botón Volver -->
|
||||
<div class="mb-4">
|
||||
<a href="index.php" class="btn btn-outline-secondary d-inline-flex align-items-center gap-2">
|
||||
@@ -31,181 +27,80 @@
|
||||
Volver al Inicio
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Botón Crear Sala -->
|
||||
<div id="contenedorCrearSala" class="text-center mb-5">
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-play-kahoot btn-crear-sala"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalCrearSala">
|
||||
|
||||
<span>+</span>
|
||||
Crear sala
|
||||
|
||||
<button type="button" class="btn btn-play-kahoot btn-crear-sala" data-bs-toggle="modal" data-bs-target="#modalCrearSala">
|
||||
<span>+</span> Crear sala
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="contenedorSalas"
|
||||
class="row justify-content-center g-4">
|
||||
|
||||
<div
|
||||
id="cargandoSalas"
|
||||
class="col-12 text-center">
|
||||
|
||||
<div
|
||||
class="spinner-border text-primary"
|
||||
role="status">
|
||||
|
||||
<span class="visually-hidden">
|
||||
Cargando...
|
||||
</span>
|
||||
|
||||
<!-- Contenedor Principal de Salas -->
|
||||
<div id="contenedorSalas" class="row justify-content-center g-4">
|
||||
<div id="cargandoSalas" class="col-12 text-center">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Cargando...</span>
|
||||
</div>
|
||||
|
||||
<p class="mt-3 text-muted">
|
||||
Cargando salas...
|
||||
</p>
|
||||
|
||||
<p class="mt-3 text-muted">Cargando salas...</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
<!-- Modal Crear Sala -->
|
||||
<div
|
||||
class="modal fade"
|
||||
id="modalCrearSala"
|
||||
tabindex="-1"
|
||||
aria-labelledby="modalCrearSalaLabel"
|
||||
aria-hidden="true">
|
||||
|
||||
<div class="modal fade" id="modalCrearSala" tabindex="-1" aria-labelledby="modalCrearSalaLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
|
||||
<div class="modal-content modal-kahoot">
|
||||
|
||||
<div class="modal-header modal-kahoot-header">
|
||||
|
||||
<h5
|
||||
class="modal-title"
|
||||
id="modalCrearSalaLabel">
|
||||
|
||||
Crear sala
|
||||
|
||||
</h5>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn-close btn-close-white"
|
||||
data-bs-dismiss="modal"
|
||||
aria-label="Cerrar">
|
||||
</button>
|
||||
|
||||
<h5 class="modal-title" id="modalCrearSalaLabel">Crear sala</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body p-4">
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreSala"
|
||||
class="form-label">
|
||||
|
||||
Nombre de la sala
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreSala"
|
||||
class="form-control input-kahoot"
|
||||
name="nombreSala"
|
||||
placeholder="Ej. Noche de Trivial"
|
||||
maxlength="100">
|
||||
|
||||
<label for="nombreSala" class="form-label">Nombre de la sala</label>
|
||||
<input type="text" id="nombreSala" class="form-control input-kahoot" name="nombreSala" placeholder="Ej. Noche de Trivial" maxlength="100">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreEquipo1"
|
||||
class="form-label">
|
||||
|
||||
Nombre del equipo 1
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreEquipo1"
|
||||
name="nombreEquipo1"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Ej. Los cerebritos"
|
||||
maxlength="50">
|
||||
|
||||
<label for="nombreEquipo1" class="form-label">Nombre del equipo 1</label>
|
||||
<input type="text" id="nombreEquipo1" name="nombreEquipo1" class="form-control input-kahoot" placeholder="Ej. Los cerebritos" maxlength="50">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="nombreEquipo2"
|
||||
class="form-label">
|
||||
|
||||
Nombre del equipo 2
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
id="nombreEquipo2"
|
||||
name="nombreEquipo2"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Ej. Los campeones"
|
||||
maxlength="50">
|
||||
|
||||
<label for="nombreEquipo2" class="form-label">Nombre del equipo 2</label>
|
||||
<input type="text" id="nombreEquipo2" name="nombreEquipo2" class="form-control input-kahoot" placeholder="Ej. Los campeones" maxlength="50">
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div class="modal-footer">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
data-bs-dismiss="modal">
|
||||
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="button" class="btn btn-kahoot-login" id="btnCrearSala">Crear sala</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!--MODAL ABANDONAR SALA -->
|
||||
<!-- Modal Confirmar Abandonar Sala -->
|
||||
<div class="modal fade" id="modalAbandonarSala" tabindex="-1" aria-labelledby="modalAbandonarSalaLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content modal-kahoot text-center p-3">
|
||||
<div class="modal-body">
|
||||
<div class="mb-3 fs-1">⚠️</div>
|
||||
<h4 class="modal-title mb-2 fw-bold" id="modalAbandonarSalaLabel">¿Abandonar la sala?</h4>
|
||||
<p class="text-dark-50" id="modalAbandonarSalaMensaje">Si sales de la sala, perderás tu lugar en el equipo.</p>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-center border-0 gap-2">
|
||||
<button type="button" class="btn btn-secondary px-4 py-2" data-bs-dismiss="modal">
|
||||
Cancelar
|
||||
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-kahoot-login"
|
||||
id="btnCrearSala">
|
||||
|
||||
Crear sala
|
||||
|
||||
<button type="button" id="btnConfirmarAbandonar" class="btn btn-danger px-4 py-2">
|
||||
Sí, salir
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script
|
||||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js">
|
||||
</script>
|
||||
|
||||
<script src="js/jquery.min.js"></script>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/buscadorSala.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
+9
-8
@@ -21,9 +21,8 @@
|
||||
<div class="collapse navbar-collapse" id="navbarContent">
|
||||
<ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
|
||||
|
||||
<!-- Adtoy ti pagianan ti botones / dropdown a patulaon ti JS -->
|
||||
<!-- Contenedor dinámico cargado por js/cabecera.js -->
|
||||
<div class="d-flex align-items-center gap-3" id="contenedorUsuarioCabecera">
|
||||
<!-- Ikapit ti JS ti HTML dita -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -49,11 +48,6 @@
|
||||
<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>
|
||||
@@ -93,7 +87,14 @@
|
||||
<input type="password" class="form-control border-dark" id="regPasswordConfirm" name="contrasenaConfirm" placeholder="Confirmar contraseña" required>
|
||||
<label for="regPasswordConfirm">Confirmar contraseña</label>
|
||||
</div>
|
||||
<input type="hidden" name="orden" value="registrar">
|
||||
|
||||
<!-- Checkbox Recuérdame -->
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input border-dark" type="checkbox" value="" id="recuerdameCheck">
|
||||
<label class="form-check-label fw-semibold" for="recuerdameCheck">
|
||||
Recuérdame en 10 días
|
||||
</label>
|
||||
</div>
|
||||
</form>
|
||||
<div id="errorRegistro" class="text-danger fw-bold mt-2"></div>
|
||||
</div>
|
||||
|
||||
+127
-10
@@ -60,6 +60,7 @@ class EquipoxUsuario
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function obtenerSalaUsuario($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
@@ -108,7 +109,6 @@ class EquipoxUsuario
|
||||
'idEquipo' => $resultado['idEquipo'],
|
||||
'idPartida' => $resultado['idPartida']
|
||||
];
|
||||
|
||||
} catch (PDOException $error) {
|
||||
|
||||
return [
|
||||
@@ -118,8 +118,6 @@ class EquipoxUsuario
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static function salirDeSala($idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
@@ -129,24 +127,143 @@ public static function salirDeSala($idUsuario)
|
||||
}
|
||||
|
||||
try {
|
||||
$sql = "DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario";
|
||||
|
||||
// 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,
|
||||
'mensaje' => 'Usuario eliminado de la sala correctamente.'
|
||||
'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 salir de la sala.',
|
||||
'error' => 'Ocurrió un error al abandonar la sala.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
require_once __DIR__ . '/ClaseRespuestaAlmacenada.php';
|
||||
|
||||
/**
|
||||
* Lógica de la dinámica de juego (la usa juego.php a través de ControladorJuego.php):
|
||||
* - deja preparadas las 10 preguntas de la partida
|
||||
* - se las devuelve al jugador con sus respuestas SIN decir cuál es la correcta
|
||||
* - guarda la respuesta de cada jugador y le dice si ha acertado
|
||||
*
|
||||
* Todos los métodos devuelven un array con la clave 'error' si algo falla,
|
||||
* igual que el resto de clases del proyecto.
|
||||
*/
|
||||
class Juego
|
||||
{
|
||||
const NUM_PREGUNTAS = 10;
|
||||
|
||||
/**
|
||||
* Comprueba que el usuario pertenece a alguno de los equipos de la partida.
|
||||
* Devuelve true/false (o el array de error si falla la BD).
|
||||
*/
|
||||
public static function usuarioEnPartida($idPartida, $idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) AS total
|
||||
FROM equipoxpartida exp
|
||||
INNER JOIN equipoxusuario exu
|
||||
ON exu.idEquipo = exp.idEquipo
|
||||
WHERE exp.idPartida = :idPartida
|
||||
AND exu.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
return (int)$consulta->fetchColumn() > 0;
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al comprobar si perteneces a la partida.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Si la partida todavía no tiene preguntas, le asigna 10 al azar.
|
||||
* Se hace dentro de una transacción con la fila de la partida bloqueada
|
||||
* para que, si varios jugadores entran a la vez, las preguntas se
|
||||
* asignen una sola vez.
|
||||
* Devuelve null si todo va bien, o un array de error.
|
||||
*/
|
||||
private static function asegurarPreguntas($conexion, $idPartida)
|
||||
{
|
||||
try {
|
||||
$conexion->beginTransaction();
|
||||
|
||||
$bloqueo = $conexion->prepare("
|
||||
SELECT idPartida FROM partida
|
||||
WHERE idPartida = :idPartida
|
||||
FOR UPDATE
|
||||
");
|
||||
$bloqueo->execute([':idPartida' => $idPartida]);
|
||||
|
||||
if (!$bloqueo->fetch()) {
|
||||
$conexion->rollBack();
|
||||
return ['error' => 'La partida no existe.'];
|
||||
}
|
||||
|
||||
$cuenta = $conexion->prepare("
|
||||
SELECT COUNT(*) FROM partidaxpregunta
|
||||
WHERE idPartida = :idPartida
|
||||
");
|
||||
$cuenta->execute([':idPartida' => $idPartida]);
|
||||
|
||||
if ((int)$cuenta->fetchColumn() === 0) {
|
||||
|
||||
// Solo preguntas que tengan alguna respuesta marcada como correcta
|
||||
$elegidas = $conexion->query("
|
||||
SELECT p.idPregunta
|
||||
FROM pregunta p
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM respuesta r
|
||||
WHERE r.idPregunta = p.idPregunta
|
||||
AND r.correcta = 1
|
||||
)
|
||||
ORDER BY RAND()
|
||||
LIMIT " . self::NUM_PREGUNTAS
|
||||
)->fetchAll(PDO::FETCH_COLUMN);
|
||||
|
||||
$insertar = $conexion->prepare("
|
||||
INSERT INTO partidaxpregunta (idPartida, idPregunta)
|
||||
VALUES (:idPartida, :idPregunta)
|
||||
");
|
||||
foreach ($elegidas as $idPregunta) {
|
||||
$insertar->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idPregunta' => $idPregunta
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$conexion->commit();
|
||||
return null;
|
||||
} catch (PDOException $error) {
|
||||
if ($conexion->inTransaction()) {
|
||||
$conexion->rollBack();
|
||||
}
|
||||
return [
|
||||
'error' => 'Ocurrió un error al preparar las preguntas de la partida.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve las preguntas de la partida (máximo 10) con sus respuestas
|
||||
* mezcladas. NO incluye el campo 'correcta' para que no se pueda hacer
|
||||
* trampa mirando la respuesta del servidor.
|
||||
* Cada pregunta indica si este usuario ya la ha respondido, para poder
|
||||
* retomar la partida si recarga la página.
|
||||
*/
|
||||
public static function cargarPreguntas($idPartida, $idUsuario)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
$error = self::asegurarPreguntas($conexion, $idPartida);
|
||||
if ($error !== null) {
|
||||
return $error;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. Las preguntas, siempre en el mismo orden para todos los jugadores
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT
|
||||
pxp.idPartidaxPregunta,
|
||||
p.idPregunta,
|
||||
p.nombrePregunta
|
||||
FROM partidaxpregunta pxp
|
||||
INNER JOIN pregunta p
|
||||
ON p.idPregunta = pxp.idPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
ORDER BY pxp.idPartidaxPregunta
|
||||
LIMIT " . self::NUM_PREGUNTAS
|
||||
);
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
$preguntas = $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||
|
||||
// 2. Las respuestas de todas esas preguntas, agrupadas por pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT DISTINCT
|
||||
r.idRespuesta,
|
||||
r.idPregunta,
|
||||
r.nombreRespuesta
|
||||
FROM respuesta r
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPregunta = r.idPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
|
||||
$respuestasPorPregunta = [];
|
||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
||||
$respuestasPorPregunta[(int)$fila['idPregunta']][] = [
|
||||
'idRespuesta' => (int)$fila['idRespuesta'],
|
||||
'nombreRespuesta' => $fila['nombreRespuesta']
|
||||
];
|
||||
}
|
||||
|
||||
// 3. Qué preguntas ha respondido ya este usuario
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT ra.idPartidaxPregunta
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
AND ra.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
$respondidas = array_flip($consulta->fetchAll(PDO::FETCH_COLUMN));
|
||||
|
||||
// 4. Montamos la respuesta final
|
||||
$resultado = [];
|
||||
foreach ($preguntas as $pregunta) {
|
||||
$idPregunta = (int)$pregunta['idPregunta'];
|
||||
$idPxp = (int)$pregunta['idPartidaxPregunta'];
|
||||
|
||||
$respuestas = $respuestasPorPregunta[$idPregunta] ?? [];
|
||||
shuffle($respuestas);
|
||||
|
||||
$resultado[] = [
|
||||
'idPartidaxPregunta' => $idPxp,
|
||||
'idPregunta' => $idPregunta,
|
||||
'nombrePregunta' => $pregunta['nombrePregunta'],
|
||||
'respondida' => isset($respondidas[$idPxp]),
|
||||
'respuestas' => $respuestas
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'total' => count($resultado),
|
||||
'respondidas' => count($respondidas),
|
||||
'preguntas' => $resultado
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al cargar las preguntas.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Guarda la respuesta que ha elegido el usuario en una pregunta y
|
||||
* devuelve si ha acertado y cuál era la correcta (para el feedback).
|
||||
* Comprueba en el servidor que:
|
||||
* - la pregunta pertenece a la partida
|
||||
* - la respuesta pertenece a esa pregunta
|
||||
* - el usuario no ha respondido ya esa pregunta
|
||||
*/
|
||||
public static function registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta)
|
||||
{
|
||||
$conexion = conexionBD();
|
||||
if (is_array($conexion)) {
|
||||
return $conexion;
|
||||
}
|
||||
|
||||
try {
|
||||
// 1. La pregunta tiene que ser de esta partida
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT idPregunta
|
||||
FROM partidaxpregunta
|
||||
WHERE idPartidaxPregunta = :idPxp
|
||||
AND idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPxp' => $idPartidaxPregunta,
|
||||
':idPartida' => $idPartida
|
||||
]);
|
||||
$idPregunta = $consulta->fetchColumn();
|
||||
|
||||
if ($idPregunta === false) {
|
||||
return ['error' => 'Esa pregunta no pertenece a esta partida.'];
|
||||
}
|
||||
|
||||
// 2. La respuesta tiene que ser una de las de esa pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT idRespuesta, correcta
|
||||
FROM respuesta
|
||||
WHERE idPregunta = :idPregunta
|
||||
");
|
||||
$consulta->execute([':idPregunta' => $idPregunta]);
|
||||
|
||||
$elegida = null;
|
||||
$primeraCorrecta = null;
|
||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
||||
if ((int)$fila['correcta'] === 1 && $primeraCorrecta === null) {
|
||||
$primeraCorrecta = (int)$fila['idRespuesta'];
|
||||
}
|
||||
if ((int)$fila['idRespuesta'] === $idRespuesta) {
|
||||
$elegida = $fila;
|
||||
}
|
||||
}
|
||||
|
||||
if ($elegida === null) {
|
||||
return ['error' => 'Esa respuesta no pertenece a la pregunta.'];
|
||||
}
|
||||
|
||||
// 3. Solo se puede responder una vez a cada pregunta
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada
|
||||
WHERE idPartidaxPregunta = :idPxp
|
||||
AND idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPxp' => $idPartidaxPregunta,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
|
||||
if ((int)$consulta->fetchColumn() > 0) {
|
||||
return ['error' => 'Ya has respondido a esta pregunta.'];
|
||||
}
|
||||
|
||||
// 4. Guardamos la respuesta con la clase que ya existía
|
||||
$almacenada = new RespuestaAlmacenada(
|
||||
null,
|
||||
$idPartidaxPregunta,
|
||||
$idUsuario,
|
||||
$idRespuesta
|
||||
);
|
||||
$guardado = $almacenada->guardarRespuesta();
|
||||
|
||||
if (isset($guardado['error'])) {
|
||||
return $guardado;
|
||||
}
|
||||
|
||||
// 5. Progreso del usuario en la partida
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*)
|
||||
FROM respuestaalmacenada ra
|
||||
INNER JOIN partidaxpregunta pxp
|
||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
||||
WHERE pxp.idPartida = :idPartida
|
||||
AND ra.idUsuario = :idUsuario
|
||||
");
|
||||
$consulta->execute([
|
||||
':idPartida' => $idPartida,
|
||||
':idUsuario' => $idUsuario
|
||||
]);
|
||||
$respondidas = (int)$consulta->fetchColumn();
|
||||
|
||||
$consulta = $conexion->prepare("
|
||||
SELECT COUNT(*) FROM partidaxpregunta
|
||||
WHERE idPartida = :idPartida
|
||||
");
|
||||
$consulta->execute([':idPartida' => $idPartida]);
|
||||
$total = min((int)$consulta->fetchColumn(), self::NUM_PREGUNTAS);
|
||||
|
||||
$acierto = (int)$elegida['correcta'] === 1;
|
||||
|
||||
return [
|
||||
'exito' => 'Respuesta guardada.',
|
||||
'acierto' => $acierto,
|
||||
'idRespuestaCorrecta' => $acierto ? $idRespuesta : $primeraCorrecta,
|
||||
'respondidas' => $respondidas,
|
||||
'total' => $total,
|
||||
'terminada' => $respondidas >= $total
|
||||
];
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'Ocurrió un error al guardar la respuesta.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
@@ -466,4 +467,25 @@ class Partida
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
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,3 +1,4 @@
|
||||
|
||||
<?php
|
||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
||||
|
||||
@@ -110,4 +111,22 @@ class Pregunta {
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,7 @@ switch ($_POST['orden']) {
|
||||
|
||||
break;
|
||||
|
||||
|
||||
case 'salirDeSala':
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Usuario no autenticado']);
|
||||
@@ -86,5 +87,4 @@ switch ($_POST['orden']) {
|
||||
|
||||
echo json_encode($respuesta);
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
session_start();
|
||||
|
||||
require_once '../clases/ClaseJuego.php';
|
||||
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// Hay que estar logueado y decir de qué partida se trata
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
||||
|
||||
if ($idPartida <= 0) {
|
||||
echo json_encode(['error' => 'No se ha indicado la partida.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Solo pueden jugar los usuarios que están en uno de los equipos de la partida
|
||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida, $idUsuario);
|
||||
|
||||
if (is_array($perteneceAPartida)) {
|
||||
echo json_encode($perteneceAPartida);
|
||||
exit;
|
||||
}
|
||||
|
||||
if (!$perteneceAPartida) {
|
||||
echo json_encode(['error' => 'No formas parte de esta partida.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
switch ($_POST['orden'] ?? '') {
|
||||
|
||||
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
|
||||
case 'cargarPreguntas':
|
||||
|
||||
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
|
||||
|
||||
break;
|
||||
|
||||
|
||||
// Guarda la respuesta del usuario y dice si ha acertado
|
||||
case 'responder':
|
||||
|
||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta'] ?? 0);
|
||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
||||
|
||||
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0) {
|
||||
echo json_encode(['error' => 'Faltan datos para registrar la respuesta.']);
|
||||
break;
|
||||
}
|
||||
|
||||
echo json_encode(
|
||||
Juego::registrarRespuesta(
|
||||
$idPartida,
|
||||
$idUsuario,
|
||||
$idPartidaxPregunta,
|
||||
$idRespuesta
|
||||
)
|
||||
);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
// Recibe los aciertos del jugador al terminar sus 10 preguntas,
|
||||
// para que resultados.php los pueda usar al montar la hoja de resultados
|
||||
case 'finalizarPartida':
|
||||
|
||||
$aciertos = intval($_POST['aciertos'] ?? 0);
|
||||
|
||||
if (!isset($_SESSION['aciertosPorPartida'])) {
|
||||
$_SESSION['aciertosPorPartida'] = [];
|
||||
}
|
||||
|
||||
$_SESSION['aciertosPorPartida'][$idPartida] = $aciertos;
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Aciertos registrados correctamente.',
|
||||
'idPartida' => $idPartida,
|
||||
'aciertos' => $aciertos
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
|
||||
default:
|
||||
|
||||
echo json_encode(['error' => 'La orden indicada no existe.']);
|
||||
|
||||
break;
|
||||
}
|
||||
@@ -6,6 +6,7 @@ require_once '../clases/ClasePartida.php';
|
||||
require_once '../clases/ClaseEquipo.php';
|
||||
require_once '../clases/ClaseEquipoxUsuario.php';
|
||||
require_once '../clases/ClaseEquipoxPartida.php';
|
||||
require_once '../clases/ClasePregunta.php';
|
||||
|
||||
|
||||
switch ($_POST['orden']) {
|
||||
@@ -119,6 +120,7 @@ switch ($_POST['orden']) {
|
||||
}
|
||||
|
||||
$idPartida = (int)$resultadoPartida['exito_tecnico'];
|
||||
$partida->idPartida = $idPartida;
|
||||
|
||||
|
||||
/*
|
||||
@@ -211,6 +213,42 @@ switch ($_POST['orden']) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* 5. ASIGNAMOS 10 PREGUNTAS ALEATORIAS A LA PARTIDA
|
||||
* ==========================================
|
||||
*/
|
||||
|
||||
// Obtenemos todos los IDs de las preguntas
|
||||
|
||||
$listaPreguntas = Pregunta::getTodosIds();
|
||||
|
||||
$totalPreguntas = count($listaPreguntas);
|
||||
|
||||
// Guardamos las preguntas que ya hemos asignado
|
||||
$preguntasAsignadas = [];
|
||||
|
||||
// Generamos 10 posiciones aleatorias sin repetir
|
||||
while (count($preguntasAsignadas) < 10) {
|
||||
|
||||
// Generamos una posición aleatoria del array
|
||||
$posicionAleatoria = rand(0, $totalPreguntas - 1);
|
||||
|
||||
// Obtenemos el ID real de la pregunta
|
||||
$idPreguntaAleatoria = $listaPreguntas[$posicionAleatoria];
|
||||
|
||||
// Comprobamos que esa pregunta no haya sido asignada ya
|
||||
if (!in_array($idPreguntaAleatoria, $preguntasAsignadas)) {
|
||||
$preguntasAsignadas[] = $idPreguntaAleatoria;
|
||||
|
||||
// Asignamos el ID real de la pregunta a la partida
|
||||
$partida->asignarPregunta($idPreguntaAleatoria);
|
||||
}
|
||||
}//fin shile
|
||||
|
||||
|
||||
/*
|
||||
* ==========================================
|
||||
* TODO CORRECTO
|
||||
@@ -218,7 +256,7 @@ switch ($_POST['orden']) {
|
||||
*/
|
||||
|
||||
echo json_encode([
|
||||
'exito' => 'Sala creada correctamente.',
|
||||
'exito' => 'Sala creada correctamente. Preguntas preparadas.',
|
||||
'idPartida' => $resultadoPartida['exito_tecnico'],
|
||||
'idEquipo1' => $equipo1->idEquipo,
|
||||
'idEquipo2' => $equipo2->idEquipo
|
||||
|
||||
@@ -55,10 +55,11 @@ switch ($_POST['orden']) {
|
||||
|
||||
if ($resultado instanceof Usuario) {
|
||||
|
||||
// === AÑADIR ESTAS LÍNEAS PARA GUARDAR EN SESIÓN ===
|
||||
// === GUARDAR EN SESIÓN (incluido avatar)===
|
||||
$_SESSION['idUsuario'] = $resultado->getIdUsuario();
|
||||
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
||||
$_SESSION['email'] = $resultado->getEmail();
|
||||
$_SESSION['avatar'] = $resultado->getAvatar();
|
||||
// =================================================
|
||||
|
||||
echo json_encode([
|
||||
@@ -83,6 +84,7 @@ switch ($_POST['orden']) {
|
||||
unset($_SESSION['idUsuario']);
|
||||
unset($_SESSION['email']);
|
||||
unset($_SESSION['nombreUsuario']);
|
||||
unset($_SESSION['avatar']);
|
||||
|
||||
// Destruimos la sesión
|
||||
session_destroy();
|
||||
@@ -92,7 +94,6 @@ switch ($_POST['orden']) {
|
||||
]);
|
||||
|
||||
break;
|
||||
|
||||
case 'mostrarEstadisticas':
|
||||
|
||||
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
||||
@@ -242,7 +243,8 @@ switch ($_POST['orden']) {
|
||||
'activa' => true,
|
||||
'usuario' => [
|
||||
'idUsuario' => $_SESSION['idUsuario'],
|
||||
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? ''
|
||||
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? '',
|
||||
'avatar' => $_SESSION['avatar'] ?? ''
|
||||
]
|
||||
]);
|
||||
} else {
|
||||
|
||||
+10
-2
@@ -68,8 +68,8 @@
|
||||
|
||||
.btn-unirse {
|
||||
border: none;
|
||||
border-bottom: 3px solid #0c4891;
|
||||
background-color: var(--kahoot-blue);
|
||||
border-bottom: 3px solid #1f6f09;
|
||||
background-color: #26890c;
|
||||
color: white;
|
||||
font-weight: 600;
|
||||
border-radius: 8px;
|
||||
@@ -105,3 +105,11 @@
|
||||
border-color: var(--kahoot-purple);
|
||||
box-shadow: 0 0 0 3px rgba(70, 23, 143, 0.15);
|
||||
}
|
||||
|
||||
.jugador-host {
|
||||
background-color: #fff3cd;
|
||||
border: 1px solid #ffc107;
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@@ -117,3 +117,65 @@
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Lógica de juego (js/juego.js) ===== */
|
||||
|
||||
.game-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
height: 8px;
|
||||
background-color: #ddd;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
background-color: #1368ce;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
.feedback {
|
||||
min-height: 1.5em;
|
||||
margin-top: 12px;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.feedback.ok { color: #26890c; }
|
||||
.feedback.ko { color: #e21b3c; }
|
||||
|
||||
/* Mientras se envía la respuesta o se ve el feedback no se puede volver a pulsar */
|
||||
.answers-grid.bloqueado .btn-answer {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.btn-answer.correcta {
|
||||
box-shadow: 0 0 0 6px #fff, 0 0 0 10px #26890c;
|
||||
}
|
||||
|
||||
.btn-answer.incorrecta,
|
||||
.btn-answer.atenuada {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
.btn-answer:focus-visible {
|
||||
outline: 4px solid #333;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.progress-fill,
|
||||
.btn-answer {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.9 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 19 KiB |
+19
-22
@@ -1,29 +1,26 @@
|
||||
<?php
|
||||
//CARGA DE ARCHIVOS .ENV CON PHPDOTENV
|
||||
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();
|
||||
|
||||
function conexionBD (){
|
||||
// Configuración para Laragon
|
||||
$servidor = "localhost";
|
||||
$bd = "triviagmatico"; // Asegúrate de que este sea el nombre de tu BD en HeidiSQL / phpMyAdmin
|
||||
$usuario = "root";
|
||||
$pass = ""; // Laragon deja la contraseña de root vacía por defecto
|
||||
$puerto = "3306";
|
||||
|
||||
try{
|
||||
$dsn = "mysql:host=$servidor;port=$puerto;dbname=$bd;charset=utf8mb4";
|
||||
|
||||
$opciones = [
|
||||
$servidor = 'mysql:host='.$_ENV['bDatosServer'].';dbname='.$_ENV['bDatos'];
|
||||
$user=$_ENV['bDatosUser'];
|
||||
$password=$_ENV['bDatosPass'];
|
||||
$options=array(
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
];
|
||||
|
||||
return new PDO($dsn, $usuario, $pass, $opciones);
|
||||
|
||||
} catch (PDOException $error) {
|
||||
return [
|
||||
'error' => 'No se pudo conectar a la base de datos.',
|
||||
'error_tecnico' => $error->getMessage()
|
||||
];
|
||||
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
|
||||
);
|
||||
//Creamos la conexión PDO a la base de datos
|
||||
$pdo = new PDO($servidor, $user, $password, $options);
|
||||
}
|
||||
catch(PDOException $e){
|
||||
//$resultado = ['error' => $e->getMessage()];
|
||||
$resultado = ['error' => 'Error Temporal: No se puede conectar con la base de datos.'];
|
||||
return $resultado;
|
||||
}
|
||||
|
||||
return $pdo;
|
||||
}
|
||||
?>
|
||||
@@ -1,7 +1,3 @@
|
||||
<?php
|
||||
include 'cabecera.php';
|
||||
?>
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="es-ES">
|
||||
|
||||
@@ -9,16 +5,17 @@ include 'cabecera.php';
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Triviagmático</title>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<?php include 'cabecera.php'; ?>
|
||||
|
||||
<div class="container my-5">
|
||||
<div class="row justify-content-center align-items-center g-4">
|
||||
|
||||
<!-- Botón Jugar (oculto por defecto, JS lo muestra si hay sesión) -->
|
||||
<!-- Botón Jugar (oculto por defecto, JS lo muestra si hay sesión activa) -->
|
||||
<div class="col-12 col-lg-5 col-xl-4 d-none" id="colBotonJugar">
|
||||
<a href="buscadorSala.php" class="btn btn-play-kahoot" id="btnJugar">
|
||||
<i class="fa-solid fa-play"></i>
|
||||
|
||||
+168
-221
@@ -4,6 +4,7 @@ $(document).ready(function () {
|
||||
comprobarSalaUsuario();
|
||||
});
|
||||
|
||||
// 1. Comprobar si el usuario actual ya pertenece a una sala
|
||||
function comprobarSalaUsuario() {
|
||||
$("#cargandoSalas").remove();
|
||||
|
||||
@@ -11,101 +12,64 @@ function comprobarSalaUsuario() {
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "obtenerSalaUsuario",
|
||||
},
|
||||
|
||||
data: { orden: "obtenerSalaUsuario" },
|
||||
success: function (respuesta) {
|
||||
console.log("Sala del usuario:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
console.error(respuesta.error);
|
||||
|
||||
if (respuesta.error || !respuesta.asociado) {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
$("#contenedorCrearSala").show();
|
||||
cargarSalas();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (respuesta.asociado) {
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
|
||||
cargarSalaUsuario(respuesta.idPartida);
|
||||
} else {
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
cargarSalas();
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
$("#contenedorCrearSala").hide(); // Ocultar "Crear Sala" si ya pertenece a una
|
||||
cargarSalaUsuario(respuesta.idPartida);
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al comprobar la sala del usuario:", error);
|
||||
|
||||
usuarioYaEstaEnEquipo = false;
|
||||
|
||||
cargarSalas();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Cargar únicamente la sala en la que está metido el usuario
|
||||
function cargarSalaUsuario(idPartida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "buscar",
|
||||
idPartida: idPartida,
|
||||
},
|
||||
|
||||
data: { orden: "buscar", idPartida: idPartida },
|
||||
success: function (partida) {
|
||||
if (partida.error) {
|
||||
console.error(partida.error);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
cargarInformacionSala(partida);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener la sala del usuario:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Cargar la lista completa de todas las salas
|
||||
function cargarSalas() {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "listar",
|
||||
},
|
||||
|
||||
data: { orden: "listar" },
|
||||
success: function (partidas) {
|
||||
const contenedor = $("#contenedorSalas");
|
||||
|
||||
contenedor.empty();
|
||||
contenedor.empty();
|
||||
|
||||
if (!Array.isArray(partidas) || partidas.length === 0) {
|
||||
contenedor.html(`
|
||||
<div class="col-12 text-center">
|
||||
<p class="text-muted">
|
||||
No hay salas disponibles.
|
||||
</p>
|
||||
<p class="text-muted">No hay salas disponibles actualmente.</p>
|
||||
</div>
|
||||
`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -113,54 +77,42 @@ function cargarSalas() {
|
||||
cargarInformacionSala(partida);
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener las partidas:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 4. Obtener equipos y jugadores asociados a una sala concreta
|
||||
function cargarInformacionSala(partida) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getEquipos",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
data: { orden: "getEquipos", idPartida: partida.idPartida },
|
||||
success: function (equipos) {
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "getJugadores",
|
||||
idPartida: partida.idPartida,
|
||||
},
|
||||
|
||||
data: { orden: "getJugadores", idPartida: partida.idPartida },
|
||||
success: function (jugadores) {
|
||||
mostrarSala(partida, equipos, jugadores);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener jugadores:", error);
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al obtener equipos:", error);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 5. Renderizar el HTML de la sala y botones según estado
|
||||
function mostrarSala(partida, equipos, jugadores) {
|
||||
const contenedor = $("#contenedorSalas");
|
||||
|
||||
let equiposHTML = "";
|
||||
|
||||
equipos.forEach(function (equipo) {
|
||||
@@ -169,229 +121,249 @@ function mostrarSala(partida, equipos, jugadores) {
|
||||
});
|
||||
|
||||
let jugadoresHTML = "";
|
||||
|
||||
if (jugadoresEquipo.length > 0) {
|
||||
jugadoresEquipo.forEach(function (jugador) {
|
||||
const esHost = jugador.idUsuario == partida.idUsuario;
|
||||
|
||||
jugadoresHTML += `
|
||||
<div class="jugador">
|
||||
|
||||
<span class="avatar">
|
||||
👤
|
||||
</span>
|
||||
|
||||
<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>
|
||||
`;
|
||||
jugadoresHTML = `<div class="text-muted small">Sin jugadores</div>`;
|
||||
}
|
||||
|
||||
// Botón "Unirse" solo visible si NO pertenece a ningún equipo
|
||||
let botonUnirseHTML = "";
|
||||
|
||||
if (!usuarioYaEstaEnEquipo) {
|
||||
botonUnirseHTML = `
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-unirse w-100 btn-unirse-equipo"
|
||||
<button type="button" class="btn-unirse w-100 btn-unirse-equipo mt-2"
|
||||
data-id-partida="${partida.idPartida}"
|
||||
data-id-equipo="${equipo.idEquipo}">
|
||||
|
||||
Unirse
|
||||
|
||||
</button>
|
||||
`;
|
||||
}
|
||||
|
||||
equiposHTML += `
|
||||
<div class="equipo">
|
||||
|
||||
<h6>
|
||||
${escapeHTML(equipo.nombreEquipo)}
|
||||
</h6>
|
||||
|
||||
<div class="jugadores">
|
||||
|
||||
<div class="equipo me-2 ms-2 p-3 border rounded">
|
||||
<h6>${escapeHTML(equipo.nombreEquipo)}</h6>
|
||||
<div class="jugadores mb-2">
|
||||
${jugadoresHTML}
|
||||
|
||||
</div>
|
||||
|
||||
${botonUnirseHTML}
|
||||
|
||||
</div>
|
||||
`;
|
||||
});
|
||||
|
||||
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
||||
// 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">
|
||||
|
||||
<div class="sala-header">
|
||||
|
||||
<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">
|
||||
|
||||
<div class="equipos d-flex justify-content-around">
|
||||
${equiposHTML}
|
||||
|
||||
</div>
|
||||
${accionesSalaHTML}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
`;
|
||||
|
||||
contenedor.append(salaHTML);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// UNIRSE A UN EQUIPO
|
||||
// ======================================================
|
||||
|
||||
// 6. Evento: Unirse a un Equipo
|
||||
$(document).on("click", ".btn-unirse-equipo", function () {
|
||||
const boton = $(this);
|
||||
|
||||
const idEquipo = boton.data("id-equipo");
|
||||
|
||||
const idPartida = boton.data("id-partida");
|
||||
|
||||
boton.prop("disabled", true);
|
||||
|
||||
boton.text("Uniéndose...");
|
||||
boton.prop("disabled", true).text("Uniéndose...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/ControladorEquipoxUsuario.php",
|
||||
|
||||
type: "POST",
|
||||
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "registrarUsuarioEnEquipo",
|
||||
idEquipo: idEquipo,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
console.log("Respuesta al unirse:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false);
|
||||
|
||||
boton.text("Unirse");
|
||||
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
return;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// UNIÓN CORRECTA
|
||||
// ==========================================
|
||||
|
||||
usuarioYaEstaEnEquipo = true;
|
||||
|
||||
// Ocultamos el botón "Crear sala"
|
||||
|
||||
$("#contenedorCrearSala").hide();
|
||||
|
||||
// Eliminamos las salas actuales
|
||||
|
||||
$("#contenedorSalas").empty();
|
||||
|
||||
// Cargamos directamente la sala
|
||||
// donde acaba de entrar el usuario
|
||||
|
||||
cargarSalaUsuario(idPartida);
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al unirse al equipo:", error);
|
||||
|
||||
console.error("Respuesta del servidor:", xhr.responseText);
|
||||
|
||||
alert("No se ha podido unir al equipo.");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
|
||||
boton.text("Unirse");
|
||||
boton.prop("disabled", false).text("Unirse");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// ======================================================
|
||||
// ESCAPAR HTML
|
||||
// ======================================================
|
||||
// 7. Evento: Abandonar Sala
|
||||
// Guardamos temporalmente el botón presionado
|
||||
let botonAbandonarReferencia = null;
|
||||
|
||||
function escapeHTML(texto) {
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
// 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");
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// CREAR SALA
|
||||
// ======================================================
|
||||
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();
|
||||
|
||||
let valido = true;
|
||||
|
||||
$(".mensaje-error-sala").remove();
|
||||
|
||||
$(".input-kahoot").removeClass("is-invalid");
|
||||
|
||||
if (nombreSala === "") {
|
||||
mostrarError("#nombreSala", "El nombre de la sala es obligatorio.");
|
||||
|
||||
valido = false;
|
||||
} else if (nombreSala.length < 3) {
|
||||
if (nombreSala === "" || nombreSala.length < 3) {
|
||||
mostrarError(
|
||||
"#nombreSala",
|
||||
"El nombre de la sala debe tener al menos 3 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (nombreEquipo1 === "") {
|
||||
mostrarError("#nombreEquipo1", "El nombre del equipo 1 es obligatorio.");
|
||||
|
||||
valido = false;
|
||||
} else if (nombreEquipo1.length < 2) {
|
||||
if (nombreEquipo1 === "" || nombreEquipo1.length < 2) {
|
||||
mostrarError(
|
||||
"#nombreEquipo1",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (nombreEquipo2 === "") {
|
||||
mostrarError("#nombreEquipo2", "El nombre del equipo 2 es obligatorio.");
|
||||
|
||||
valido = false;
|
||||
} else if (nombreEquipo2.length < 2) {
|
||||
if (nombreEquipo2 === "" || nombreEquipo2.length < 2) {
|
||||
mostrarError(
|
||||
"#nombreEquipo2",
|
||||
"El nombre del equipo debe tener al menos 2 caracteres.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
@@ -404,22 +376,16 @@ $("#btnCrearSala").on("click", function () {
|
||||
"#nombreEquipo2",
|
||||
"Los dos equipos deben tener nombres diferentes.",
|
||||
);
|
||||
|
||||
valido = false;
|
||||
}
|
||||
|
||||
if (!valido) {
|
||||
return;
|
||||
}
|
||||
if (!valido) return;
|
||||
|
||||
// Deshabilitamos el botón mientras se crea la sala
|
||||
const boton = $("#btnCrearSala");
|
||||
|
||||
boton.prop("disabled", true);
|
||||
boton.text("Creando sala...");
|
||||
boton.prop("disabled", true).text("Creando sala...");
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPartida.php", // <-- cambia esto por la ruta de tu controlador
|
||||
url: "controladores/controladorPartida.php",
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
@@ -428,16 +394,10 @@ $("#btnCrearSala").on("click", function () {
|
||||
nombreEquipo1: nombreEquipo1,
|
||||
nombreEquipo2: nombreEquipo2,
|
||||
},
|
||||
|
||||
success: function (respuesta) {
|
||||
console.log("Respuesta del servidor:", respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear sala");
|
||||
|
||||
boton.prop("disabled", false).text("Crear sala");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -446,43 +406,30 @@ $("#btnCrearSala").on("click", function () {
|
||||
location.reload();
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al crear la sala:", error);
|
||||
console.error("Respuesta:", xhr.responseText);
|
||||
|
||||
alert("No se ha podido crear la sala.");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear sala");
|
||||
boton.prop("disabled", false).text("Crear sala");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// ======================================================
|
||||
// MOSTRAR ERROR
|
||||
// ======================================================
|
||||
// Auxiliares
|
||||
function escapeHTML(texto) {
|
||||
return $("<div>")
|
||||
.text(texto ?? "")
|
||||
.html();
|
||||
}
|
||||
|
||||
function mostrarError(selector, mensaje) {
|
||||
const input = $(selector);
|
||||
|
||||
input.addClass("is-invalid");
|
||||
|
||||
input.after(`
|
||||
<div class="mensaje-error-sala text-danger mt-1 small">
|
||||
|
||||
${mensaje}
|
||||
|
||||
</div>
|
||||
`);
|
||||
input.after(
|
||||
`<div class="mensaje-error-sala text-danger mt-1 small">${mensaje}</div>`,
|
||||
);
|
||||
}
|
||||
|
||||
// ======================================================
|
||||
// QUITAR ERROR AL ESCRIBIR
|
||||
// ======================================================
|
||||
|
||||
$(".input-kahoot").on("input", function () {
|
||||
$(document).on("input", ".input-kahoot", function () {
|
||||
$(this).removeClass("is-invalid");
|
||||
|
||||
$(this).next(".mensaje-error-sala").remove();
|
||||
});
|
||||
|
||||
+189
-271
@@ -1,299 +1,217 @@
|
||||
// Función de escape colocada arriba para evitar el ReferenceError
|
||||
function escapeHTML(str) {
|
||||
return $("<div>").text(str ?? "").html();
|
||||
}
|
||||
let idUsuarioSesion = null;
|
||||
|
||||
// Comprobar estado de sesión al cargar la página
|
||||
$(document).ready(function () {
|
||||
comprobarSesion();
|
||||
// Comprobar la sesión activa al cargar la página
|
||||
comprobarEstadoSesion();
|
||||
|
||||
// Evento Click: Login
|
||||
$('#botonAceptarLogin').on('click', function () {
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
// Permitir Submit con tecla Enter en el formulario de Login
|
||||
$('#formLogin').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarLogin();
|
||||
});
|
||||
|
||||
// Comprobar estado de sesión al cargar la página
|
||||
function comprobarSesion() {
|
||||
// Evento Click: Registro
|
||||
$('#botonAceptarRegistro').on('click', function () {
|
||||
ejecutarRegistro();
|
||||
});
|
||||
|
||||
// Permitir Submit con tecla Enter en el formulario de Registro
|
||||
$('#formRegistro').on('submit', function (e) {
|
||||
e.preventDefault();
|
||||
ejecutarRegistro();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Comprueba con el servidor si existe una sesión PHP
|
||||
*/
|
||||
function comprobarEstadoSesion() {
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: { orden: "comprobarSesion" },
|
||||
}).done(function (respuesta) {
|
||||
try {
|
||||
if (typeof respuesta === "string") {
|
||||
respuesta = JSON.parse(respuesta);
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'comprobarSesion' },
|
||||
success: function (respuesta) {
|
||||
if (respuesta.activa) {
|
||||
idUsuarioSesion = respuesta.usuario.idUsuario;
|
||||
renderizarCabeceraConSesion(respuesta.usuario);
|
||||
$('#colBotonJugar').removeClass('d-none');
|
||||
} else {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const contenedor = $("#contenedorUsuarioCabecera");
|
||||
contenedor.empty();
|
||||
/**
|
||||
* Petición AJAX para iniciar sesión
|
||||
*/
|
||||
function ejecutarLogin() {
|
||||
let email = $('#loginEmail').val().trim();
|
||||
let contrasena = $('#loginPassword').val().trim();
|
||||
$('#errorLogin').text('');
|
||||
|
||||
if (respuesta.activa && respuesta.usuario) {
|
||||
// 1. Renderizar Menú de Usuario en la Cabecera
|
||||
const htmlUsuario = `
|
||||
if (email === '' || contrasena === '') {
|
||||
$('#errorLogin').text('Por favor, rellena todos los campos.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
orden: 'comprobarUsuario',
|
||||
email: email,
|
||||
contrasena: contrasena
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$('#errorLogin').text(respuesta.error);
|
||||
} else if (respuesta.exito) {
|
||||
$('#modalLogin').modal('hide');
|
||||
$('#formLogin')[0].reset();
|
||||
|
||||
// Cargar datos de la sesión actualizados
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
$('#errorLogin').text('Error al conectar con el servidor.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para registrar un usuario
|
||||
*/
|
||||
function ejecutarRegistro() {
|
||||
let nombre = $('#regNombre').val().trim();
|
||||
let email = $('#regEmail').val().trim();
|
||||
let pass = $('#regPassword').val().trim();
|
||||
let passConfirm = $('#regPasswordConfirm').val().trim();
|
||||
|
||||
$('#errorRegistro').text('');
|
||||
|
||||
if (nombre === '' || email === '' || pass === '') {
|
||||
$('#errorRegistro').text('Todos los campos son obligatorios.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (pass !== passConfirm) {
|
||||
$('#errorRegistro').text('Las contraseñas no coinciden.');
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: {
|
||||
orden: 'registrarUsuario',
|
||||
nombreUsuario: nombre,
|
||||
email: email,
|
||||
contrasena: pass
|
||||
},
|
||||
success: function (respuesta) {
|
||||
if (respuesta.error) {
|
||||
$('#errorRegistro').text(respuesta.error);
|
||||
} else {
|
||||
$('#modalRegistro').modal('hide');
|
||||
$('#formRegistro')[0].reset();
|
||||
|
||||
// Autologin tras registrarse
|
||||
$('#loginEmail').val(email);
|
||||
$('#loginPassword').val(pass);
|
||||
ejecutarLogin();
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
$('#errorRegistro').text('Error al procesar el registro.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Petición AJAX para cerrar la sesión
|
||||
*/
|
||||
function cerrarSesion() {
|
||||
$.ajax({
|
||||
url: 'controladores/controladorUsuario.php',
|
||||
type: 'POST',
|
||||
dataType: 'json',
|
||||
data: { orden: 'cerrarSesion' },
|
||||
success: function () {
|
||||
renderizarCabeceraSinSesion();
|
||||
$('#colBotonJugar').addClass('d-none');
|
||||
|
||||
if (window.location.pathname.includes('perfil.php') || window.location.pathname.includes('buscadorSala.php')) {
|
||||
window.location.href = 'index.php';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza la cabecera cuando HAY sesión iniciada
|
||||
*/
|
||||
function renderizarCabeceraConSesion(usuario) {
|
||||
//Mete el avatar en cabecera
|
||||
let avatarImg = (usuario.avatar && usuario.avatar !== '')
|
||||
? usuario.avatar
|
||||
: 'img/avatars/defaultProfile.jpeg';
|
||||
|
||||
// Refrescar avatar si se cambia
|
||||
let avatarConCacheBuster = avatarImg + '?v=' + new Date().getTime();
|
||||
|
||||
let html = `
|
||||
<div class="dropdown">
|
||||
<button class="btn user-dropdown-btn dropdown-toggle d-flex align-items-center gap-2"
|
||||
type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="fa-solid fa-circle-user fa-lg text-warning"></i>
|
||||
<span>${escapeHTML(respuesta.usuario.nombreUsuario)}</span>
|
||||
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<img src="${avatarConCacheBuster}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
||||
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end user-dropdown-menu" aria-labelledby="userDropdown">
|
||||
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
||||
<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 class="dropdown-item py-2 fw-semibold" href="perfil.php">
|
||||
<i class="fa-solid fa-user me-2 text-primary"></i>Mi Perfil
|
||||
</a>
|
||||
</li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li>
|
||||
<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>
|
||||
<button class="dropdown-item py-2 fw-semibold text-danger" onclick="cerrarSesion()">
|
||||
<i class="fa-solid fa-right-from-bracket me-2"></i>Cerrar Sesión
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
contenedor.html(htmlUsuario);
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
}
|
||||
|
||||
// 2. Muestra el botón JUGAR y ajusta columnas
|
||||
$("#colBotonJugar").removeClass("d-none");
|
||||
$("#colRanking").removeClass("col-lg-8").addClass("col-lg-7 col-xl-8");
|
||||
|
||||
} else {
|
||||
// 1. Renderizar Botones de Invitado
|
||||
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
|
||||
/**
|
||||
* Renderiza los botones en la cabecera cuando NO hay sesión (Iniciar sesión azul)
|
||||
*/
|
||||
function renderizarCabeceraSinSesion() {
|
||||
let html = `
|
||||
<button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
||||
</button>
|
||||
<button type="button" class="btn btn-kahoot-register rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||
<i class="fa-solid fa-user-plus me-1"></i> Registrarse
|
||||
</button>
|
||||
`;
|
||||
contenedor.html(htmlInvitado);
|
||||
|
||||
// 2. Ocultar el botón JUGAR y expandir ranking
|
||||
$("#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);
|
||||
}
|
||||
});
|
||||
$('#contenedorUsuarioCabecera').html(html);
|
||||
}
|
||||
|
||||
// Registro
|
||||
$("#botonAceptarRegistro").click(function (event) {
|
||||
event.preventDefault();
|
||||
let nombreUsuario = $("#regNombre").val().trim();
|
||||
let email = $("#regEmail").val().trim();
|
||||
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("");
|
||||
|
||||
if (contrasena !== contrasenaConfirmacion) {
|
||||
$("#regPassword").addClass("is-invalid");
|
||||
$("#regPasswordConfirm").addClass("is-invalid");
|
||||
$("#errorRegistro").text("Las contraseñas no coinciden.");
|
||||
return;
|
||||
function escapeHtml(texto) {
|
||||
return $('<div>').text(texto).html();
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
nombreUsuario: nombreUsuario,
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "registrarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#errorRegistro").text(respuesta.error);
|
||||
$("#regNombre").addClass("is-invalid");
|
||||
$("#regEmail").addClass("is-invalid");
|
||||
} else {
|
||||
$("#errorRegistro")
|
||||
.removeClass("text-danger")
|
||||
.addClass("text-success")
|
||||
.text(respuesta.exito);
|
||||
|
||||
$("#formRegistro")[0].reset();
|
||||
|
||||
setTimeout(function () {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Login
|
||||
$("#botonAceptarLogin").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let email = $("#loginEmail").val().trim();
|
||||
let contrasena = $("#loginPassword").val();
|
||||
|
||||
$("#loginEmail").removeClass("is-invalid");
|
||||
$("#loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").text("");
|
||||
|
||||
if (email === "" || contrasena === "") {
|
||||
$("#errorLogin").text("Todos los campos son obligatorios.");
|
||||
if (email === "") $("#loginEmail").addClass("is-invalid");
|
||||
if (contrasena === "") $("#loginPassword").addClass("is-invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "comprobarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
$("#errorLogin").text(respuesta.error);
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Cerrar sesión
|
||||
$(document).on("click", "#botonCerrarSesion", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
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";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Registro
|
||||
$("#botonAceptarRegistro").click(function (event) {
|
||||
event.preventDefault();
|
||||
let nombreUsuario = $("#regNombre").val().trim();
|
||||
let email = $("#regEmail").val().trim();
|
||||
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("");
|
||||
|
||||
if (contrasena !== contrasenaConfirmacion) {
|
||||
$("#regPassword").addClass("is-invalid");
|
||||
$("#regPasswordConfirm").addClass("is-invalid");
|
||||
$("#errorRegistro").text("Las contraseñas no coinciden.");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
nombreUsuario: nombreUsuario,
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "registrarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#errorRegistro").text(respuesta.error);
|
||||
$("#regNombre").addClass("is-invalid");
|
||||
$("#regEmail").addClass("is-invalid");
|
||||
} else {
|
||||
$("#errorRegistro")
|
||||
.removeClass("text-danger")
|
||||
.addClass("text-success")
|
||||
.text(respuesta.exito);
|
||||
|
||||
$("#formRegistro")[0].reset();
|
||||
|
||||
setTimeout(function () {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Login
|
||||
$("#botonAceptarLogin").click(function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
let email = $("#loginEmail").val().trim();
|
||||
let contrasena = $("#loginPassword").val();
|
||||
|
||||
$("#loginEmail").removeClass("is-invalid");
|
||||
$("#loginPassword").removeClass("is-invalid");
|
||||
$("#errorLogin").text("");
|
||||
|
||||
if (email === "" || contrasena === "") {
|
||||
$("#errorLogin").text("Todos los campos son obligatorios.");
|
||||
if (email === "") $("#loginEmail").addClass("is-invalid");
|
||||
if (contrasena === "") $("#loginPassword").addClass("is-invalid");
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
data: {
|
||||
email: email,
|
||||
contrasena: contrasena,
|
||||
orden: "comprobarUsuario",
|
||||
},
|
||||
}).done(function (respuesta) {
|
||||
if (typeof respuesta === "string") respuesta = JSON.parse(respuesta);
|
||||
|
||||
if (respuesta.error) {
|
||||
$("#loginEmail").addClass("is-invalid");
|
||||
$("#loginPassword").addClass("is-invalid");
|
||||
$("#errorLogin").text(respuesta.error);
|
||||
} else {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Cerrar sesión (Usa delegación de eventos por si el botón se crea dinámicamente)
|
||||
$(document).on("click", "#botonCerrarSesion", function (event) {
|
||||
event.preventDefault();
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
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";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
// Lógica de juego.php
|
||||
// Carga las preguntas de la partida, las muestra de una en una,
|
||||
// guarda cada respuesta en el servidor y al terminar lleva a resultados.php
|
||||
|
||||
const URL_CONTROLADOR = "controladores/ControladorJuego.php";
|
||||
const PAUSA_FEEDBACK = 1800; // ms que se ve si has acertado o fallado
|
||||
|
||||
// Colores y formas de los botones (estilo Kahoot, definidos en juego.css)
|
||||
const ESTILOS_BOTON = [
|
||||
{ color: "red", forma: "triangle" },
|
||||
{ color: "blue", forma: "diamond" },
|
||||
{ color: "yellow", forma: "circle" },
|
||||
{ color: "green", forma: "square" },
|
||||
];
|
||||
|
||||
let idPartida = 0;
|
||||
let preguntas = [];
|
||||
let indice = 0; // pregunta que se está mostrando
|
||||
let bloqueado = false; // true mientras se envía una respuesta o se ve el feedback
|
||||
let numeroAciertos = 0; // número de aciertos del jugador
|
||||
|
||||
$(document).ready(function () {
|
||||
idPartida = parseInt($("body").data("id-partida"), 10);
|
||||
|
||||
// Un solo listener para todos los botones de respuesta
|
||||
$("#respuestas").on("click", ".btn-answer", function () {
|
||||
responder($(this));
|
||||
});
|
||||
|
||||
cargarPreguntas();
|
||||
});
|
||||
|
||||
// 1. Pedir las preguntas al servidor
|
||||
function cargarPreguntas() {
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: { orden: "cargarPreguntas", idPartida: idPartida },
|
||||
success: function (datos) {
|
||||
if (datos.error) {
|
||||
mostrarError(datos.error);
|
||||
return;
|
||||
}
|
||||
|
||||
preguntas = datos.preguntas;
|
||||
|
||||
if (preguntas.length === 0) {
|
||||
mostrarError("Esta partida no tiene preguntas.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Retomamos por la primera pregunta sin responder (por si recarga la página)
|
||||
indice = preguntas.findIndex(function (p) {
|
||||
return !p.respondida;
|
||||
});
|
||||
|
||||
if (indice === -1) {
|
||||
irAResultados();
|
||||
return;
|
||||
}
|
||||
|
||||
mostrarPregunta();
|
||||
},
|
||||
error: function () {
|
||||
mostrarError("No se pudo conectar con el servidor.");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Pintar la pregunta actual y sus respuestas
|
||||
function mostrarPregunta() {
|
||||
const pregunta = preguntas[indice];
|
||||
|
||||
bloqueado = false;
|
||||
|
||||
$("#textoPregunta").text(pregunta.nombrePregunta);
|
||||
$("#feedback").text("").removeClass("ok ko");
|
||||
$("#contadorPregunta").text(
|
||||
"Pregunta " + (indice + 1) + " de " + preguntas.length,
|
||||
);
|
||||
$("#barraProgreso").css("width", (indice / preguntas.length) * 100 + "%");
|
||||
|
||||
const $respuestas = $("#respuestas").empty();
|
||||
|
||||
pregunta.respuestas.forEach(function (respuesta, i) {
|
||||
const estilo = ESTILOS_BOTON[i % ESTILOS_BOTON.length];
|
||||
|
||||
// .text() y createTextNode evitan que el texto de la BD se interprete como HTML
|
||||
const $boton = $("<button>")
|
||||
.attr("type", "button")
|
||||
.addClass("btn-answer " + estilo.color)
|
||||
.attr("data-id-respuesta", respuesta.idRespuesta)
|
||||
.append($("<span>").addClass("shape " + estilo.forma))
|
||||
.append(document.createTextNode(respuesta.nombreRespuesta));
|
||||
|
||||
$respuestas.append($boton);
|
||||
});
|
||||
}
|
||||
|
||||
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
|
||||
function responder($botonPulsado) {
|
||||
if (bloqueado) {
|
||||
return;
|
||||
}
|
||||
bloqueado = true;
|
||||
|
||||
const pregunta = preguntas[indice];
|
||||
const idRespuesta = parseInt($botonPulsado.attr("data-id-respuesta"), 10);
|
||||
|
||||
$("#respuestas").addClass("bloqueado");
|
||||
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "responder",
|
||||
idPartida: idPartida,
|
||||
idPartidaxPregunta: pregunta.idPartidaxPregunta,
|
||||
idRespuesta: idRespuesta,
|
||||
},
|
||||
success: function (datos) {
|
||||
if (datos.error) {
|
||||
// No se guardó: dejamos que vuelva a intentarlo
|
||||
$("#feedback").text(datos.error).removeClass("ok").addClass("ko");
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
bloqueado = false;
|
||||
return;
|
||||
}
|
||||
|
||||
pregunta.respondida = true;
|
||||
mostrarFeedback($botonPulsado, datos);
|
||||
|
||||
setTimeout(function () {
|
||||
if (datos.terminada || indice >= preguntas.length - 1) {
|
||||
terminar();
|
||||
} else {
|
||||
indice++;
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
mostrarPregunta();
|
||||
}
|
||||
}, PAUSA_FEEDBACK);
|
||||
},
|
||||
error: function () {
|
||||
$("#feedback")
|
||||
.text("No se pudo guardar la respuesta. Inténtalo de nuevo.")
|
||||
.removeClass("ok")
|
||||
.addClass("ko");
|
||||
$("#respuestas").removeClass("bloqueado");
|
||||
bloqueado = false;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Marca la respuesta correcta en verde y atenúa el resto
|
||||
function mostrarFeedback($botonPulsado, datos) {
|
||||
$("#respuestas .btn-answer").each(function () {
|
||||
const $boton = $(this);
|
||||
const esLaCorrecta =
|
||||
parseInt($boton.attr("data-id-respuesta"), 10) ===
|
||||
datos.idRespuestaCorrecta;
|
||||
|
||||
if (esLaCorrecta) {
|
||||
$boton.addClass("correcta");
|
||||
} else {
|
||||
$boton.addClass("atenuada");
|
||||
}
|
||||
});
|
||||
|
||||
if (datos.acierto) {
|
||||
$("#feedback").text("¡Correcto!").removeClass("ko").addClass("ok");
|
||||
numeroAciertos++;
|
||||
} else {
|
||||
$botonPulsado.addClass("incorrecta");
|
||||
$("#feedback")
|
||||
.text("Respuesta incorrecta. La correcta está marcada.")
|
||||
.removeClass("ok")
|
||||
.addClass("ko");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Última pregunta respondida: se avisa al backend con los aciertos y luego se va a resultados
|
||||
function terminar() {
|
||||
$("#barraProgreso").css("width", "100%");
|
||||
$("#respuestas").empty();
|
||||
$("#contadorPregunta").text("Partida terminada");
|
||||
$("#textoPregunta").text("¡Has terminado! Cargando resultados…");
|
||||
$("#feedback").text("").removeClass("ok ko");
|
||||
|
||||
setTimeout(function () {
|
||||
$.ajax({
|
||||
url: URL_CONTROLADOR,
|
||||
type: "POST",
|
||||
dataType: "json",
|
||||
data: {
|
||||
orden: "finalizarPartida",
|
||||
idPartida: idPartida,
|
||||
aciertos: numeroAciertos,
|
||||
},
|
||||
complete: function () {
|
||||
// Se va a resultados tanto si el AJAX ha ido bien como si ha fallado
|
||||
irAResultados();
|
||||
},
|
||||
});
|
||||
}, 1200);
|
||||
}
|
||||
|
||||
function irAResultados() {
|
||||
window.location.href = "resultados.php?idPartida=" + idPartida;
|
||||
}
|
||||
|
||||
function mostrarError(mensaje) {
|
||||
$("#respuestas").empty();
|
||||
$("#textoPregunta").text(mensaje);
|
||||
$("#feedback").html(
|
||||
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
|
||||
);
|
||||
}
|
||||
+30
-27
@@ -26,6 +26,10 @@ $.ajax({
|
||||
function cambiarNombre() {
|
||||
let nuevoNombre = $("#nuevoNombre").val().trim();
|
||||
|
||||
if (nuevoNombre === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
method: "POST",
|
||||
url: "controladores/controladorUsuario.php",
|
||||
@@ -42,8 +46,13 @@ function cambiarNombre() {
|
||||
// Actualizamos el nombre mostrado en la página
|
||||
$("#nombre").text(respuesta.nombreUsuario);
|
||||
|
||||
// Limpiamos el input
|
||||
|
||||
$("#nuevoNombre").val("");
|
||||
|
||||
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -74,14 +83,11 @@ $("#inputFoto").change(function () {
|
||||
// Comprobamos que sea una imagen
|
||||
if (!archivo.type.startsWith("image/")) {
|
||||
alert("El archivo seleccionado no es una imagen.");
|
||||
|
||||
$("#inputFoto").val("");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let datos = new FormData();
|
||||
|
||||
datos.append("avatar", archivo);
|
||||
datos.append("orden", "cambiarAvatar");
|
||||
|
||||
@@ -97,18 +103,23 @@ $("#inputFoto").change(function () {
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
} else {
|
||||
// Actualizamos la imagen sin recargar la página
|
||||
// Actualizamos la imagen en la página de perfil sin recargar
|
||||
$("#fotoPerfil").attr(
|
||||
"src",
|
||||
respuesta.avatar + "?t=" + new Date().getTime(),
|
||||
respuesta.avatar + "?t=" + new Date().getTime()
|
||||
);
|
||||
|
||||
// Actualizamos también el avatar superior en la cabecera
|
||||
if (typeof comprobarEstadoSesion === "function") {
|
||||
comprobarEstadoSesion();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// =========================
|
||||
// RECOGER CATEGORIAS
|
||||
// ====
|
||||
// =========================
|
||||
|
||||
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||
const selectCategoria = $("#idCategoria");
|
||||
@@ -141,16 +152,14 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||
$("<option>", {
|
||||
value: categoria.idCategoria,
|
||||
text: categoria.nombreCategoria,
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al cargar las categorías:", error);
|
||||
|
||||
console.error("Respuesta del servidor:", xhr.responseText);
|
||||
|
||||
alert("No se han podido cargar las categorías.");
|
||||
},
|
||||
});
|
||||
@@ -158,7 +167,7 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||
|
||||
// =========================
|
||||
// CREAR PREGUNTA
|
||||
// ====
|
||||
// =========================
|
||||
|
||||
$("#formCrearPregunta").on("submit", function (e) {
|
||||
e.preventDefault();
|
||||
@@ -188,24 +197,15 @@ $("#formCrearPregunta").on("submit", function (e) {
|
||||
|
||||
$.ajax({
|
||||
url: "controladores/controladorPregunta.php",
|
||||
|
||||
type: "POST",
|
||||
|
||||
dataType: "json",
|
||||
|
||||
data: {
|
||||
orden: "crearPregunta",
|
||||
|
||||
idCategoria: $("#idCategoria").val(),
|
||||
|
||||
nombrePregunta: pregunta,
|
||||
|
||||
respuestaCorrecta: respuestaCorrecta,
|
||||
|
||||
respuestaIncorrecta1: respuestaIncorrecta1,
|
||||
|
||||
respuestaIncorrecta2: respuestaIncorrecta2,
|
||||
|
||||
respuestaIncorrecta3: respuestaIncorrecta3,
|
||||
},
|
||||
|
||||
@@ -214,10 +214,8 @@ $("#formCrearPregunta").on("submit", function (e) {
|
||||
|
||||
if (respuesta.error) {
|
||||
alert(respuesta.error);
|
||||
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear pregunta");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -233,17 +231,14 @@ $("#formCrearPregunta").on("submit", function (e) {
|
||||
// Volvemos a activar el botón
|
||||
boton.prop("disabled", false);
|
||||
boton.text("Crear pregunta");
|
||||
|
||||
// Si tienes que actualizar la lista de preguntas:
|
||||
// cargarPreguntas();
|
||||
// Toast exito
|
||||
mostrarToast()
|
||||
}
|
||||
},
|
||||
|
||||
error: function (xhr, status, error) {
|
||||
console.error("Error al crear la pregunta:", error);
|
||||
|
||||
console.error("Respuesta del servidor:", xhr.responseText);
|
||||
|
||||
alert("No se ha podido crear la pregunta.");
|
||||
|
||||
boton.prop("disabled", false);
|
||||
@@ -251,3 +246,11 @@ $("#formCrearPregunta").on("submit", function (e) {
|
||||
},
|
||||
});
|
||||
});
|
||||
function mostrarToast() {
|
||||
const toastMensaje = document.getElementById("ToastCrearPregunta");
|
||||
|
||||
if (toastMensaje) {
|
||||
const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastMensaje);
|
||||
toastBootstrap.show();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,20 @@
|
||||
<?php
|
||||
session_start();
|
||||
|
||||
// Hay que estar logueado para jugar
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: index.php');
|
||||
exit;
|
||||
}
|
||||
|
||||
// La partida llega por la URL: juego.php?idPartida=3
|
||||
$idPartida = filter_input(INPUT_GET, 'idPartida', FILTER_VALIDATE_INT);
|
||||
|
||||
if (!$idPartida || $idPartida < 1) {
|
||||
header('Location: buscadorSala.php');
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
@@ -8,39 +25,27 @@
|
||||
<link rel="stylesheet" href="css/juego.css">
|
||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||
</head>
|
||||
<body>
|
||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
||||
|
||||
<!-- Contenedor de la Pregunta -->
|
||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
||||
<div class="game-header">
|
||||
<span id="contadorPregunta">Cargando…</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div class="progress-fill" id="barraProgreso"></div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de la Pregunta (lo rellena js/juego.js) -->
|
||||
<div class="question-container">
|
||||
¿Cuál es el planeta más grande de nuestro sistema solar?
|
||||
<div id="textoPregunta">Cargando preguntas…</div>
|
||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot) -->
|
||||
<div class="answers-grid">
|
||||
<button class="btn-answer red" onclick="checkAnswer('Marte')">
|
||||
<span class="shape triangle"></span>
|
||||
Marte
|
||||
</button>
|
||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
||||
<div class="answers-grid" id="respuestas"></div>
|
||||
|
||||
<button class="btn-answer blue" onclick="checkAnswer('Júpiter')">
|
||||
<span class="shape diamond"></span>
|
||||
Júpiter
|
||||
</button>
|
||||
|
||||
<button class="btn-answer yellow" onclick="checkAnswer('Saturno')">
|
||||
<span class="shape circle"></span>
|
||||
Saturno
|
||||
</button>
|
||||
|
||||
<button class="btn-answer green" onclick="checkAnswer('Tierra')">
|
||||
<span class="shape square"></span>
|
||||
Tierra
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
|
||||
</script>
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
<script src="js/juego.js"></script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -166,6 +166,9 @@ CREATE TABLE `partida` (
|
||||
`idPartida` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`nombrePartida` varchar(100) NOT NULL,
|
||||
`idUsuario` int(11) NOT NULL,
|
||||
`fechaCreacion` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`fechaInicio` DATETIME NULL,
|
||||
`fechaFin` DATETIME NULL,
|
||||
PRIMARY KEY (`idPartida`),
|
||||
KEY `FK idUsuario tabla usuario` (`idUsuario`),
|
||||
CONSTRAINT `FK idUsuario tabla usuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`)
|
||||
@@ -178,10 +181,10 @@ CREATE TABLE `partida` (
|
||||
|
||||
LOCK TABLES `partida` WRITE;
|
||||
/*!40000 ALTER TABLE `partida` DISABLE KEYS */;
|
||||
INSERT INTO `partida` VALUES
|
||||
(1,'Partida de prueba 1',1),
|
||||
(2,'Partida de prueba 2',4),
|
||||
(3,'Partida de prueba 3',9);
|
||||
INSERT INTO `partida` (idPartida, nombrePartida, idUsuario, fechaInicio, fechaFin) VALUES
|
||||
(1,'Partida de prueba 1',1, NULL, NULL),
|
||||
(2,'Partida de prueba 2',4, NULL, NULL),
|
||||
(3,'Partida de prueba 3',9, NULL, NULL);
|
||||
/*!40000 ALTER TABLE `partida` ENABLE KEYS */;
|
||||
UNLOCK TABLES;
|
||||
|
||||
@@ -2362,3 +2365,4 @@ UNLOCK TABLES;
|
||||
/*M!100616 SET NOTE_VERBOSITY=@OLD_NOTE_VERBOSITY */;
|
||||
|
||||
-- Dump completed on 2026-09-25 10:00:41
|
||||
|
||||
|
||||
+59
-207
@@ -1,3 +1,17 @@
|
||||
<?php
|
||||
if (session_status() === PHP_SESSION_NONE) {
|
||||
session_start();
|
||||
}
|
||||
|
||||
// Redirección si el usuario no ha iniciado sesión
|
||||
if (!isset($_SESSION['idUsuario'])) {
|
||||
header('Location: login.php');
|
||||
exit();
|
||||
}
|
||||
|
||||
$nombreUsuario = htmlspecialchars($_SESSION['nombreUsuario'] ?? 'Usuario');
|
||||
$avatarUsuario = htmlspecialchars($_SESSION['avatar'] ?? 'img/avatars/defaultProfile.jpeg');
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
|
||||
@@ -9,151 +23,99 @@
|
||||
<title>Perfil</title>
|
||||
|
||||
<!-- Bootstrap -->
|
||||
<link
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
|
||||
rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
|
||||
<!-- Bootstrap Icons -->
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
|
||||
|
||||
<!-- Google Font: Fredoka -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap"
|
||||
rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&display=swap" rel="stylesheet">
|
||||
|
||||
<!-- Tu CSS -->
|
||||
<link rel="stylesheet" href="css/index.css">
|
||||
<link rel="stylesheet" href="css/perfil.css">
|
||||
<script src="js/jquery-4.0.0.min.js"></script>
|
||||
|
||||
</head>
|
||||
|
||||
|
||||
<body>
|
||||
|
||||
<?php
|
||||
include_once 'cabecera.php';
|
||||
?>
|
||||
|
||||
<?php include_once 'cabecera.php'; ?>
|
||||
|
||||
<div class="perfil-container">
|
||||
|
||||
<div class="perfil-card">
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CABECERA -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="perfil-header">
|
||||
<i class="bi bi-person-circle"></i>
|
||||
Mi perfil
|
||||
</div>
|
||||
|
||||
|
||||
<div class="perfil-content">
|
||||
|
||||
<div class="row align-items-center g-5">
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- PERFIL -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="col-md-6 text-center">
|
||||
|
||||
<!-- Nombre -->
|
||||
|
||||
<h1 id="nombre" class="nombre">
|
||||
<?php echo $_SESSION['nombreUsuario'] ?>
|
||||
<?= $nombreUsuario ?>
|
||||
</h1>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- FOTO DE PERFIL -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="foto-container">
|
||||
|
||||
<img
|
||||
id="fotoPerfil"
|
||||
src="<?= htmlspecialchars($_SESSION['avatar'] ?? '') ?>"
|
||||
<img id="fotoPerfil"
|
||||
src="<?= $avatarUsuario ?>"
|
||||
alt="Foto de perfil"
|
||||
class="avatar rounded-circle">
|
||||
|
||||
|
||||
<!-- Botón lápiz -->
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-foto"
|
||||
onclick="seleccionarFoto()"
|
||||
title="Cambiar foto de perfil"
|
||||
aria-label="Cambiar foto de perfil">
|
||||
|
||||
<i class="bi bi-pencil-fill"></i>
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<!-- Input oculto -->
|
||||
|
||||
<input
|
||||
type="file"
|
||||
<input type="file"
|
||||
id="inputFoto"
|
||||
accept="image/*"
|
||||
hidden>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CAMBIAR NOMBRE -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="formulario-nombre">
|
||||
|
||||
<label
|
||||
for="nuevoNombre"
|
||||
class="form-label">
|
||||
|
||||
<label for="nuevoNombre" class="form-label">
|
||||
Cambia tu nombre
|
||||
|
||||
</label>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="nuevoNombre"
|
||||
class="form-control mb-3"
|
||||
placeholder="Escribe tu nuevo nombre">
|
||||
|
||||
|
||||
<div class="d-flex justify-content-center gap-2">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-perfil-cambiar"
|
||||
onclick="cambiarNombre()">
|
||||
|
||||
<i class="bi bi-check-lg"></i>
|
||||
Cambiar nombre
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-perfil-borrar"
|
||||
onclick="borrarNombre()">
|
||||
|
||||
<i class="bi bi-x-lg"></i>
|
||||
Borrar
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
@@ -162,11 +124,7 @@
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- ESTADÍSTICAS -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="col-md-6">
|
||||
|
||||
<div class="estadisticas">
|
||||
@@ -176,60 +134,33 @@
|
||||
Estadísticas
|
||||
</h2>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-victorias">
|
||||
|
||||
<i class="bi bi-trophy-fill"></i>
|
||||
Victorias:
|
||||
|
||||
<strong id="victorias">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="victorias">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-derrotas">
|
||||
|
||||
<i class="bi bi-x-circle-fill"></i>
|
||||
Derrotas:
|
||||
|
||||
<strong id="derrotas">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="derrotas">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="estadistica estadistica-aciertos">
|
||||
|
||||
<i class="bi bi-bullseye"></i>
|
||||
Aciertos:
|
||||
|
||||
<strong id="aciertos">
|
||||
|
||||
</strong>
|
||||
|
||||
<strong id="aciertos">0</strong>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========================= -->
|
||||
<!-- CREAR PREGUNTA -->
|
||||
<!-- ========================= -->
|
||||
|
||||
<div class="text-center mt-4">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn btn-play-kahoot"
|
||||
data-bs-toggle="modal"
|
||||
data-bs-target="#modalCrearPregunta">
|
||||
|
||||
<i class="bi bi-plus-circle-fill"></i>
|
||||
Crear pregunta
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -243,14 +174,19 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ================================================= -->
|
||||
<!-- TOAST PREGUNTA CREADA -->
|
||||
<div class="toast-container position-fixed bottom-0 end-0 p-3">
|
||||
<div id="ToastCrearPregunta" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class=" toast-header" style="background-color: #46178f;">
|
||||
<h5 class="text-white me-auto bi bi-joystick me-2"> Pregunta Creada</h5>
|
||||
</div>
|
||||
<div class="fs-6 toast-body">
|
||||
La pregunta ha sido creada correctamente
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- MODAL CREAR PREGUNTA -->
|
||||
<!-- ================================================= -->
|
||||
|
||||
<div
|
||||
class="modal fade"
|
||||
<div class="modal fade"
|
||||
id="modalCrearPregunta"
|
||||
tabindex="-1"
|
||||
aria-labelledby="modalCrearPreguntaLabel"
|
||||
@@ -260,186 +196,107 @@
|
||||
|
||||
<div class="modal-content modal-kahoot">
|
||||
|
||||
|
||||
<!-- CABECERA DEL MODAL -->
|
||||
|
||||
<div class="modal-header modal-kahoot-header">
|
||||
|
||||
<h5
|
||||
class="modal-title"
|
||||
id="modalCrearPreguntaLabel">
|
||||
|
||||
<h5 class="modal-title" id="modalCrearPreguntaLabel">
|
||||
<i class="bi bi-question-circle-fill me-2"></i>
|
||||
Crear pregunta
|
||||
|
||||
</h5>
|
||||
|
||||
|
||||
<button
|
||||
type="button"
|
||||
<button type="button"
|
||||
class="btn-close btn-close-white"
|
||||
data-bs-dismiss="modal"
|
||||
aria-label="Cerrar">
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- CUERPO DEL MODAL -->
|
||||
|
||||
<div class="modal-body p-4">
|
||||
|
||||
<form id="formCrearPregunta">
|
||||
|
||||
|
||||
<!-- PREGUNTA -->
|
||||
|
||||
<div class="mb-4">
|
||||
|
||||
<label
|
||||
for="pregunta"
|
||||
class="form-label fw-semibold">
|
||||
|
||||
<label for="pregunta" class="form-label fw-semibold">
|
||||
<i class="bi bi-question-lg me-1"></i>
|
||||
Pregunta
|
||||
|
||||
</label>
|
||||
|
||||
<textarea
|
||||
id="pregunta"
|
||||
<textarea id="pregunta"
|
||||
name="pregunta"
|
||||
class="form-control input-kahoot"
|
||||
rows="3"
|
||||
placeholder="Escribe aquí la pregunta..."
|
||||
required></textarea>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- CATEGORÍA -->
|
||||
|
||||
<div class="mb-4">
|
||||
|
||||
<label
|
||||
for="idCategoria"
|
||||
class="form-label fw-semibold">
|
||||
|
||||
<label for="idCategoria" class="form-label fw-semibold">
|
||||
<i class="bi bi-folder-fill me-1"></i>
|
||||
Categoría
|
||||
|
||||
</label>
|
||||
|
||||
<select
|
||||
id="idCategoria"
|
||||
<select id="idCategoria"
|
||||
name="idCategoria"
|
||||
class="form-select input-kahoot"
|
||||
required>
|
||||
|
||||
<option value="">
|
||||
Selecciona una categoría
|
||||
</option>
|
||||
|
||||
<option value="">Selecciona una categoría</option>
|
||||
</select>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<!-- RESPUESTA CORRECTA -->
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
for="respuestaCorrecta"
|
||||
class="form-label fw-semibold text-success">
|
||||
|
||||
<label for="respuestaCorrecta" class="form-label fw-semibold text-success">
|
||||
<i class="bi bi-check-circle-fill me-1"></i>
|
||||
Respuesta correcta
|
||||
|
||||
</label>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaCorrecta"
|
||||
name="respuestaCorrecta"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Escribe la respuesta correcta..."
|
||||
required>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- RESPUESTAS INCORRECTAS -->
|
||||
|
||||
<div class="mb-3">
|
||||
|
||||
<label
|
||||
class="form-label fw-semibold text-danger">
|
||||
|
||||
<label class="form-label fw-semibold text-danger">
|
||||
<i class="bi bi-x-circle-fill me-1"></i>
|
||||
Respuestas incorrectas
|
||||
|
||||
</label>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta1"
|
||||
name="respuestaIncorrecta1"
|
||||
class="form-control input-kahoot mb-2"
|
||||
placeholder="Respuesta incorrecta 1"
|
||||
required>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta2"
|
||||
name="respuestaIncorrecta2"
|
||||
class="form-control input-kahoot mb-2"
|
||||
placeholder="Respuesta incorrecta 2"
|
||||
required>
|
||||
|
||||
|
||||
<input
|
||||
type="text"
|
||||
<input type="text"
|
||||
id="respuestaIncorrecta3"
|
||||
name="respuestaIncorrecta3"
|
||||
class="form-control input-kahoot"
|
||||
placeholder="Respuesta incorrecta 3"
|
||||
required>
|
||||
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
<!-- PIE DEL MODAL -->
|
||||
|
||||
<div class="modal-footer">
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary"
|
||||
data-bs-dismiss="modal">
|
||||
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
|
||||
<i class="bi bi-x-lg me-1"></i>
|
||||
Cancelar
|
||||
|
||||
</button>
|
||||
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
form="formCrearPregunta"
|
||||
class="btn btn-kahoot-login"
|
||||
id="btnCrearPregunta">
|
||||
|
||||
<button type="submit" form="formCrearPregunta" class="btn btn-kahoot-login" id="btnCrearPregunta">
|
||||
<i class="bi bi-check-lg me-1"></i>
|
||||
Crear pregunta
|
||||
|
||||
</button>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -449,14 +306,9 @@
|
||||
</div>
|
||||
|
||||
<!-- Bootstrap JS -->
|
||||
|
||||
<script
|
||||
src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js">
|
||||
</script>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
|
||||
<!-- Tu JavaScript -->
|
||||
|
||||
<script src="js/perfil.js"></script>
|
||||
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
bDatosServer="localhost"
|
||||
bDatos="triviagmatico"
|
||||
bDatosUser="root"
|
||||
bDatosPass=""
|
||||
urlBase="http://triviagmatico.test"
|
||||
dirBase="C:/laragon/www/triviagmatico"
|
||||
Reference in New Issue
Block a user