Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8c0792bd7 | |||
| 534c20a45d | |||
| 94bfe480cb | |||
| 42cc1489e9 | |||
| a694f19667 |
+17
-16
@@ -7,6 +7,7 @@
|
|||||||
<title>Trivial - Lobby</title>
|
<title>Trivial - Lobby</title>
|
||||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||||
<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/index.css">
|
||||||
<link rel="stylesheet" href="css/buscadorSala.css">
|
<link rel="stylesheet" href="css/buscadorSala.css">
|
||||||
</head>
|
</head>
|
||||||
@@ -77,25 +78,25 @@
|
|||||||
</div>
|
</div>
|
||||||
<!--MODAL ABANDONAR SALA -->
|
<!--MODAL ABANDONAR SALA -->
|
||||||
<!-- Modal Confirmar Abandonar Sala -->
|
<!-- Modal Confirmar Abandonar Sala -->
|
||||||
<div class="modal fade" id="modalAbandonarSala" tabindex="-1" aria-labelledby="modalAbandonarSalaLabel" aria-hidden="true">
|
<div class="modal fade" id="modalAbandonarSala" tabindex="-1" aria-labelledby="modalAbandonarSalaLabel" aria-hidden="true">
|
||||||
<div class="modal-dialog modal-dialog-centered">
|
<div class="modal-dialog modal-dialog-centered">
|
||||||
<div class="modal-content modal-kahoot text-center p-3">
|
<div class="modal-content modal-kahoot text-center p-3">
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<div class="mb-3 fs-1">⚠️</div>
|
<div class="mb-3 fs-1">⚠️</div>
|
||||||
<h4 class="modal-title mb-2 fw-bold text-white" id="modalAbandonarSalaLabel">¿Abandonar la sala?</h4>
|
<h4 class="modal-title mb-2 fw-bold" id="modalAbandonarSalaLabel">¿Abandonar la sala?</h4>
|
||||||
<p class="text-white-50">Si sales de la sala, perderás tu lugar en el equipo.</p>
|
<p class="text-dark-50" id="modalAbandonarSalaMensaje">Si sales de la sala, perderás tu lugar en el equipo.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer justify-content-center border-0 gap-2">
|
<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">
|
<button type="button" class="btn btn-secondary px-4 py-2" data-bs-dismiss="modal">
|
||||||
Cancelar
|
Cancelar
|
||||||
</button>
|
</button>
|
||||||
<button type="button" id="btnConfirmarAbandonar" class="btn btn-danger px-4 py-2">
|
<button type="button" id="btnConfirmarAbandonar" class="btn btn-danger px-4 py-2">
|
||||||
Sí, salir
|
Sí, salir
|
||||||
</button>
|
</button>
|
||||||
|
</div>
|
||||||
</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="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/jquery-4.0.0.min.js"></script>
|
||||||
|
|||||||
+159
-37
@@ -60,17 +60,18 @@ class EquipoxUsuario
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function obtenerSalaUsuario($idUsuario)
|
public function obtenerSalaUsuario($idUsuario)
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
||||||
$sql = "
|
$sql = "
|
||||||
SELECT
|
SELECT
|
||||||
exu.idEquipo,
|
exu.idEquipo,
|
||||||
exp.idPartida
|
exp.idPartida
|
||||||
@@ -84,41 +85,40 @@ class EquipoxUsuario
|
|||||||
LIMIT 1
|
LIMIT 1
|
||||||
";
|
";
|
||||||
|
|
||||||
$consulta = $conexion->prepare($sql);
|
$consulta = $conexion->prepare($sql);
|
||||||
|
|
||||||
$consulta->bindParam(
|
$consulta->bindParam(
|
||||||
':idUsuario',
|
':idUsuario',
|
||||||
$idUsuario,
|
$idUsuario,
|
||||||
PDO::PARAM_INT
|
PDO::PARAM_INT
|
||||||
);
|
);
|
||||||
|
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
|
|
||||||
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
$resultado = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
if (!$resultado) {
|
if (!$resultado) {
|
||||||
|
|
||||||
|
return [
|
||||||
|
'asociado' => false
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'asociado' => false
|
'asociado' => true,
|
||||||
|
'idEquipo' => $resultado['idEquipo'],
|
||||||
|
'idPartida' => $resultado['idPartida']
|
||||||
|
];
|
||||||
|
} catch (PDOException $error) {
|
||||||
|
|
||||||
|
return [
|
||||||
|
'error' => 'Ocurrió un error al obtener la sala del usuario.',
|
||||||
|
'error_tecnico' => $error->getMessage()
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
return [
|
|
||||||
'asociado' => true,
|
|
||||||
'idEquipo' => $resultado['idEquipo'],
|
|
||||||
'idPartida' => $resultado['idPartida']
|
|
||||||
];
|
|
||||||
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
|
|
||||||
return [
|
|
||||||
'error' => 'Ocurrió un error al obtener la sala del usuario.',
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public static function salirDeSala($idUsuario)
|
public static function salirDeSala($idUsuario)
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|
||||||
@@ -127,21 +127,143 @@ public static function salirDeSala($idUsuario)
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
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 = $conexion->prepare($sql);
|
||||||
$consulta->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
|
$consulta->bindParam(':idUsuario',$idUsuario, PDO::PARAM_INT);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
|
|
||||||
|
$datosSala = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||||
|
|
||||||
|
// El usuario no pertenece a ninguna sala
|
||||||
|
if (!$datosSala) {
|
||||||
|
return [
|
||||||
|
'error' => 'No perteneces a ninguna sala.'
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$idEquipo = (int)$datosSala['idEquipo'];
|
||||||
|
$idPartida = (int)$datosSala['idPartida'];
|
||||||
|
$idHost = (int)$datosSala['idHost'];
|
||||||
|
|
||||||
|
// Comenzamos una transacción
|
||||||
|
$conexion->beginTransaction();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 2. Comprobamos si quien abandona es el HOST
|
||||||
|
*/
|
||||||
|
if ($idUsuario === $idHost) {
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Obtenemos todos los equipos pertenecientes
|
||||||
|
* a esta partida.
|
||||||
|
*/
|
||||||
|
$sqlEquipos = "SELECT idEquipo FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||||
|
|
||||||
|
$consultaEquipos = $conexion->prepare($sqlEquipos);
|
||||||
|
$consultaEquipos->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||||
|
$consultaEquipos->execute();
|
||||||
|
|
||||||
|
$equipos = $consultaEquipos->fetchAll(PDO::FETCH_COLUMN);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 3. Eliminamos los jugadores de esos equipos
|
||||||
|
* de la tabla equipoxusuario.
|
||||||
|
*/
|
||||||
|
if (!empty($equipos)) {
|
||||||
|
|
||||||
|
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||||
|
|
||||||
|
$sqlUsuarios = "DELETE FROM equipoxusuario WHERE idEquipo IN ($placeholders)";
|
||||||
|
|
||||||
|
$consultaUsuarios = $conexion->prepare($sqlUsuarios);
|
||||||
|
$consultaUsuarios->execute($equipos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 4. Eliminamos las relaciones
|
||||||
|
* entre equipos y partida.
|
||||||
|
*/
|
||||||
|
$sqlEquipoxPartida = "DELETE FROM equipoxpartida WHERE idPartida = :idPartida";
|
||||||
|
|
||||||
|
$consultaEquipoxPartida = $conexion->prepare($sqlEquipoxPartida);
|
||||||
|
$consultaEquipoxPartida->bindParam(':idPartida', $idPartida,PDO::PARAM_INT);
|
||||||
|
$consultaEquipoxPartida->execute();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 5. Eliminamos los equipos.
|
||||||
|
*
|
||||||
|
* Los equipos ya no tienen relaciones con
|
||||||
|
* usuarios ni con la partida.
|
||||||
|
*/
|
||||||
|
if (!empty($equipos)) {
|
||||||
|
|
||||||
|
$placeholders = implode(',', array_fill(0, count($equipos), '?'));
|
||||||
|
|
||||||
|
$sqlEliminarEquipos = "DELETE FROM equipo WHERE idEquipo IN ($placeholders)";
|
||||||
|
$consultaEliminarEquipos = $conexion->prepare($sqlEliminarEquipos);
|
||||||
|
$consultaEliminarEquipos->execute($equipos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 6. Eliminamos las relaciones
|
||||||
|
* entre preguntas y partida.
|
||||||
|
*/
|
||||||
|
$sqlPartidaxPregunta = "DELETE FROM partidaxpregunta WHERE idPartida = :idPartida";
|
||||||
|
|
||||||
|
$consultaPartidaxPregunta = $conexion->prepare($sqlPartidaxPregunta);
|
||||||
|
$consultaPartidaxPregunta->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||||
|
$consultaPartidaxPregunta->execute();
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 7. Finalmente eliminamos la partida.
|
||||||
|
*/
|
||||||
|
$sqlPartida = "DELETE FROM partida WHERE idPartida = :idPartida";
|
||||||
|
|
||||||
|
$consultaPartida = $conexion->prepare($sqlPartida);
|
||||||
|
$consultaPartida->bindParam(':idPartida', $idPartida, PDO::PARAM_INT);
|
||||||
|
$consultaPartida->execute();
|
||||||
|
|
||||||
|
// Todo ha ido correctamente
|
||||||
|
$conexion->commit();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'exito' => true,
|
||||||
|
'salaEliminada' => true,
|
||||||
|
'mensaje' => 'La sala ha sido eliminada correctamente.'
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 7. Si NO es el host, simplemente abandona
|
||||||
|
* su relación con el equipo.
|
||||||
|
*/
|
||||||
|
$sqlSalir = "DELETE FROM equipoxusuario WHERE idUsuario = :idUsuario";
|
||||||
|
|
||||||
|
$consultaSalir = $conexion->prepare($sqlSalir);
|
||||||
|
$consultaSalir->bindParam(':idUsuario', $idUsuario, PDO::PARAM_INT);
|
||||||
|
$consultaSalir->execute();
|
||||||
|
|
||||||
|
$conexion->commit();
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'exito' => true,
|
'exito' => true,
|
||||||
'mensaje' => 'Usuario eliminado de la sala correctamente.'
|
'salaEliminada' => false,
|
||||||
|
'mensaje' => 'Has abandonado la sala correctamente.'
|
||||||
];
|
];
|
||||||
} catch (PDOException $error) {
|
} catch (PDOException $error) {
|
||||||
|
|
||||||
|
// Si había una transacción activa, la deshacemos
|
||||||
|
if ($conexion->inTransaction()) {
|
||||||
|
$conexion->rollBack();
|
||||||
|
}
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'error' => 'Ocurrió un error al salir de la sala.',
|
'error' => 'Ocurrió un error al abandonar la sala.',
|
||||||
'error_tecnico' => $error->getMessage()
|
'error_tecnico' => $error->getMessage()
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,348 +0,0 @@
|
|||||||
<?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,96 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
session_start();
|
|
||||||
|
|
||||||
require_once '../clases/ClaseJuego.php';
|
|
||||||
|
|
||||||
header('Content-Type: application/json; charset=utf-8');
|
|
||||||
|
|
||||||
// Hay que estar logueado y decir de qué partida se trata
|
|
||||||
if (!isset($_SESSION['idUsuario'])) {
|
|
||||||
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
|
||||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
|
||||||
|
|
||||||
if ($idPartida <= 0) {
|
|
||||||
echo json_encode(['error' => 'No se ha indicado la partida.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Solo pueden jugar los usuarios que están en uno de los equipos de la partida
|
|
||||||
$perteneceAPartida = Juego::usuarioEnPartida($idPartida, $idUsuario);
|
|
||||||
|
|
||||||
if (is_array($perteneceAPartida)) {
|
|
||||||
echo json_encode($perteneceAPartida);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!$perteneceAPartida) {
|
|
||||||
echo json_encode(['error' => 'No formas parte de esta partida.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
switch ($_POST['orden'] ?? '') {
|
|
||||||
|
|
||||||
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
|
|
||||||
case 'cargarPreguntas':
|
|
||||||
|
|
||||||
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
// Guarda la respuesta del usuario y dice si ha acertado
|
|
||||||
case 'responder':
|
|
||||||
|
|
||||||
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta'] ?? 0);
|
|
||||||
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
|
|
||||||
|
|
||||||
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0) {
|
|
||||||
echo json_encode(['error' => 'Faltan datos para registrar la respuesta.']);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
echo json_encode(
|
|
||||||
Juego::registrarRespuesta(
|
|
||||||
$idPartida,
|
|
||||||
$idUsuario,
|
|
||||||
$idPartidaxPregunta,
|
|
||||||
$idRespuesta
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
// Recibe los aciertos del jugador al terminar sus 10 preguntas,
|
|
||||||
// para que resultados.php los pueda usar al montar la hoja de resultados
|
|
||||||
case 'finalizarPartida':
|
|
||||||
|
|
||||||
$aciertos = intval($_POST['aciertos'] ?? 0);
|
|
||||||
|
|
||||||
if (!isset($_SESSION['aciertosPorPartida'])) {
|
|
||||||
$_SESSION['aciertosPorPartida'] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$_SESSION['aciertosPorPartida'][$idPartida] = $aciertos;
|
|
||||||
|
|
||||||
echo json_encode([
|
|
||||||
'exito' => 'Aciertos registrados correctamente.',
|
|
||||||
'idPartida' => $idPartida,
|
|
||||||
'aciertos' => $aciertos
|
|
||||||
]);
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
default:
|
|
||||||
|
|
||||||
echo json_encode(['error' => 'La orden indicada no existe.']);
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
+10
-2
@@ -68,8 +68,8 @@
|
|||||||
|
|
||||||
.btn-unirse {
|
.btn-unirse {
|
||||||
border: none;
|
border: none;
|
||||||
border-bottom: 3px solid #0c4891;
|
border-bottom: 3px solid #1f6f09;
|
||||||
background-color: var(--kahoot-blue);
|
background-color: #26890c;
|
||||||
color: white;
|
color: white;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
@@ -105,3 +105,11 @@
|
|||||||
border-color: var(--kahoot-purple);
|
border-color: var(--kahoot-purple);
|
||||||
box-shadow: 0 0 0 3px rgba(70, 23, 143, 0.15);
|
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,65 +117,3 @@
|
|||||||
font-size: 18px;
|
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 |
+74
-19
@@ -123,12 +123,24 @@ function mostrarSala(partida, equipos, jugadores) {
|
|||||||
let jugadoresHTML = "";
|
let jugadoresHTML = "";
|
||||||
if (jugadoresEquipo.length > 0) {
|
if (jugadoresEquipo.length > 0) {
|
||||||
jugadoresEquipo.forEach(function (jugador) {
|
jugadoresEquipo.forEach(function (jugador) {
|
||||||
|
const esHost = jugador.idUsuario == partida.idUsuario;
|
||||||
|
|
||||||
jugadoresHTML += `
|
jugadoresHTML += `
|
||||||
<div class="jugador">
|
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${
|
||||||
<span class="avatar">👤</span>
|
esHost ? "jugador-host" : ""
|
||||||
${escapeHTML(jugador.nombreUsuario)}
|
}">
|
||||||
</div>
|
<div>
|
||||||
`;
|
<span class="avatar">${esHost ? '<i class="bi bi-award-fill"></i>' : '<i class="bi bi-person-fill"></i>'}</span>
|
||||||
|
${escapeHTML(jugador.nombreUsuario)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
${
|
||||||
|
esHost
|
||||||
|
? `<span class="badge bg-warning text-dark ms-2">HOST</span>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
jugadoresHTML = `<div class="text-muted small">Sin jugadores</div>`;
|
jugadoresHTML = `<div class="text-muted small">Sin jugadores</div>`;
|
||||||
@@ -138,7 +150,7 @@ function mostrarSala(partida, equipos, jugadores) {
|
|||||||
let botonUnirseHTML = "";
|
let botonUnirseHTML = "";
|
||||||
if (!usuarioYaEstaEnEquipo) {
|
if (!usuarioYaEstaEnEquipo) {
|
||||||
botonUnirseHTML = `
|
botonUnirseHTML = `
|
||||||
<button type="button" class="btn btn-unirse w-100 btn-unirse-equipo mt-2"
|
<button type="button" class="btn-unirse w-100 btn-unirse-equipo mt-2"
|
||||||
data-id-partida="${partida.idPartida}"
|
data-id-partida="${partida.idPartida}"
|
||||||
data-id-equipo="${equipo.idEquipo}">
|
data-id-equipo="${equipo.idEquipo}">
|
||||||
Unirse
|
Unirse
|
||||||
@@ -157,25 +169,44 @@ function mostrarSala(partida, equipos, jugadores) {
|
|||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
||||||
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
// Acciones disponibles si el usuario YA ESTÁ dentro de esta sala
|
||||||
let accionesSalaHTML = "";
|
let accionesSalaHTML = "";
|
||||||
|
|
||||||
if (usuarioYaEstaEnEquipo) {
|
if (usuarioYaEstaEnEquipo) {
|
||||||
accionesSalaHTML = `
|
const esHost = partida.idUsuario == idUsuarioSesion;
|
||||||
<div class="sala-acciones text-center mt-4 pt-3 border-top d-flex justify-content-center gap-3">
|
let botonIniciarHTML = "";
|
||||||
<button type="button" class="btn btn-outline-danger btn-abandonar-sala" data-id-partida="${partida.idPartida}">
|
|
||||||
Abandonar sala
|
// Solo el host puede iniciar la partida
|
||||||
</button>
|
if (esHost) {
|
||||||
<a href="juego.php?idPartida=${partida.idPartida}" class="btn btn-success btn-lg px-4">
|
botonIniciarHTML = `
|
||||||
🎮 ¡Iniciar Partida!
|
<a href="juego.php?idPartida=${partida.idPartida}"
|
||||||
</a>
|
class="btn btn-success btn-lg px-4">
|
||||||
</div>
|
<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 = `
|
const salaHTML = `
|
||||||
<div class="col-12 col-md-10 col-lg-8">
|
<div class="col-12 col-md-10 col-lg-8">
|
||||||
<div class="sala card p-3 shadow-sm mb-4">
|
<div class="sala card p-3 shadow-sm mb-4">
|
||||||
<div class="sala-header h4 text-center mb-3">
|
<div class="sala-header h4 text-center mb-3 text-white">
|
||||||
${escapeHTML(partida.nombrePartida)}
|
${escapeHTML(partida.nombrePartida)}
|
||||||
</div>
|
</div>
|
||||||
<div class="sala-body">
|
<div class="sala-body">
|
||||||
@@ -234,13 +265,37 @@ let botonAbandonarReferencia = null;
|
|||||||
// A. Al hacer clic en el botón "Abandonar sala" de la tarjeta, abrimos el modal
|
// A. Al hacer clic en el botón "Abandonar sala" de la tarjeta, abrimos el modal
|
||||||
$(document).on("click", ".btn-abandonar-sala", function () {
|
$(document).on("click", ".btn-abandonar-sala", function () {
|
||||||
botonAbandonarReferencia = $(this);
|
botonAbandonarReferencia = $(this);
|
||||||
const modal = new bootstrap.Modal(document.getElementById('modalAbandonarSala'));
|
|
||||||
|
const esHost = $(this).data("es-host") === true || $(this).data("es-host") === "true";
|
||||||
|
const titulo = $("#modalAbandonarSalaLabel");
|
||||||
|
const mensaje = $("#modalAbandonarSalaMensaje");
|
||||||
|
const botonConfirmar = $("#btnConfirmarAbandonar");
|
||||||
|
|
||||||
|
if (esHost) {
|
||||||
|
titulo.text("¿Abandonar la sala?");
|
||||||
|
mensaje.text(
|
||||||
|
"Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.",
|
||||||
|
);
|
||||||
|
botonConfirmar.text("Sí, abandonar");
|
||||||
|
} else {
|
||||||
|
titulo.text("¿Abandonar la sala?");
|
||||||
|
mensaje.text(
|
||||||
|
"Si sales de la sala, perderás tu lugar en el equipo.",
|
||||||
|
);
|
||||||
|
botonConfirmar.text("Sí, salir");
|
||||||
|
}
|
||||||
|
|
||||||
|
const modal = new bootstrap.Modal(
|
||||||
|
document.getElementById("modalAbandonarSala"),
|
||||||
|
);
|
||||||
|
|
||||||
modal.show();
|
modal.show();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// B. Al hacer clic en "Sí, salir" dentro del modal Kahoot
|
// B. Al hacer clic en "Sí, salir" dentro del modal Kahoot
|
||||||
$(document).on("click", "#btnConfirmarAbandonar", function () {
|
$(document).on("click", "#btnConfirmarAbandonar", function () {
|
||||||
const modalEl = document.getElementById('modalAbandonarSala');
|
const modalEl = document.getElementById("modalAbandonarSala");
|
||||||
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
const modalInstance = bootstrap.Modal.getInstance(modalEl);
|
||||||
|
|
||||||
const btnConfirmar = $(this);
|
const btnConfirmar = $(this);
|
||||||
@@ -275,7 +330,7 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
|
|||||||
if (modalInstance) {
|
if (modalInstance) {
|
||||||
modalInstance.hide();
|
modalInstance.hide();
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
// 8. Evento: Crear Sala
|
// 8. Evento: Crear Sala
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
let idUsuarioSesion = null;
|
||||||
|
|
||||||
$(document).ready(function () {
|
$(document).ready(function () {
|
||||||
// Comprobar la sesión activa al cargar la página
|
// Comprobar la sesión activa al cargar la página
|
||||||
comprobarEstadoSesion();
|
comprobarEstadoSesion();
|
||||||
@@ -36,6 +38,7 @@ function comprobarEstadoSesion() {
|
|||||||
data: { orden: 'comprobarSesion' },
|
data: { orden: 'comprobarSesion' },
|
||||||
success: function (respuesta) {
|
success: function (respuesta) {
|
||||||
if (respuesta.activa) {
|
if (respuesta.activa) {
|
||||||
|
idUsuarioSesion = respuesta.usuario.idUsuario;
|
||||||
renderizarCabeceraConSesion(respuesta.usuario);
|
renderizarCabeceraConSesion(respuesta.usuario);
|
||||||
$('#colBotonJugar').removeClass('d-none');
|
$('#colBotonJugar').removeClass('d-none');
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
-219
@@ -1,219 +0,0 @@
|
|||||||
// 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>',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,20 +1,3 @@
|
|||||||
<?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>
|
<!DOCTYPE html>
|
||||||
<html lang="es">
|
<html lang="es">
|
||||||
<head>
|
<head>
|
||||||
@@ -25,27 +8,39 @@ if (!$idPartida || $idPartida < 1) {
|
|||||||
<link rel="stylesheet" href="css/juego.css">
|
<link rel="stylesheet" href="css/juego.css">
|
||||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||||
</head>
|
</head>
|
||||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
<body>
|
||||||
|
|
||||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
<!-- Contenedor de la Pregunta -->
|
||||||
<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">
|
<div class="question-container">
|
||||||
<div id="textoPregunta">Cargando preguntas…</div>
|
¿Cuál es el planeta más grande de nuestro sistema solar?
|
||||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
<!-- Contenedor de Respuestas (Estilo Kahoot) -->
|
||||||
<div class="answers-grid" id="respuestas"></div>
|
<div class="answers-grid">
|
||||||
|
<button class="btn-answer red" onclick="checkAnswer('Marte')">
|
||||||
|
<span class="shape triangle"></span>
|
||||||
|
Marte
|
||||||
|
</button>
|
||||||
|
|
||||||
<script src="js/jquery-4.0.0.min.js"></script>
|
<button class="btn-answer blue" onclick="checkAnswer('Júpiter')">
|
||||||
<script src="js/juego.js"></script>
|
<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>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
Reference in New Issue
Block a user