From 5113b960d2a0ce0aff590eb61d5a35520388b2cd Mon Sep 17 00:00:00 2001 From: alexis Date: Thu, 1 Oct 2026 13:52:36 +0200 Subject: [PATCH] Add se actualizan las salas automaticamente --- js/buscadorSala.js | 359 ++++++++++++++++++++++++++++++++--------- js/sala.js | 389 +++++++++++++++++---------------------------- 2 files changed, 431 insertions(+), 317 deletions(-) diff --git a/js/buscadorSala.js b/js/buscadorSala.js index f0b966f..ae10912 100644 --- a/js/buscadorSala.js +++ b/js/buscadorSala.js @@ -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(` -
-

- No hay salas disponibles actualmente. -

-
- `); + // Ocultamos/eliminamos únicamente las salas + $(".sala-item").remove(); + + if ($("#mensajeSinSalas").length === 0) { + contenedor.append(` +
+ +

+ No hay salas disponibles actualmente. +

+ +
+ `); + } 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 = ` +
+ +
+ + + +
+ + ${escapeHTML( + partida.nombrePartida + )} + +
+ + + + +
+ + + +
+ + ${equiposHTML} + +
+ +
+ +
+ +
+ `; + + + $("#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 += ` -
+
+ + ${ esHost ? '' : '' } + ${escapeHTML( jugador.nombreUsuario )} +
+ ${ esHost ? ` - + + HOST + ` : "" @@ -174,18 +402,22 @@ function mostrarSalaBuscador( `; } + // ----------------------------------------------- // BOTÓN UNIRSE // ----------------------------------------------- let botonUnirseHTML = ""; + if (!usuarioYaEstaEnEquipo) { botonUnirseHTML = ` - ${ - esHost - ? botonIniciarHTML - : "" - } + ${esHost ? botonIniciarHTML : ""}
@@ -368,208 +337,159 @@ function mostrarSala(partida, equipos, jugadores) {
`; - // IMPORTANTE: - // El usuario está dentro de una única sala. - // Por eso aquí SÍ queremos reemplazar. - contenedor.html(salaHTML); + // IMPORTANTE: + // El usuario está dentro de una única sala. + // Por eso aquí SÍ queremos reemplazar. + contenedor.html(salaHTML); } - // ===================================================== // UNIRSE A UN EQUIPO // ===================================================== -$(document).on( - "click", - ".btn-unirse-equipo", - function () { - const boton = $(this); +$(document).on("click", ".btn-unirse-equipo", function () { + const boton = $(this); - const idEquipo = boton.data("id-equipo"); - const idPartida = boton.data("id-partida"); + const idEquipo = boton.data("id-equipo"); + const idPartida = boton.data("id-partida"); - boton - .prop("disabled", true) - .text("Uniéndose..."); + boton.prop("disabled", true).text("Uniéndose..."); - $.ajax({ - url: "controladores/controladorEquipoxUsuario.php", - type: "POST", - dataType: "json", + $.ajax({ + url: "controladores/controladorEquipoxUsuario.php", + type: "POST", + dataType: "json", - data: { - orden: "registrarUsuarioEnEquipo", - idEquipo: idEquipo, - }, + data: { + orden: "registrarUsuarioEnEquipo", + idEquipo: idEquipo, + }, - success: function (respuesta) { - if (respuesta.error) { - alert(respuesta.error); + success: function (respuesta) { + if (respuesta.error) { + alert(respuesta.error); - boton - .prop("disabled", false) - .text("Unirse"); + boton.prop("disabled", false).text("Unirse"); - return; - } + return; + } - usuarioYaEstaEnEquipo = true; + usuarioYaEstaEnEquipo = true; - $("#contenedorCrearSala").hide(); - $("#contenedorSalas").empty(); + $("#contenedorCrearSala").hide(); + $("#contenedorSalas").empty(); - cargarSalaUsuario(idPartida); - }, + cargarSalaUsuario(idPartida); + }, - error: function (xhr, status, error) { - console.error( - "Error al unirse al equipo:", - error - ); + error: function (xhr, status, error) { + console.error("Error al unirse al equipo:", error); - alert( - "No se ha podido unir al equipo." - ); + alert("No se ha podido unir al equipo."); - boton - .prop("disabled", false) - .text("Unirse"); - }, - }); - } -); + boton.prop("disabled", false).text("Unirse"); + }, + }); +}); // ===================================================== // ABANDONAR SALA - ABRIR MODAL // ===================================================== -$(document).on( - "click", - ".btn-abandonar-sala", - function () { - botonAbandonarReferencia = $(this); +$(document).on("click", ".btn-abandonar-sala", function () { + botonAbandonarReferencia = $(this); - const esHost = - $(this).data("es-host") === true || - $(this).data("es-host") === "true"; + const esHost = + $(this).data("es-host") === true || $(this).data("es-host") === "true"; - const titulo = - $("#modalAbandonarSalaLabel"); + const titulo = $("#modalAbandonarSalaLabel"); - const mensaje = - $("#modalAbandonarSalaMensaje"); + const mensaje = $("#modalAbandonarSalaMensaje"); - const botonConfirmar = - $("#btnConfirmarAbandonar"); + const botonConfirmar = $("#btnConfirmarAbandonar"); - if (esHost) { - titulo.text("¿Abandonar la sala?"); + if (esHost) { + titulo.text("¿Abandonar la sala?"); - mensaje.text( - "Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores." - ); - - botonConfirmar.text( - "Sí, terminar partida" - ); - } else { - titulo.text("¿Abandonar la sala?"); - - mensaje.text( - "Si sales de la sala, perderás tu lugar en el equipo." - ); - - botonConfirmar.text("Sí, salir"); - } - - const modal = new bootstrap.Modal( - document.getElementById( - "modalAbandonarSala" - ) + mensaje.text( + "Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.", ); - modal.show(); + botonConfirmar.text("Sí, terminar partida"); + } else { + titulo.text("¿Abandonar la sala?"); + + mensaje.text("Si sales de la sala, perderás tu lugar en el equipo."); + + botonConfirmar.text("Sí, salir"); } -); + + const modal = new bootstrap.Modal( + document.getElementById("modalAbandonarSala"), + ); + + modal.show(); +}); // ===================================================== // CONFIRMAR ABANDONAR SALA // ===================================================== -$(document).on( - "click", - "#btnConfirmarAbandonar", - function () { - const modalEl = - document.getElementById( - "modalAbandonarSala" - ); +$(document).on("click", "#btnConfirmarAbandonar", function () { + const modalEl = document.getElementById("modalAbandonarSala"); - const modalInstance = - bootstrap.Modal.getInstance(modalEl); + const modalInstance = bootstrap.Modal.getInstance(modalEl); - const btnConfirmar = $(this); + const btnConfirmar = $(this); - btnConfirmar - .prop("disabled", true) - .text("Saliendo..."); + btnConfirmar.prop("disabled", true).text("Saliendo..."); - $.ajax({ - url: "controladores/controladorEquipoxUsuario.php", - type: "POST", - dataType: "json", + $.ajax({ + url: "controladores/controladorEquipoxUsuario.php", + type: "POST", + dataType: "json", - data: { - orden: "salirDeSala", - }, + data: { + orden: "salirDeSala", + }, - success: function (respuesta) { - btnConfirmar - .prop("disabled", false) - .text("Sí, salir"); + success: function (respuesta) { + btnConfirmar.prop("disabled", false).text("Sí, salir"); - if (modalInstance) { - modalInstance.hide(); - } + if (modalInstance) { + modalInstance.hide(); + } - if (respuesta.error) { - alert(respuesta.error); - return; - } + if (respuesta.error) { + alert(respuesta.error); + return; + } - usuarioYaEstaEnEquipo = false; + usuarioYaEstaEnEquipo = false; - if (intervaloSala) { - clearInterval(intervaloSala); - intervaloSala = null; - } + if (intervaloSala) { + clearInterval(intervaloSala); + intervaloSala = null; + } - $("#contenedorCrearSala").show(); + $("#contenedorCrearSala").show(); - cargarSalas(); - }, + cargarSalas(); + }, - error: function (xhr, status, error) { - console.error( - "Error al salir de la sala:", - error - ); + error: function (xhr, status, error) { + console.error("Error al salir de la sala:", error); - alert( - "No se pudo salir de la sala." - ); + alert("No se pudo salir de la sala."); - btnConfirmar - .prop("disabled", false) - .text("Sí, salir"); + btnConfirmar.prop("disabled", false).text("Sí, salir"); - if (modalInstance) { - modalInstance.hide(); - } - }, - }); - } -); + if (modalInstance) { + modalInstance.hide(); + } + }, + }); +}); // ===================================================== // AUXILIARES @@ -581,29 +501,19 @@ function escapeHTML(texto) { .html(); } -function mostrarEquipos( - partida, - equipos, - jugadores -) { +function mostrarEquipos(partida, equipos, jugadores) { let equiposHTML = ""; equipos.forEach(function (equipo) { - const jugadoresEquipo = - jugadores.filter(function (jugador) { - return ( - jugador.idEquipo == - equipo.idEquipo - ); - }); + const jugadoresEquipo = jugadores.filter(function (jugador) { + return jugador.idEquipo == equipo.idEquipo; + }); let jugadoresHTML = ""; if (jugadoresEquipo.length > 0) { jugadoresEquipo.forEach(function (jugador) { - const esHost = - jugador.idUsuario == - partida.idUsuario; + const esHost = jugador.idUsuario == partida.idUsuario; jugadoresHTML += `
- ${escapeHTML( - equipo.nombreEquipo - )} + ${escapeHTML(equipo.nombreEquipo)}
@@ -660,6 +566,5 @@ function mostrarEquipos( `; }); - $("#contenedorSalas .equipos") - .html(equiposHTML); + $("#contenedorSalas .equipos").html(equiposHTML); }