Add se actualizan las salas automaticamente

This commit is contained in:
2026-10-01 13:52:36 +02:00
parent 8453735727
commit 5113b960d2
2 changed files with 431 additions and 317 deletions
+284 -75
View File
@@ -1,8 +1,47 @@
// =====================================================
// VARIABLES
// =====================================================
let intervaloBuscadorSalas = null;
let cargandoSalas = false;
// =====================================================
// INICIAR ACTUALIZACIÓN AUTOMÁTICA
// =====================================================
function iniciarActualizacionSalas() {
// Evitar crear varios intervalos
if (intervaloBuscadorSalas) {
clearInterval(intervaloBuscadorSalas);
}
// Primera carga
cargarSalas();
// Actualizar cada 5 segundos
intervaloBuscadorSalas = setInterval(function () {
// Si el usuario está dentro de una sala,
// no necesitamos actualizar el buscador.
if (!usuarioYaEstaEnEquipo) {
cargarSalas();
}
}, 5000);
}
// =====================================================
// CARGAR LISTA DE SALAS
// =====================================================
function cargarSalas() {
// Evitar peticiones simultáneas
if (cargandoSalas) {
return;
}
cargandoSalas = true;
$.ajax({
url: "controladores/controladorPartida.php",
type: "POST",
@@ -15,24 +54,71 @@ function cargarSalas() {
success: function (partidas) {
const contenedor = $("#contenedorSalas");
contenedor.empty();
// =================================================
// NO HAY SALAS
// =================================================
if (
!Array.isArray(partidas) ||
partidas.length === 0
) {
contenedor.html(`
<div class="col-12 text-center">
<p class="text-muted">
No hay salas disponibles actualmente.
</p>
</div>
`);
// Ocultamos/eliminamos únicamente las salas
$(".sala-item").remove();
if ($("#mensajeSinSalas").length === 0) {
contenedor.append(`
<div
id="mensajeSinSalas"
class="col-12 text-center">
<p class="text-muted">
No hay salas disponibles actualmente.
</p>
</div>
`);
}
return;
}
// Cargar cada sala individualmente
// =================================================
// HAY SALAS
// =================================================
// Eliminar mensaje de "no hay salas"
$("#mensajeSinSalas").remove();
// =================================================
// OBTENER IDS DE LAS SALAS ACTUALES
// =================================================
const idsPartidas = partidas.map(function (partida) {
return String(partida.idPartida);
});
// =================================================
// ELIMINAR SALAS QUE YA NO EXISTEN
// =================================================
$(".sala-item").each(function () {
const idPartida = String(
$(this).data("id-partida")
);
if (!idsPartidas.includes(idPartida)) {
$(this).remove();
}
});
// =================================================
// ACTUALIZAR / CREAR CADA SALA
// =================================================
partidas.forEach(function (partida) {
cargarSalaBuscador(partida);
});
@@ -44,12 +130,16 @@ function cargarSalas() {
error
);
},
complete: function () {
cargandoSalas = false;
},
});
}
// =====================================================
// CARGAR INFORMACIÓN DE UNA SALA DEL BUSCADOR
// CARGAR INFORMACIÓN DE UNA SALA
// =====================================================
function cargarSalaBuscador(partida) {
@@ -75,7 +165,7 @@ function cargarSalaBuscador(partida) {
},
success: function (jugadores) {
mostrarSalaBuscador(
actualizarSalaBuscador(
partida,
equipos,
jugadores
@@ -102,30 +192,158 @@ function cargarSalaBuscador(partida) {
// =====================================================
// MOSTRAR UNA SALA EN EL BUSCADOR
// ACTUALIZAR UNA SALA
// =====================================================
function mostrarSalaBuscador(
function actualizarSalaBuscador(
partida,
equipos,
jugadores
) {
const selectorSala =
`.sala-item[data-id-partida="${partida.idPartida}"]`;
const salaExistente = $(selectorSala);
// ===================================================
// SI LA SALA NO EXISTE → CREARLA
// ===================================================
if (salaExistente.length === 0) {
crearSalaBuscador(
partida,
equipos,
jugadores
);
return;
}
// ===================================================
// LA SALA YA EXISTE
// ===================================================
//
// NO TOCAMOS LA TARJETA COMPLETA.
//
// Solo actualizamos .equipos
//
const equiposHTML =
generarEquiposHTML(
partida,
equipos,
jugadores
);
salaExistente
.find(".equipos")
.html(equiposHTML);
}
// =====================================================
// CREAR UNA SALA NUEVA
// =====================================================
function crearSalaBuscador(
partida,
equipos,
jugadores
) {
const equiposHTML =
generarEquiposHTML(
partida,
equipos,
jugadores
);
const salaHTML = `
<div
class="col-12 col-md-10 col-lg-8 sala-item"
data-id-partida="${partida.idPartida}">
<div class="sala card p-3 shadow-sm mb-4">
<!-- =========================================
CABECERA
========================================== -->
<div
class="sala-header h4 text-center mb-3 text-white">
${escapeHTML(
partida.nombrePartida
)}
</div>
<!-- =========================================
CUERPO
========================================== -->
<div class="sala-body">
<!-- ESTA ES LA PARTE QUE SE ACTUALIZA -->
<div class="equipos d-flex justify-content-around">
${equiposHTML}
</div>
</div>
</div>
</div>
`;
$("#contenedorSalas").append(
salaHTML
);
}
// =====================================================
// GENERAR HTML DE EQUIPOS Y JUGADORES
// =====================================================
function generarEquiposHTML(
partida,
equipos,
jugadores
) {
let equiposHTML = "";
equipos.forEach(function (equipo) {
const jugadoresEquipo = jugadores.filter(
function (jugador) {
return (
jugador.idEquipo ==
equipo.idEquipo
);
}
);
// -----------------------------------------------
// JUGADORES DE ESTE EQUIPO
// -----------------------------------------------
const jugadoresEquipo =
jugadores.filter(
function (jugador) {
return (
jugador.idEquipo ==
equipo.idEquipo
);
}
);
let jugadoresHTML = "";
// -----------------------------------------------
// JUGADORES DEL EQUIPO
// MOSTRAR JUGADORES
// -----------------------------------------------
if (jugadoresEquipo.length > 0) {
@@ -135,28 +353,38 @@ function mostrarSalaBuscador(
jugador.idUsuario ==
partida.idUsuario;
jugadoresHTML += `
<div class="jugador border border-2 d-flex align-items-center justify-content-between">
<div
class="jugador border border-2 d-flex align-items-center justify-content-between">
<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">
<span
class="badge bg-warning text-dark ms-2">
HOST
</span>
`
: ""
@@ -174,18 +402,22 @@ function mostrarSalaBuscador(
`;
}
// -----------------------------------------------
// BOTÓN UNIRSE
// -----------------------------------------------
let botonUnirseHTML = "";
if (!usuarioYaEstaEnEquipo) {
botonUnirseHTML = `
<button
type="button"
class="btn-unirse w-100 btn-unirse-equipo mt-2"
data-id-partida="${partida.idPartida}"
data-id-equipo="${equipo.idEquipo}">
Unirse
@@ -194,12 +426,14 @@ function mostrarSalaBuscador(
`;
}
// -----------------------------------------------
// EQUIPO
// -----------------------------------------------
equiposHTML += `
<div class="equipo me-2 ms-2 p-3 border rounded">
<div
class="equipo me-2 ms-2 p-3 border rounded">
<h6>
${escapeHTML(
@@ -208,7 +442,9 @@ function mostrarSalaBuscador(
</h6>
<div class="jugadores mb-2">
${jugadoresHTML}
</div>
${botonUnirseHTML}
@@ -218,48 +454,7 @@ function mostrarSalaBuscador(
});
// =================================================
// TARJETA DE LA SALA
// =================================================
const salaHTML = `
<div class="col-12 col-md-10 col-lg-8">
<div class="sala card p-3 shadow-sm mb-4">
<div class="sala-header h4 text-center mb-3 text-white">
${escapeHTML(
partida.nombrePartida
)}
</div>
<div class="sala-body">
<div class="equipos d-flex justify-content-around">
${equiposHTML}
</div>
</div>
</div>
</div>
`;
// =================================================
// IMPORTANTE
// =================================================
//
// NO usamos .html() aquí porque eso eliminaría
// las salas que ya se hayan mostrado.
//
// Usamos .append() para añadir cada nueva sala.
//
$("#contenedorSalas").append(
salaHTML
);
return equiposHTML;
}
@@ -279,9 +474,14 @@ $("#btnCrearSala").on(
const nombreEquipo2 =
$("#nombreEquipo2").val().trim();
let valido = true;
// Limpiar errores anteriores
// -----------------------------------------------
// LIMPIAR ERRORES
// -----------------------------------------------
$(".mensaje-error-sala").remove();
$(".input-kahoot")
@@ -340,7 +540,7 @@ $("#btnCrearSala").on(
// -----------------------------------------------
// LOS EQUIPOS NO PUEDEN TENER EL MISMO NOMBRE
// COMPROBAR NOMBRES IGUALES
// -----------------------------------------------
if (
@@ -358,14 +558,17 @@ $("#btnCrearSala").on(
}
// Si hay errores, no continuar
// -----------------------------------------------
// SI HAY ERRORES
// -----------------------------------------------
if (!valido) {
return;
}
// -----------------------------------------------
// DESACTIVAR BOTÓN
// BOTÓN
// -----------------------------------------------
const boton = $("#btnCrearSala");
@@ -376,7 +579,7 @@ $("#btnCrearSala").on(
// -----------------------------------------------
// CREAR SALA
// PETICIÓN
// -----------------------------------------------
$.ajax({
@@ -386,8 +589,11 @@ $("#btnCrearSala").on(
data: {
orden: "crear",
nombrePartida: nombreSala,
nombreEquipo1: nombreEquipo1,
nombreEquipo2: nombreEquipo2,
},
@@ -432,7 +638,7 @@ $("#btnCrearSala").on(
// =====================================================
// MOSTRAR ERROR DE VALIDACIÓN
// MOSTRAR ERROR
// =====================================================
function mostrarError(
@@ -444,8 +650,11 @@ function mostrarError(
input.addClass("is-invalid");
input.after(`
<div class="mensaje-error-sala text-danger mt-1 small">
<div
class="mensaje-error-sala text-danger mt-1 small">
${mensaje}
</div>
`);
}
@@ -466,4 +675,4 @@ $(document).on(
.next(".mensaje-error-sala")
.remove();
}
);
);