Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8c0792bd7 | |||
| 534c20a45d | |||
| 94bfe480cb | |||
| 42cc1489e9 | |||
| a694f19667 | |||
| 3cc0dfb122 |
+3
-2
@@ -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>
|
||||||
@@ -82,8 +83,8 @@
|
|||||||
<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">
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ class EquipoxUsuario
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function obtenerSalaUsuario($idUsuario)
|
public function obtenerSalaUsuario($idUsuario)
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
@@ -108,7 +109,6 @@ class EquipoxUsuario
|
|||||||
'idEquipo' => $resultado['idEquipo'],
|
'idEquipo' => $resultado['idEquipo'],
|
||||||
'idPartida' => $resultado['idPartida']
|
'idPartida' => $resultado['idPartida']
|
||||||
];
|
];
|
||||||
|
|
||||||
} catch (PDOException $error) {
|
} catch (PDOException $error) {
|
||||||
|
|
||||||
return [
|
return [
|
||||||
@@ -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 [
|
return [
|
||||||
'exito' => true,
|
'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) {
|
} 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()
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-58
@@ -142,63 +142,10 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function iniciar()
|
/**
|
||||||
{
|
* Devuelve las preguntas asignadas a la partida, junto con el
|
||||||
$conexion = conexionBD();
|
* idPartidaxPregunta (necesario para guardar respuestas después).
|
||||||
if (is_array($conexion)) {
|
*/
|
||||||
return $conexion;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
UPDATE partida
|
|
||||||
SET fechaInicio = NOW()
|
|
||||||
WHERE idPartida = :idPartida
|
|
||||||
AND fechaInicio IS NULL
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
|
||||||
$consulta->execute();
|
|
||||||
return [
|
|
||||||
"exito" => "La partida se inició correctamente.",
|
|
||||||
"exito_tecnico" => $this->idPartida
|
|
||||||
];
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
return [
|
|
||||||
"error" => "No se pudo iniciar la partida.",
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function finalizar()
|
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
|
||||||
if (is_array($conexion)) {
|
|
||||||
return $conexion;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
UPDATE partida
|
|
||||||
SET fechaFin = NOW()
|
|
||||||
WHERE idPartida = :idPartida
|
|
||||||
AND fechaInicio IS NOT NULL
|
|
||||||
AND fechaFin IS NULL
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
|
||||||
$consulta->execute();
|
|
||||||
return [
|
|
||||||
"exito" => "La partida se finalizó correctamente.",
|
|
||||||
"exito_tecnico" => $this->idPartida
|
|
||||||
];
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
return [
|
|
||||||
"error" => "No se pudo finalizar la partida.",
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public function getPreguntas()
|
public function getPreguntas()
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
@@ -227,7 +174,9 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asocia una pregunta ya existente a esta partida.
|
||||||
|
*/
|
||||||
public function asignarPregunta($idPregunta)
|
public function asignarPregunta($idPregunta)
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|||||||
@@ -55,10 +55,11 @@ switch ($_POST['orden']) {
|
|||||||
|
|
||||||
if ($resultado instanceof Usuario) {
|
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['idUsuario'] = $resultado->getIdUsuario();
|
||||||
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
||||||
$_SESSION['email'] = $resultado->getEmail();
|
$_SESSION['email'] = $resultado->getEmail();
|
||||||
|
$_SESSION['avatar'] = $resultado->getAvatar();
|
||||||
// =================================================
|
// =================================================
|
||||||
|
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
@@ -83,6 +84,7 @@ switch ($_POST['orden']) {
|
|||||||
unset($_SESSION['idUsuario']);
|
unset($_SESSION['idUsuario']);
|
||||||
unset($_SESSION['email']);
|
unset($_SESSION['email']);
|
||||||
unset($_SESSION['nombreUsuario']);
|
unset($_SESSION['nombreUsuario']);
|
||||||
|
unset($_SESSION['avatar']);
|
||||||
|
|
||||||
// Destruimos la sesión
|
// Destruimos la sesión
|
||||||
session_destroy();
|
session_destroy();
|
||||||
@@ -92,7 +94,6 @@ switch ($_POST['orden']) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'mostrarEstadisticas':
|
case 'mostrarEstadisticas':
|
||||||
|
|
||||||
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
||||||
@@ -242,7 +243,8 @@ switch ($_POST['orden']) {
|
|||||||
'activa' => true,
|
'activa' => true,
|
||||||
'usuario' => [
|
'usuario' => [
|
||||||
'idUsuario' => $_SESSION['idUsuario'],
|
'idUsuario' => $_SESSION['idUsuario'],
|
||||||
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? ''
|
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? '',
|
||||||
|
'avatar' => $_SESSION['avatar'] ?? ''
|
||||||
]
|
]
|
||||||
]);
|
]);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+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;
|
||||||
|
}
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 6.9 KiB |
+66
-11
@@ -123,11 +123,23 @@ 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" : ""
|
||||||
|
}">
|
||||||
|
<div>
|
||||||
|
<span class="avatar">${esHost ? '<i class="bi bi-award-fill"></i>' : '<i class="bi bi-person-fill"></i>'}</span>
|
||||||
${escapeHTML(jugador.nombreUsuario)}
|
${escapeHTML(jugador.nombreUsuario)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
${
|
||||||
|
esHost
|
||||||
|
? `<span class="badge bg-warning text-dark ms-2">HOST</span>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -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,17 +169,36 @@ 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) {
|
||||||
|
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 = `
|
accionesSalaHTML = `
|
||||||
<div class="sala-acciones text-center mt-4 pt-3 border-top d-flex justify-content-center gap-3">
|
<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}">
|
|
||||||
|
<button type="button"
|
||||||
|
class="btn btn-outline-danger btn-abandonar-sala"
|
||||||
|
data-id-partida="${partida.idPartida}"
|
||||||
|
data-es-host="${esHost}">
|
||||||
Abandonar sala
|
Abandonar sala
|
||||||
</button>
|
</button>
|
||||||
<a href="juego.php?idPartida=${partida.idPartida}" class="btn btn-success btn-lg px-4">
|
|
||||||
🎮 ¡Iniciar Partida!
|
${botonIniciarHTML}
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
@@ -175,7 +206,7 @@ function mostrarSala(partida, equipos, jugadores) {
|
|||||||
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
|
||||||
|
|||||||
+18
-17
@@ -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();
|
||||||
@@ -26,7 +28,7 @@ $(document).ready(function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Comprueba con el servidor si existe una sesión PHP activa.
|
* Comprueba con el servidor si existe una sesión PHP
|
||||||
*/
|
*/
|
||||||
function comprobarEstadoSesion() {
|
function comprobarEstadoSesion() {
|
||||||
$.ajax({
|
$.ajax({
|
||||||
@@ -36,8 +38,8 @@ 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);
|
||||||
// Si existe el contenedor del botón Jugar en index, lo mostramos
|
|
||||||
$('#colBotonJugar').removeClass('d-none');
|
$('#colBotonJugar').removeClass('d-none');
|
||||||
} else {
|
} else {
|
||||||
renderizarCabeceraSinSesion();
|
renderizarCabeceraSinSesion();
|
||||||
@@ -79,13 +81,8 @@ function ejecutarLogin() {
|
|||||||
$('#modalLogin').modal('hide');
|
$('#modalLogin').modal('hide');
|
||||||
$('#formLogin')[0].reset();
|
$('#formLogin')[0].reset();
|
||||||
|
|
||||||
renderizarCabeceraConSesion({
|
// Cargar datos de la sesión actualizados
|
||||||
idUsuario: respuesta.idUsuario,
|
comprobarEstadoSesion();
|
||||||
nombreUsuario: respuesta.nombreUsuario,
|
|
||||||
avatar: respuesta.avatar
|
|
||||||
});
|
|
||||||
|
|
||||||
$('#colBotonJugar').removeClass('d-none');
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: function () {
|
error: function () {
|
||||||
@@ -132,7 +129,7 @@ function ejecutarRegistro() {
|
|||||||
$('#modalRegistro').modal('hide');
|
$('#modalRegistro').modal('hide');
|
||||||
$('#formRegistro')[0].reset();
|
$('#formRegistro')[0].reset();
|
||||||
|
|
||||||
// Autologin
|
// Autologin tras registrarse
|
||||||
$('#loginEmail').val(email);
|
$('#loginEmail').val(email);
|
||||||
$('#loginPassword').val(pass);
|
$('#loginPassword').val(pass);
|
||||||
ejecutarLogin();
|
ejecutarLogin();
|
||||||
@@ -165,15 +162,21 @@ function cerrarSesion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renderiza la cabecera cuando HAY sesión iniciada (Menú Perfil + Avatar)
|
* Renderiza la cabecera cuando HAY sesión iniciada
|
||||||
*/
|
*/
|
||||||
function renderizarCabeceraConSesion(usuario) {
|
function renderizarCabeceraConSesion(usuario) {
|
||||||
let avatarImg = usuario.avatar ? usuario.avatar : 'img/avatars/defaultProfile.jpeg';
|
//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 = `
|
let html = `
|
||||||
<div class="dropdown">
|
<div class="dropdown">
|
||||||
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
<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="${avatarImg}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
<img src="${avatarConCacheBuster}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
||||||
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
||||||
</button>
|
</button>
|
||||||
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
||||||
@@ -195,13 +198,11 @@ function renderizarCabeceraConSesion(usuario) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renderiza los botones originales:
|
* Renderiza los botones en la cabecera cuando NO hay sesión (Iniciar sesión azul)
|
||||||
* - "Iniciar Sesión" (Rojo -> btn-danger)
|
|
||||||
* - "Registrarse" (Verde -> btn-success)
|
|
||||||
*/
|
*/
|
||||||
function renderizarCabeceraSinSesion() {
|
function renderizarCabeceraSinSesion() {
|
||||||
let html = `
|
let html = `
|
||||||
<button class="btn btn-danger rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
<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
|
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" 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">
|
||||||
|
|||||||
+20
-27
@@ -26,6 +26,10 @@ $.ajax({
|
|||||||
function cambiarNombre() {
|
function cambiarNombre() {
|
||||||
let nuevoNombre = $("#nuevoNombre").val().trim();
|
let nuevoNombre = $("#nuevoNombre").val().trim();
|
||||||
|
|
||||||
|
if (nuevoNombre === "") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "controladores/controladorUsuario.php",
|
url: "controladores/controladorUsuario.php",
|
||||||
@@ -42,8 +46,13 @@ function cambiarNombre() {
|
|||||||
// Actualizamos el nombre mostrado en la página
|
// Actualizamos el nombre mostrado en la página
|
||||||
$("#nombre").text(respuesta.nombreUsuario);
|
$("#nombre").text(respuesta.nombreUsuario);
|
||||||
|
|
||||||
// Limpiamos el input
|
|
||||||
$("#nuevoNombre").val("");
|
$("#nuevoNombre").val("");
|
||||||
|
|
||||||
|
|
||||||
|
if (typeof comprobarEstadoSesion === "function") {
|
||||||
|
comprobarEstadoSesion();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -74,14 +83,11 @@ $("#inputFoto").change(function () {
|
|||||||
// Comprobamos que sea una imagen
|
// Comprobamos que sea una imagen
|
||||||
if (!archivo.type.startsWith("image/")) {
|
if (!archivo.type.startsWith("image/")) {
|
||||||
alert("El archivo seleccionado no es una imagen.");
|
alert("El archivo seleccionado no es una imagen.");
|
||||||
|
|
||||||
$("#inputFoto").val("");
|
$("#inputFoto").val("");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let datos = new FormData();
|
let datos = new FormData();
|
||||||
|
|
||||||
datos.append("avatar", archivo);
|
datos.append("avatar", archivo);
|
||||||
datos.append("orden", "cambiarAvatar");
|
datos.append("orden", "cambiarAvatar");
|
||||||
|
|
||||||
@@ -97,18 +103,23 @@ $("#inputFoto").change(function () {
|
|||||||
if (respuesta.error) {
|
if (respuesta.error) {
|
||||||
alert(respuesta.error);
|
alert(respuesta.error);
|
||||||
} else {
|
} else {
|
||||||
// Actualizamos la imagen sin recargar la página
|
// Actualizamos la imagen en la página de perfil sin recargar
|
||||||
$("#fotoPerfil").attr(
|
$("#fotoPerfil").attr(
|
||||||
"src",
|
"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
|
// RECOGER CATEGORIAS
|
||||||
// ====
|
// =========================
|
||||||
|
|
||||||
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||||
const selectCategoria = $("#idCategoria");
|
const selectCategoria = $("#idCategoria");
|
||||||
@@ -141,16 +152,14 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
|||||||
$("<option>", {
|
$("<option>", {
|
||||||
value: categoria.idCategoria,
|
value: categoria.idCategoria,
|
||||||
text: categoria.nombreCategoria,
|
text: categoria.nombreCategoria,
|
||||||
}),
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
error: function (xhr, status, error) {
|
error: function (xhr, status, error) {
|
||||||
console.error("Error al cargar las categorías:", error);
|
console.error("Error al cargar las categorías:", error);
|
||||||
|
|
||||||
console.error("Respuesta del servidor:", xhr.responseText);
|
console.error("Respuesta del servidor:", xhr.responseText);
|
||||||
|
|
||||||
alert("No se han podido cargar las categorías.");
|
alert("No se han podido cargar las categorías.");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -158,7 +167,7 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
|||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// CREAR PREGUNTA
|
// CREAR PREGUNTA
|
||||||
// ====
|
// =========================
|
||||||
|
|
||||||
$("#formCrearPregunta").on("submit", function (e) {
|
$("#formCrearPregunta").on("submit", function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -188,24 +197,15 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: "controladores/controladorPregunta.php",
|
url: "controladores/controladorPregunta.php",
|
||||||
|
|
||||||
type: "POST",
|
type: "POST",
|
||||||
|
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
|
|
||||||
data: {
|
data: {
|
||||||
orden: "crearPregunta",
|
orden: "crearPregunta",
|
||||||
|
|
||||||
idCategoria: $("#idCategoria").val(),
|
idCategoria: $("#idCategoria").val(),
|
||||||
|
|
||||||
nombrePregunta: pregunta,
|
nombrePregunta: pregunta,
|
||||||
|
|
||||||
respuestaCorrecta: respuestaCorrecta,
|
respuestaCorrecta: respuestaCorrecta,
|
||||||
|
|
||||||
respuestaIncorrecta1: respuestaIncorrecta1,
|
respuestaIncorrecta1: respuestaIncorrecta1,
|
||||||
|
|
||||||
respuestaIncorrecta2: respuestaIncorrecta2,
|
respuestaIncorrecta2: respuestaIncorrecta2,
|
||||||
|
|
||||||
respuestaIncorrecta3: respuestaIncorrecta3,
|
respuestaIncorrecta3: respuestaIncorrecta3,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -214,10 +214,8 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
|
|
||||||
if (respuesta.error) {
|
if (respuesta.error) {
|
||||||
alert(respuesta.error);
|
alert(respuesta.error);
|
||||||
|
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
boton.text("Crear pregunta");
|
boton.text("Crear pregunta");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,17 +231,12 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
// Volvemos a activar el botón
|
// Volvemos a activar el botón
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
boton.text("Crear pregunta");
|
boton.text("Crear pregunta");
|
||||||
|
|
||||||
// Si tienes que actualizar la lista de preguntas:
|
|
||||||
// cargarPreguntas();
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
error: function (xhr, status, error) {
|
error: function (xhr, status, error) {
|
||||||
console.error("Error al crear la pregunta:", error);
|
console.error("Error al crear la pregunta:", error);
|
||||||
|
|
||||||
console.error("Respuesta del servidor:", xhr.responseText);
|
console.error("Respuesta del servidor:", xhr.responseText);
|
||||||
|
|
||||||
alert("No se ha podido crear la pregunta.");
|
alert("No se ha podido crear la pregunta.");
|
||||||
|
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
|
|||||||
Reference in New Issue
Block a user