diff --git a/js/buscadorSala.js b/js/buscadorSala.js index ae10912..0799c12 100644 --- a/js/buscadorSala.js +++ b/js/buscadorSala.js @@ -1,41 +1,21 @@ -// ===================================================== -// 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; } @@ -46,7 +26,6 @@ function cargarSalas() { url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "listar", }, @@ -54,15 +33,7 @@ function cargarSalas() { success: function (partidas) { const contenedor = $("#contenedorSalas"); - // ================================================= - // NO HAY SALAS - // ================================================= - - if ( - !Array.isArray(partidas) || - partidas.length === 0 - ) { - // Ocultamos/eliminamos únicamente las salas + if (!Array.isArray(partidas) || partidas.length === 0) { $(".sala-item").remove(); if ($("#mensajeSinSalas").length === 0) { @@ -82,43 +53,20 @@ function cargarSalas() { return; } - - // ================================================= - // 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") - ); + const idPartida = String($(this).data("id-partida")); if (!idsPartidas.includes(idPartida)) { $(this).remove(); } }); - - // ================================================= - // ACTUALIZAR / CREAR CADA SALA - // ================================================= - partidas.forEach(function (partida) { cargarSalaBuscador(partida); }); @@ -137,17 +85,11 @@ function cargarSalas() { }); } - -// ===================================================== -// CARGAR INFORMACIÓN DE UNA SALA -// ===================================================== - function cargarSalaBuscador(partida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "getEquipos", idPartida: partida.idPartida, @@ -158,13 +100,25 @@ function cargarSalaBuscador(partida) { url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "getJugadores", idPartida: partida.idPartida, }, success: function (jugadores) { + if ( + !Array.isArray(jugadores) || + jugadores.length === 0 + ) { + $( + `.sala-item[data-id-partida="${partida.idPartida}"]` + ).remove(); + + comprobarSiNoHaySalas(); + + return; + } + actualizarSalaBuscador( partida, equipos, @@ -190,26 +144,36 @@ function cargarSalaBuscador(partida) { }); } +function comprobarSiNoHaySalas() { + if ($(".sala-item").length === 0) { + if ($("#mensajeSinSalas").length === 0) { + $("#contenedorSalas").append(` +
-// ===================================================== -// ACTUALIZAR UNA SALA -// ===================================================== +

+ No hay salas disponibles actualmente. +

+ +
+ `); + } + } +} function actualizarSalaBuscador( partida, equipos, jugadores ) { + $("#mensajeSinSalas").remove(); + const selectorSala = `.sala-item[data-id-partida="${partida.idPartida}"]`; const salaExistente = $(selectorSala); - - // =================================================== - // SI LA SALA NO EXISTE → CREARLA - // =================================================== - if (salaExistente.length === 0) { crearSalaBuscador( partida, @@ -220,17 +184,6 @@ function actualizarSalaBuscador( return; } - - // =================================================== - // LA SALA YA EXISTE - // =================================================== - // - // NO TOCAMOS LA TARJETA COMPLETA. - // - // Solo actualizamos .equipos - // - - const equiposHTML = generarEquiposHTML( partida, @@ -238,22 +191,18 @@ function actualizarSalaBuscador( jugadores ); - salaExistente .find(".equipos") .html(equiposHTML); } - -// ===================================================== -// CREAR UNA SALA NUEVA -// ===================================================== - function crearSalaBuscador( partida, equipos, jugadores ) { + $("#mensajeSinSalas").remove(); + const equiposHTML = generarEquiposHTML( partida, @@ -261,7 +210,6 @@ function crearSalaBuscador( jugadores ); - const salaHTML = `
- -
- ${escapeHTML( - partida.nombrePartida - )} + ${escapeHTML(partida.nombrePartida)}
- - -
- -
${equiposHTML} @@ -304,17 +239,9 @@ function crearSalaBuscador(
`; - - $("#contenedorSalas").append( - salaHTML - ); + $("#contenedorSalas").append(salaHTML); } - -// ===================================================== -// GENERAR HTML DE EQUIPOS Y JUGADORES -// ===================================================== - function generarEquiposHTML( partida, equipos, @@ -322,78 +249,61 @@ function generarEquiposHTML( ) { let equiposHTML = ""; - equipos.forEach(function (equipo) { - // ----------------------------------------------- - // JUGADORES DE ESTE EQUIPO - // ----------------------------------------------- - const jugadoresEquipo = - jugadores.filter( - function (jugador) { - return ( - jugador.idEquipo == - equipo.idEquipo - ); - } - ); - + jugadores.filter(function (jugador) { + return ( + jugador.idEquipo == + equipo.idEquipo + ); + }); let jugadoresHTML = ""; - - // ----------------------------------------------- - // MOSTRAR JUGADORES - // ----------------------------------------------- - if (jugadoresEquipo.length > 0) { - jugadoresEquipo.forEach( - function (jugador) { - const esHost = - jugador.idUsuario == - partida.idUsuario; + jugadoresEquipo.forEach(function (jugador) { + const esHost = + jugador.idUsuario == + partida.idUsuario; + jugadoresHTML += ` +
- jugadoresHTML += ` -
+
-
+ - + ${ + esHost + ? '' + : '' + } - ${ - esHost - ? '' - : '' - } + - - - ${escapeHTML( - jugador.nombreUsuario - )} - -
- - - ${ - esHost - ? ` - - - HOST - - - ` - : "" - } + ${escapeHTML( + jugador.nombreUsuario + )}
- `; - } - ); + + ${ + esHost + ? ` + + + HOST + + + ` + : "" + } + +
+ `; + }); } else { jugadoresHTML = `
@@ -402,22 +312,14 @@ function generarEquiposHTML( `; } - - // ----------------------------------------------- - // BOTÓN UNIRSE - // ----------------------------------------------- - let botonUnirseHTML = ""; - if (!usuarioYaEstaEnEquipo) { botonUnirseHTML = ` - - ${esHost ? botonIniciarHTML : ""} - -
- -
- -
- -
- `; - - // 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); - - const idEquipo = boton.data("id-equipo"); - const idPartida = boton.data("id-partida"); - - boton.prop("disabled", true).text("Uniéndose..."); - - $.ajax({ - url: "controladores/controladorEquipoxUsuario.php", - type: "POST", - dataType: "json", - - data: { - orden: "registrarUsuarioEnEquipo", - idEquipo: idEquipo, - }, - - success: function (respuesta) { - if (respuesta.error) { - alert(respuesta.error); - - boton.prop("disabled", false).text("Unirse"); - - return; - } - - usuarioYaEstaEnEquipo = true; - - $("#contenedorCrearSala").hide(); - $("#contenedorSalas").empty(); - - cargarSalaUsuario(idPartida); - }, - - error: function (xhr, status, error) { - console.error("Error al unirse al equipo:", error); - - alert("No se ha podido unir al equipo."); - - boton.prop("disabled", false).text("Unirse"); - }, - }); -}); - -// ===================================================== -// ABANDONAR SALA - ABRIR MODAL -// ===================================================== - -$(document).on("click", ".btn-abandonar-sala", function () { - botonAbandonarReferencia = $(this); - - const esHost = - $(this).data("es-host") === true || $(this).data("es-host") === "true"; - - const titulo = $("#modalAbandonarSalaLabel"); - - const mensaje = $("#modalAbandonarSalaMensaje"); - - const botonConfirmar = $("#btnConfirmarAbandonar"); - - if (esHost) { - titulo.text("¿Abandonar la sala?"); - - mensaje.text( - "Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.", - ); - - botonConfirmar.text("Sí, 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"); - - const modalInstance = bootstrap.Modal.getInstance(modalEl); - - const btnConfirmar = $(this); - - btnConfirmar.prop("disabled", true).text("Saliendo..."); - - $.ajax({ - url: "controladores/controladorEquipoxUsuario.php", - type: "POST", - dataType: "json", - - data: { - orden: "salirDeSala", - }, - - success: function (respuesta) { - btnConfirmar.prop("disabled", false).text("Sí, salir"); - - if (modalInstance) { - modalInstance.hide(); - } - - if (respuesta.error) { - alert(respuesta.error); - return; - } - - usuarioYaEstaEnEquipo = false; - - if (intervaloSala) { - clearInterval(intervaloSala); - intervaloSala = null; - } - - $("#contenedorCrearSala").show(); - - cargarSalas(); - }, - - error: function (xhr, status, error) { - console.error("Error al salir de la sala:", error); - - alert("No se pudo salir de la sala."); - - btnConfirmar.prop("disabled", false).text("Sí, salir"); - - if (modalInstance) { - modalInstance.hide(); - } - }, - }); -}); - -// ===================================================== -// AUXILIARES -// ===================================================== - -function escapeHTML(texto) { - return $("
") - .text(texto ?? "") - .html(); -} - -function mostrarEquipos(partida, equipos, jugadores) { - let equiposHTML = ""; - equipos.forEach(function (equipo) { const jugadoresEquipo = jugadores.filter(function (jugador) { return jugador.idEquipo == equipo.idEquipo; @@ -566,5 +257,294 @@ function mostrarEquipos(partida, equipos, jugadores) { `; }); - $("#contenedorSalas .equipos").html(equiposHTML); + const esHost = partida.idUsuario == idUsuarioSesion; + + let botonIniciarHTML = ""; + + if (esHost) { + botonIniciarHTML = ` + + + + ¡Iniciar Partida! + + + `; + } + + const salaHTML = ` +
+ +
+ +
+ ${escapeHTML(partida.nombrePartida)} +
+ +
+ +
+ ${equiposHTML} +
+ +
+ + + + ${esHost ? botonIniciarHTML : ""} + +
+ +
+ +
+ +
+ `; + + contenedor.html(salaHTML); } + +$(document).on("click", ".btn-unirse-equipo", function () { + const boton = $(this); + + const idEquipo = boton.data("id-equipo"); + const idPartida = boton.data("id-partida"); + + boton.prop("disabled", true).text("Uniéndose..."); + + $.ajax({ + url: "controladores/controladorEquipoxUsuario.php", + type: "POST", + dataType: "json", + + data: { + orden: "registrarUsuarioEnEquipo", + idEquipo: idEquipo, + }, + + success: function (respuesta) { + if (respuesta.error) { + alert(respuesta.error); + + boton.prop("disabled", false).text("Unirse"); + + return; + } + + usuarioYaEstaEnEquipo = true; + + $("#contenedorCrearSala").hide(); + $("#contenedorSalas").empty(); + + cargarSalaUsuario(idPartida); + }, + + error: function (xhr, status, error) { + console.error("Error al unirse al equipo:", error); + + alert("No se ha podido unir al equipo."); + + boton.prop("disabled", false).text("Unirse"); + }, + }); +}); + +$(document).on("click", ".btn-abandonar-sala", function () { + botonAbandonarReferencia = $(this); + + const esHost = + $(this).data("es-host") === true || + $(this).data("es-host") === "true"; + + const titulo = $("#modalAbandonarSalaLabel"); + + const mensaje = $("#modalAbandonarSalaMensaje"); + + const botonConfirmar = $("#btnConfirmarAbandonar"); + + if (esHost) { + titulo.text("¿Abandonar la sala?"); + + mensaje.text( + "Si abandonas la sala como anfitrión, la partida terminará para todos los jugadores.", + ); + + botonConfirmar.text("Sí, 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(); +}); + +$(document).on("click", "#btnConfirmarAbandonar", function () { + const modalEl = + document.getElementById("modalAbandonarSala"); + + const modalInstance = + bootstrap.Modal.getInstance(modalEl); + + const btnConfirmar = $(this); + + btnConfirmar + .prop("disabled", true) + .text("Saliendo..."); + + $.ajax({ + url: "controladores/controladorEquipoxUsuario.php", + type: "POST", + dataType: "json", + + data: { + orden: "salirDeSala", + }, + + success: function (respuesta) { + btnConfirmar + .prop("disabled", false) + .text("Sí, salir"); + + if (modalInstance) { + modalInstance.hide(); + } + + if (respuesta.error) { + alert(respuesta.error); + return; + } + + usuarioYaEstaEnEquipo = false; + + if (intervaloSala) { + clearInterval(intervaloSala); + intervaloSala = null; + } + + $("#contenedorSalas").empty(); + + $("#contenedorCrearSala").show(); + + iniciarActualizacionSalas(); + }, + + error: function (xhr, status, error) { + console.error( + "Error al salir de la sala:", + error + ); + + alert("No se pudo salir de la sala."); + + btnConfirmar + .prop("disabled", false) + .text("Sí, salir"); + + if (modalInstance) { + modalInstance.hide(); + } + }, + }); +}); + +function escapeHTML(texto) { + return $("
") + .text(texto ?? "") + .html(); +} + +function mostrarEquipos( + partida, + equipos, + jugadores +) { + let equiposHTML = ""; + + equipos.forEach(function (equipo) { + 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; + + jugadoresHTML += ` +
+ +
+ + ${ + esHost + ? '' + : '' + } + + + ${escapeHTML( + jugador.nombreUsuario + )} +
+ + ${ + esHost + ? ` + HOST + ` + : "" + } + +
+ `; + }); + } else { + jugadoresHTML = ` +
+ Sin jugadores +
+ `; + } + + equiposHTML += ` +
+ +
+ ${escapeHTML(equipo.nombreEquipo)} +
+ +
+ ${jugadoresHTML} +
+ +
+ `; + }); + + $("#contenedorSalas .equipos").html(equiposHTML); +} \ No newline at end of file