From fdd1ba8272617c1a7d519989686b8fe49761f8dc Mon Sep 17 00:00:00 2001 From: alexis Date: Thu, 1 Oct 2026 13:18:11 +0200 Subject: [PATCH 1/4] Add actualizacion de jugadores dentro de sala cada 5 segundos --- js/buscadorSala.js | 205 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 193 insertions(+), 12 deletions(-) diff --git a/js/buscadorSala.js b/js/buscadorSala.js index e6a97d9..4ec3803 100644 --- a/js/buscadorSala.js +++ b/js/buscadorSala.js @@ -33,22 +33,131 @@ function comprobarSalaUsuario() { } // 2. Cargar únicamente la sala en la que está metido el usuario +let intervaloSala = null; + function cargarSalaUsuario(idPartida) { + // Primera carga completa + cargarSalaCompleta(idPartida); + + // Evitamos crear varios intervalos + if (intervaloSala) { + clearInterval(intervaloSala); + } + + intervaloSala = setInterval(() => { + actualizarSalaUsuario(idPartida); + }, 5000); +} + +function cargarSalaCompleta(idPartida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "buscar", idPartida: idPartida }, + data: { + orden: "buscar", + idPartida: idPartida, + }, + success: function (partida) { if (partida.error) { console.error(partida.error); return; } - $("#contenedorSalas").empty(); + + cargarInformacionSalaCompleta(partida); + }, + + error: function (xhr, status, error) { + console.error("Error al obtener la sala:", error); + }, + }); +} + +function cargarInformacionSalaCompleta(partida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getEquipos", + idPartida: partida.idPartida, + }, + + success: function (equipos) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getJugadores", + idPartida: partida.idPartida, + }, + + success: function (jugadores) { + // AQUÍ hacemos la primera construcción completa + mostrarSala(partida, equipos, jugadores); + }, + + error: function (xhr, status, error) { + console.error("Error al obtener jugadores:", error); + }, + }); + }, + + error: function (xhr, status, error) { + console.error("Error al obtener equipos:", error); + }, + }); +} + +function actualizarSalaUsuario(idPartida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "buscar", + idPartida: idPartida, + }, + + success: function (partida) { + if (partida.error) { + console.error(partida.error); + return; + } + cargarInformacionSala(partida); }, + error: function (xhr, status, error) { - console.error("Error al obtener la sala del usuario:", error); + console.error("Error al actualizar la sala:", error); + }, + }); +} + +function actualizarSalaUsuario(idPartida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + data: { + orden: "buscar", + idPartida: idPartida, + }, + success: function (partida) { + if (partida.error) { + console.error(partida.error); + return; + } + + cargarInformacionSala(partida, true); + }, + error: function (xhr, status, error) { + console.error("Error al obtener la sala:", error); }, }); } @@ -74,7 +183,7 @@ function cargarSalas() { } partidas.forEach(function (partida) { - cargarInformacionSala(partida); + cargarInformacionSalaCompleta(partida); }); }, error: function (xhr, status, error) { @@ -89,15 +198,21 @@ function cargarInformacionSala(partida) { url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "getEquipos", idPartida: partida.idPartida }, + data: { + orden: "getEquipos", + idPartida: partida.idPartida, + }, success: function (equipos) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "getJugadores", idPartida: partida.idPartida }, + data: { + orden: "getJugadores", + idPartida: partida.idPartida, + }, success: function (jugadores) { - mostrarSala(partida, equipos, jugadores); + mostrarEquipos(partida, equipos, jugadores); }, error: function (xhr, status, error) { console.error("Error al obtener jugadores:", error); @@ -266,7 +381,8 @@ let botonAbandonarReferencia = null; $(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 mensaje = $("#modalAbandonarSalaMensaje"); const botonConfirmar = $("#btnConfirmarAbandonar"); @@ -279,9 +395,7 @@ $(document).on("click", ".btn-abandonar-sala", function () { 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.", - ); + mensaje.text("Si sales de la sala, perderás tu lugar en el equipo."); botonConfirmar.text("Sí, salir"); } @@ -292,7 +406,6 @@ $(document).on("click", ".btn-abandonar-sala", function () { modal.show(); }); - // B. Al hacer clic en "Sí, salir" dentro del modal Kahoot $(document).on("click", "#btnConfirmarAbandonar", function () { const modalEl = document.getElementById("modalAbandonarSala"); @@ -433,3 +546,71 @@ $(document).on("input", ".input-kahoot", function () { $(this).removeClass("is-invalid"); $(this).next(".mensaje-error-sala").remove(); }); + +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} +
+ +
+ `; + }); + + // IMPORTANTE: + // Solo modificamos .equipos + $("#contenedorSalas .equipos").html(equiposHTML); +} From 84537357274a7e0e88fecc1bf7e09835c1f0171a Mon Sep 17 00:00:00 2001 From: alexis Date: Thu, 1 Oct 2026 13:42:48 +0200 Subject: [PATCH 2/4] Dividido buscadorSala.js en dos archivos para facilitar la modificacion --- buscadorSala.php | 5 +- js/buscadorSala.js | 907 +++++++++++++++++++-------------------------- js/sala.js | 665 +++++++++++++++++++++++++++++++++ 3 files changed, 1049 insertions(+), 528 deletions(-) create mode 100644 js/sala.js diff --git a/buscadorSala.php b/buscadorSala.php index f4d33d8..9128365 100644 --- a/buscadorSala.php +++ b/buscadorSala.php @@ -22,7 +22,7 @@
- + Volver al Inicio @@ -100,7 +100,10 @@ + + + \ No newline at end of file diff --git a/js/buscadorSala.js b/js/buscadorSala.js index 4ec3803..f0b966f 100644 --- a/js/buscadorSala.js +++ b/js/buscadorSala.js @@ -1,592 +1,171 @@ -let usuarioYaEstaEnEquipo = false; +// ===================================================== +// CARGAR LISTA DE SALAS +// ===================================================== -$(document).ready(function () { - comprobarSalaUsuario(); -}); - -// 1. Comprobar si el usuario actual ya pertenece a una sala -function comprobarSalaUsuario() { - $("#cargandoSalas").remove(); - - $.ajax({ - url: "controladores/controladorEquipoxUsuario.php", - type: "POST", - dataType: "json", - data: { orden: "obtenerSalaUsuario" }, - success: function (respuesta) { - if (respuesta.error || !respuesta.asociado) { - usuarioYaEstaEnEquipo = false; - $("#contenedorCrearSala").show(); - cargarSalas(); - } else { - usuarioYaEstaEnEquipo = true; - $("#contenedorCrearSala").hide(); // Ocultar "Crear Sala" si ya pertenece a una - cargarSalaUsuario(respuesta.idPartida); - } - }, - error: function (xhr, status, error) { - console.error("Error al comprobar la sala del usuario:", error); - usuarioYaEstaEnEquipo = false; - cargarSalas(); - }, - }); -} - -// 2. Cargar únicamente la sala en la que está metido el usuario -let intervaloSala = null; - -function cargarSalaUsuario(idPartida) { - // Primera carga completa - cargarSalaCompleta(idPartida); - - // Evitamos crear varios intervalos - if (intervaloSala) { - clearInterval(intervaloSala); - } - - intervaloSala = setInterval(() => { - actualizarSalaUsuario(idPartida); - }, 5000); -} - -function cargarSalaCompleta(idPartida) { - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - data: { - orden: "buscar", - idPartida: idPartida, - }, - - success: function (partida) { - if (partida.error) { - console.error(partida.error); - return; - } - - cargarInformacionSalaCompleta(partida); - }, - - error: function (xhr, status, error) { - console.error("Error al obtener la sala:", error); - }, - }); -} - -function cargarInformacionSalaCompleta(partida) { - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - - data: { - orden: "getEquipos", - idPartida: partida.idPartida, - }, - - success: function (equipos) { - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - - data: { - orden: "getJugadores", - idPartida: partida.idPartida, - }, - - success: function (jugadores) { - // AQUÍ hacemos la primera construcción completa - mostrarSala(partida, equipos, jugadores); - }, - - error: function (xhr, status, error) { - console.error("Error al obtener jugadores:", error); - }, - }); - }, - - error: function (xhr, status, error) { - console.error("Error al obtener equipos:", error); - }, - }); -} - -function actualizarSalaUsuario(idPartida) { - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - - data: { - orden: "buscar", - idPartida: idPartida, - }, - - success: function (partida) { - if (partida.error) { - console.error(partida.error); - return; - } - - cargarInformacionSala(partida); - }, - - error: function (xhr, status, error) { - console.error("Error al actualizar la sala:", error); - }, - }); -} - -function actualizarSalaUsuario(idPartida) { - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - data: { - orden: "buscar", - idPartida: idPartida, - }, - success: function (partida) { - if (partida.error) { - console.error(partida.error); - return; - } - - cargarInformacionSala(partida, true); - }, - error: function (xhr, status, error) { - console.error("Error al obtener la sala:", error); - }, - }); -} - -// 3. Cargar la lista completa de todas las salas function cargarSalas() { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", - data: { orden: "listar" }, + + data: { + orden: "listar", + }, + success: function (partidas) { const contenedor = $("#contenedorSalas"); + contenedor.empty(); - if (!Array.isArray(partidas) || partidas.length === 0) { + if ( + !Array.isArray(partidas) || + partidas.length === 0 + ) { contenedor.html(`
-

No hay salas disponibles actualmente.

+

+ No hay salas disponibles actualmente. +

`); + return; } + // Cargar cada sala individualmente partidas.forEach(function (partida) { - cargarInformacionSalaCompleta(partida); + cargarSalaBuscador(partida); }); }, + error: function (xhr, status, error) { - console.error("Error al obtener las partidas:", error); + console.error( + "Error al obtener las partidas:", + error + ); }, }); } -// 4. Obtener equipos y jugadores asociados a una sala concreta -function cargarInformacionSala(partida) { + +// ===================================================== +// CARGAR INFORMACIÓN DE UNA SALA DEL BUSCADOR +// ===================================================== + +function cargarSalaBuscador(partida) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", + data: { orden: "getEquipos", idPartida: partida.idPartida, }, + success: function (equipos) { $.ajax({ url: "controladores/controladorPartida.php", type: "POST", dataType: "json", + data: { orden: "getJugadores", idPartida: partida.idPartida, }, + success: function (jugadores) { - mostrarEquipos(partida, equipos, jugadores); + mostrarSalaBuscador( + partida, + equipos, + jugadores + ); }, + error: function (xhr, status, error) { - console.error("Error al obtener jugadores:", error); + console.error( + "Error al obtener jugadores:", + error + ); }, }); }, + error: function (xhr, status, error) { - console.error("Error al obtener equipos:", error); + console.error( + "Error al obtener equipos:", + error + ); }, }); } -// 5. Renderizar el HTML de la sala y botones según estado -function mostrarSala(partida, equipos, jugadores) { - const contenedor = $("#contenedorSalas"); + +// ===================================================== +// MOSTRAR UNA SALA EN EL BUSCADOR +// ===================================================== + +function mostrarSalaBuscador( + 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` - : "" + const jugadoresEquipo = jugadores.filter( + function (jugador) { + return ( + jugador.idEquipo == + equipo.idEquipo + ); } -
- `; - }); - } else { - jugadoresHTML = `
Sin jugadores
`; - } - - // Botón "Unirse" solo visible si NO pertenece a ningún equipo - let botonUnirseHTML = ""; - if (!usuarioYaEstaEnEquipo) { - botonUnirseHTML = ` - - `; - } - - equiposHTML += ` -
-
${escapeHTML(equipo.nombreEquipo)}
-
- ${jugadoresHTML} -
- ${botonUnirseHTML} -
- `; - }); - - // Acciones disponibles si el usuario YA ESTÁ dentro de esta sala - // Acciones disponibles si el usuario YA ESTÁ dentro de esta sala - let accionesSalaHTML = ""; - - if (usuarioYaEstaEnEquipo) { - const esHost = partida.idUsuario == idUsuarioSesion; - let botonIniciarHTML = ""; - - // Solo el host puede iniciar la partida - if (esHost) { - botonIniciarHTML = ` - - ¡Iniciar Partida! - - `; - } - - accionesSalaHTML = ` -
- - - - ${botonIniciarHTML} - -
- `; - } - - const salaHTML = ` -
-
-
- ${escapeHTML(partida.nombrePartida)} -
-
-
- ${equiposHTML} -
- ${accionesSalaHTML} -
-
-
- `; - - contenedor.append(salaHTML); -} - -// 6. Evento: 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"); - }, - }); -}); - -// 7. Evento: Abandonar Sala -// Guardamos temporalmente el botón presionado -let botonAbandonarReferencia = null; - -// A. Al hacer clic en el botón "Abandonar sala" de la tarjeta, abrimos el 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(); -}); - -// B. Al hacer clic en "Sí, salir" dentro del modal Kahoot -$(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; - } - - // Restablecemos la interfaz a la lista completa de salas - usuarioYaEstaEnEquipo = false; - $("#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(); - } - }, - }); -}); -// 8. Evento: Crear Sala -$("#btnCrearSala").on("click", function () { - const nombreSala = $("#nombreSala").val().trim(); - const nombreEquipo1 = $("#nombreEquipo1").val().trim(); - const nombreEquipo2 = $("#nombreEquipo2").val().trim(); - - let valido = true; - $(".mensaje-error-sala").remove(); - $(".input-kahoot").removeClass("is-invalid"); - - if (nombreSala === "" || nombreSala.length < 3) { - mostrarError( - "#nombreSala", - "El nombre de la sala debe tener al menos 3 caracteres.", - ); - valido = false; - } - - if (nombreEquipo1 === "" || nombreEquipo1.length < 2) { - mostrarError( - "#nombreEquipo1", - "El nombre del equipo debe tener al menos 2 caracteres.", - ); - valido = false; - } - - if (nombreEquipo2 === "" || nombreEquipo2.length < 2) { - mostrarError( - "#nombreEquipo2", - "El nombre del equipo debe tener al menos 2 caracteres.", - ); - valido = false; - } - - if ( - nombreEquipo1 !== "" && - nombreEquipo2 !== "" && - nombreEquipo1.toLowerCase() === nombreEquipo2.toLowerCase() - ) { - mostrarError( - "#nombreEquipo2", - "Los dos equipos deben tener nombres diferentes.", - ); - valido = false; - } - - if (!valido) return; - - const boton = $("#btnCrearSala"); - boton.prop("disabled", true).text("Creando sala..."); - - $.ajax({ - url: "controladores/controladorPartida.php", - type: "POST", - dataType: "json", - data: { - orden: "crear", - nombrePartida: nombreSala, - nombreEquipo1: nombreEquipo1, - nombreEquipo2: nombreEquipo2, - }, - success: function (respuesta) { - if (respuesta.error) { - alert(respuesta.error); - boton.prop("disabled", false).text("Crear sala"); - return; - } - - if (respuesta.exito) { - $("#modalCrearSala").modal("hide"); - location.reload(); - } - }, - error: function (xhr, status, error) { - console.error("Error al crear la sala:", error); - alert("No se ha podido crear la sala."); - boton.prop("disabled", false).text("Crear sala"); - }, - }); -}); - -// Auxiliares -function escapeHTML(texto) { - return $("
") - .text(texto ?? "") - .html(); -} - -function mostrarError(selector, mensaje) { - const input = $(selector); - input.addClass("is-invalid"); - input.after( - `
${mensaje}
`, - ); -} - -$(document).on("input", ".input-kahoot", function () { - $(this).removeClass("is-invalid"); - $(this).next(".mensaje-error-sala").remove(); -}); - -function mostrarEquipos(partida, equipos, jugadores) { - let equiposHTML = ""; - - equipos.forEach(function (equipo) { - const jugadoresEquipo = jugadores.filter(function (jugador) { - return jugador.idEquipo == equipo.idEquipo; - }); let jugadoresHTML = ""; + // ----------------------------------------------- + // JUGADORES DEL EQUIPO + // ----------------------------------------------- + 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 = `
@@ -595,22 +174,296 @@ function mostrarEquipos(partida, equipos, jugadores) { `; } + // ----------------------------------------------- + // BOTÓN UNIRSE + // ----------------------------------------------- + + let botonUnirseHTML = ""; + + if (!usuarioYaEstaEnEquipo) { + botonUnirseHTML = ` + + `; + } + + // ----------------------------------------------- + // EQUIPO + // ----------------------------------------------- + equiposHTML += `
- ${escapeHTML(equipo.nombreEquipo)} + ${escapeHTML( + equipo.nombreEquipo + )}
${jugadoresHTML}
+ ${botonUnirseHTML} +
`; }); - // IMPORTANTE: - // Solo modificamos .equipos - $("#contenedorSalas .equipos").html(equiposHTML); + + // ================================================= + // TARJETA DE LA SALA + // ================================================= + + const salaHTML = ` +
+ +
+ +
+ ${escapeHTML( + partida.nombrePartida + )} +
+ +
+ +
+ ${equiposHTML} +
+ +
+ +
+ +
+ `; + + + // ================================================= + // 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 + ); } + + +// ===================================================== +// CREAR SALA +// ===================================================== + +$("#btnCrearSala").on( + "click", + function () { + const nombreSala = + $("#nombreSala").val().trim(); + + const nombreEquipo1 = + $("#nombreEquipo1").val().trim(); + + const nombreEquipo2 = + $("#nombreEquipo2").val().trim(); + + let valido = true; + + // Limpiar errores anteriores + $(".mensaje-error-sala").remove(); + + $(".input-kahoot") + .removeClass("is-invalid"); + + + // ----------------------------------------------- + // VALIDAR NOMBRE DE SALA + // ----------------------------------------------- + + if ( + nombreSala === "" || + nombreSala.length < 3 + ) { + mostrarError( + "#nombreSala", + "El nombre de la sala debe tener al menos 3 caracteres." + ); + + valido = false; + } + + + // ----------------------------------------------- + // VALIDAR EQUIPO 1 + // ----------------------------------------------- + + if ( + nombreEquipo1 === "" || + nombreEquipo1.length < 2 + ) { + mostrarError( + "#nombreEquipo1", + "El nombre del equipo debe tener al menos 2 caracteres." + ); + + valido = false; + } + + + // ----------------------------------------------- + // VALIDAR EQUIPO 2 + // ----------------------------------------------- + + if ( + nombreEquipo2 === "" || + nombreEquipo2.length < 2 + ) { + mostrarError( + "#nombreEquipo2", + "El nombre del equipo debe tener al menos 2 caracteres." + ); + + valido = false; + } + + + // ----------------------------------------------- + // LOS EQUIPOS NO PUEDEN TENER EL MISMO NOMBRE + // ----------------------------------------------- + + if ( + nombreEquipo1 !== "" && + nombreEquipo2 !== "" && + nombreEquipo1.toLowerCase() === + nombreEquipo2.toLowerCase() + ) { + mostrarError( + "#nombreEquipo2", + "Los dos equipos deben tener nombres diferentes." + ); + + valido = false; + } + + + // Si hay errores, no continuar + if (!valido) { + return; + } + + + // ----------------------------------------------- + // DESACTIVAR BOTÓN + // ----------------------------------------------- + + const boton = $("#btnCrearSala"); + + boton + .prop("disabled", true) + .text("Creando sala..."); + + + // ----------------------------------------------- + // CREAR SALA + // ----------------------------------------------- + + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "crear", + nombrePartida: nombreSala, + nombreEquipo1: nombreEquipo1, + nombreEquipo2: nombreEquipo2, + }, + + success: function (respuesta) { + if (respuesta.error) { + alert(respuesta.error); + + boton + .prop("disabled", false) + .text("Crear sala"); + + return; + } + + + if (respuesta.exito) { + $("#modalCrearSala").modal( + "hide" + ); + + location.reload(); + } + }, + + error: function (xhr, status, error) { + console.error( + "Error al crear la sala:", + error + ); + + alert( + "No se ha podido crear la sala." + ); + + boton + .prop("disabled", false) + .text("Crear sala"); + }, + }); + } +); + + +// ===================================================== +// MOSTRAR ERROR DE VALIDACIÓN +// ===================================================== + +function mostrarError( + selector, + mensaje +) { + const input = $(selector); + + input.addClass("is-invalid"); + + input.after(` +
+ ${mensaje} +
+ `); +} + + +// ===================================================== +// LIMPIAR ERRORES AL ESCRIBIR +// ===================================================== + +$(document).on( + "input", + ".input-kahoot", + function () { + $(this) + .removeClass("is-invalid"); + + $(this) + .next(".mensaje-error-sala") + .remove(); + } +); diff --git a/js/sala.js b/js/sala.js new file mode 100644 index 0000000..b12547e --- /dev/null +++ b/js/sala.js @@ -0,0 +1,665 @@ +let usuarioYaEstaEnEquipo = false; +let intervaloSala = null; +let botonAbandonarReferencia = null; + +$(document).ready(function () { + comprobarSalaUsuario(); +}); + +// ===================================================== +// COMPROBAR SI EL USUARIO YA ESTÁ EN UNA SALA +// ===================================================== + +function comprobarSalaUsuario() { + $("#cargandoSalas").remove(); + + $.ajax({ + url: "controladores/controladorEquipoxUsuario.php", + type: "POST", + dataType: "json", + data: { + orden: "obtenerSalaUsuario", + }, + + success: function (respuesta) { + if (respuesta.error || !respuesta.asociado) { + usuarioYaEstaEnEquipo = false; + + $("#contenedorCrearSala").show(); + + cargarSalas(); + } else { + usuarioYaEstaEnEquipo = true; + + $("#contenedorCrearSala").hide(); + + cargarSalaUsuario(respuesta.idPartida); + } + }, + + error: function (xhr, status, error) { + console.error( + "Error al comprobar la sala del usuario:", + error + ); + + usuarioYaEstaEnEquipo = false; + + $("#contenedorCrearSala").show(); + + cargarSalas(); + }, + }); +} + +// ===================================================== +// CARGAR SALA DEL USUARIO +// ===================================================== + +function cargarSalaUsuario(idPartida) { + // Primera carga completa + cargarSalaCompleta(idPartida); + + // Evitar intervalos duplicados + if (intervaloSala) { + clearInterval(intervaloSala); + } + + intervaloSala = setInterval(function () { + actualizarSalaUsuario(idPartida); + }, 5000); +} + +// ===================================================== +// CARGA COMPLETA DE LA SALA +// ===================================================== + +function cargarSalaCompleta(idPartida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "buscar", + idPartida: idPartida, + }, + + success: function (partida) { + if (partida.error) { + console.error(partida.error); + return; + } + + cargarInformacionSalaCompleta(partida); + }, + + error: function (xhr, status, error) { + console.error( + "Error al obtener la sala:", + error + ); + }, + }); +} + +// ===================================================== +// OBTENER EQUIPOS Y JUGADORES +// ===================================================== + +function cargarInformacionSalaCompleta(partida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getEquipos", + idPartida: partida.idPartida, + }, + + success: function (equipos) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getJugadores", + idPartida: partida.idPartida, + }, + + success: function (jugadores) { + mostrarSala(partida, equipos, jugadores); + }, + + error: function (xhr, status, error) { + console.error( + "Error al obtener jugadores:", + error + ); + }, + }); + }, + + error: function (xhr, status, error) { + console.error( + "Error al obtener equipos:", + error + ); + }, + }); +} + +// ===================================================== +// ACTUALIZAR SALA CADA 5 SEGUNDOS +// ===================================================== + +function actualizarSalaUsuario(idPartida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "buscar", + idPartida: idPartida, + }, + + success: function (partida) { + if (partida.error) { + console.error(partida.error); + return; + } + + cargarInformacionSala(partida); + }, + + error: function (xhr, status, error) { + console.error( + "Error al actualizar la sala:", + error + ); + }, + }); +} + +// ===================================================== +// OBTENER INFORMACIÓN PARA ACTUALIZACIÓN +// ===================================================== + +function cargarInformacionSala(partida) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getEquipos", + idPartida: partida.idPartida, + }, + + success: function (equipos) { + $.ajax({ + url: "controladores/controladorPartida.php", + type: "POST", + dataType: "json", + + data: { + orden: "getJugadores", + idPartida: partida.idPartida, + }, + + success: function (jugadores) { + mostrarEquipos( + partida, + equipos, + jugadores + ); + }, + + error: function (xhr, status, error) { + console.error( + "Error al obtener jugadores:", + error + ); + }, + }); + }, + + error: function (xhr, status, error) { + console.error( + "Error al obtener equipos:", + error + ); + }, + }); +} + +// ===================================================== +// MOSTRAR SALA COMPLETA +// ===================================================== + +function mostrarSala(partida, equipos, jugadores) { + const contenedor = $("#contenedorSalas"); + + 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} +
+ +
+ `; + }); + + const esHost = + partida.idUsuario == idUsuarioSesion; + + let botonIniciarHTML = ""; + + if (esHost) { + botonIniciarHTML = ` + + + + ¡Iniciar Partida! + + + `; + } + + const salaHTML = ` +
+ +
+ +
+ ${escapeHTML(partida.nombrePartida)} +
+ +
+ +
+ ${equiposHTML} +
+ +
+ + + + ${ + 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 + ); + }); + + 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); +} From 5113b960d2a0ce0aff590eb61d5a35520388b2cd Mon Sep 17 00:00:00 2001 From: alexis Date: Thu, 1 Oct 2026 13:52:36 +0200 Subject: [PATCH 3/4] 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); } From c0207197fba7189f9fac517ace2f75a3b96a4c4d Mon Sep 17 00:00:00 2001 From: alexis Date: Thu, 1 Oct 2026 14:05:02 +0200 Subject: [PATCH 4/4] =?UTF-8?q?Add=20se=20actualizan=20las=20salas=20sin?= =?UTF-8?q?=20pesta=C3=B1eo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/buscadorSala.js | 521 +++++++++++++------------------------- js/sala.js | 616 ++++++++++++++++++++++----------------------- 2 files changed, 474 insertions(+), 663 deletions(-) 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