Add actualizacion de jugadores dentro de sala cada 5 segundos #29

Merged
jorge merged 4 commits from lobby into main 2026-10-01 14:09:14 +02:00
2 changed files with 474 additions and 663 deletions
Showing only changes of commit c0207197fb - Show all commits
+44 -213
View File
@@ -1,41 +1,21 @@
// =====================================================
// VARIABLES
// =====================================================
let intervaloBuscadorSalas = null; let intervaloBuscadorSalas = null;
let cargandoSalas = false; let cargandoSalas = false;
// =====================================================
// INICIAR ACTUALIZACIÓN AUTOMÁTICA
// =====================================================
function iniciarActualizacionSalas() { function iniciarActualizacionSalas() {
// Evitar crear varios intervalos
if (intervaloBuscadorSalas) { if (intervaloBuscadorSalas) {
clearInterval(intervaloBuscadorSalas); clearInterval(intervaloBuscadorSalas);
} }
// Primera carga
cargarSalas(); cargarSalas();
// Actualizar cada 5 segundos
intervaloBuscadorSalas = setInterval(function () { intervaloBuscadorSalas = setInterval(function () {
// Si el usuario está dentro de una sala,
// no necesitamos actualizar el buscador.
if (!usuarioYaEstaEnEquipo) { if (!usuarioYaEstaEnEquipo) {
cargarSalas(); cargarSalas();
} }
}, 5000); }, 5000);
} }
// =====================================================
// CARGAR LISTA DE SALAS
// =====================================================
function cargarSalas() { function cargarSalas() {
// Evitar peticiones simultáneas
if (cargandoSalas) { if (cargandoSalas) {
return; return;
} }
@@ -46,7 +26,6 @@ function cargarSalas() {
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
data: { data: {
orden: "listar", orden: "listar",
}, },
@@ -54,15 +33,7 @@ function cargarSalas() {
success: function (partidas) { success: function (partidas) {
const contenedor = $("#contenedorSalas"); const contenedor = $("#contenedorSalas");
// ================================================= if (!Array.isArray(partidas) || partidas.length === 0) {
// NO HAY SALAS
// =================================================
if (
!Array.isArray(partidas) ||
partidas.length === 0
) {
// Ocultamos/eliminamos únicamente las salas
$(".sala-item").remove(); $(".sala-item").remove();
if ($("#mensajeSinSalas").length === 0) { if ($("#mensajeSinSalas").length === 0) {
@@ -82,43 +53,20 @@ function cargarSalas() {
return; return;
} }
// =================================================
// HAY SALAS
// =================================================
// Eliminar mensaje de "no hay salas"
$("#mensajeSinSalas").remove(); $("#mensajeSinSalas").remove();
// =================================================
// OBTENER IDS DE LAS SALAS ACTUALES
// =================================================
const idsPartidas = partidas.map(function (partida) { const idsPartidas = partidas.map(function (partida) {
return String(partida.idPartida); return String(partida.idPartida);
}); });
// =================================================
// ELIMINAR SALAS QUE YA NO EXISTEN
// =================================================
$(".sala-item").each(function () { $(".sala-item").each(function () {
const idPartida = String( const idPartida = String($(this).data("id-partida"));
$(this).data("id-partida")
);
if (!idsPartidas.includes(idPartida)) { if (!idsPartidas.includes(idPartida)) {
$(this).remove(); $(this).remove();
} }
}); });
// =================================================
// ACTUALIZAR / CREAR CADA SALA
// =================================================
partidas.forEach(function (partida) { partidas.forEach(function (partida) {
cargarSalaBuscador(partida); cargarSalaBuscador(partida);
}); });
@@ -137,17 +85,11 @@ function cargarSalas() {
}); });
} }
// =====================================================
// CARGAR INFORMACIÓN DE UNA SALA
// =====================================================
function cargarSalaBuscador(partida) { function cargarSalaBuscador(partida) {
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
data: { data: {
orden: "getEquipos", orden: "getEquipos",
idPartida: partida.idPartida, idPartida: partida.idPartida,
@@ -158,13 +100,25 @@ function cargarSalaBuscador(partida) {
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
type: "POST", type: "POST",
dataType: "json", dataType: "json",
data: { data: {
orden: "getJugadores", orden: "getJugadores",
idPartida: partida.idPartida, idPartida: partida.idPartida,
}, },
success: function (jugadores) { success: function (jugadores) {
if (
!Array.isArray(jugadores) ||
jugadores.length === 0
) {
$(
`.sala-item[data-id-partida="${partida.idPartida}"]`
).remove();
comprobarSiNoHaySalas();
return;
}
actualizarSalaBuscador( actualizarSalaBuscador(
partida, partida,
equipos, equipos,
@@ -190,26 +144,36 @@ function cargarSalaBuscador(partida) {
}); });
} }
function comprobarSiNoHaySalas() {
if ($(".sala-item").length === 0) {
if ($("#mensajeSinSalas").length === 0) {
$("#contenedorSalas").append(`
<div
id="mensajeSinSalas"
class="col-12 text-center">
// ===================================================== <p class="text-muted">
// ACTUALIZAR UNA SALA No hay salas disponibles actualmente.
// ===================================================== </p>
</div>
`);
}
}
}
function actualizarSalaBuscador( function actualizarSalaBuscador(
partida, partida,
equipos, equipos,
jugadores jugadores
) { ) {
$("#mensajeSinSalas").remove();
const selectorSala = const selectorSala =
`.sala-item[data-id-partida="${partida.idPartida}"]`; `.sala-item[data-id-partida="${partida.idPartida}"]`;
const salaExistente = $(selectorSala); const salaExistente = $(selectorSala);
// ===================================================
// SI LA SALA NO EXISTE → CREARLA
// ===================================================
if (salaExistente.length === 0) { if (salaExistente.length === 0) {
crearSalaBuscador( crearSalaBuscador(
partida, partida,
@@ -220,17 +184,6 @@ function actualizarSalaBuscador(
return; return;
} }
// ===================================================
// LA SALA YA EXISTE
// ===================================================
//
// NO TOCAMOS LA TARJETA COMPLETA.
//
// Solo actualizamos .equipos
//
const equiposHTML = const equiposHTML =
generarEquiposHTML( generarEquiposHTML(
partida, partida,
@@ -238,22 +191,18 @@ function actualizarSalaBuscador(
jugadores jugadores
); );
salaExistente salaExistente
.find(".equipos") .find(".equipos")
.html(equiposHTML); .html(equiposHTML);
} }
// =====================================================
// CREAR UNA SALA NUEVA
// =====================================================
function crearSalaBuscador( function crearSalaBuscador(
partida, partida,
equipos, equipos,
jugadores jugadores
) { ) {
$("#mensajeSinSalas").remove();
const equiposHTML = const equiposHTML =
generarEquiposHTML( generarEquiposHTML(
partida, partida,
@@ -261,7 +210,6 @@ function crearSalaBuscador(
jugadores jugadores
); );
const salaHTML = ` const salaHTML = `
<div <div
class="col-12 col-md-10 col-lg-8 sala-item" class="col-12 col-md-10 col-lg-8 sala-item"
@@ -269,28 +217,15 @@ function crearSalaBuscador(
<div class="sala card p-3 shadow-sm mb-4"> <div class="sala card p-3 shadow-sm mb-4">
<!-- =========================================
CABECERA
========================================== -->
<div <div
class="sala-header h4 text-center mb-3 text-white"> class="sala-header h4 text-center mb-3 text-white">
${escapeHTML( ${escapeHTML(partida.nombrePartida)}
partida.nombrePartida
)}
</div> </div>
<!-- =========================================
CUERPO
========================================== -->
<div class="sala-body"> <div class="sala-body">
<!-- ESTA ES LA PARTE QUE SE ACTUALIZA -->
<div class="equipos d-flex justify-content-around"> <div class="equipos d-flex justify-content-around">
${equiposHTML} ${equiposHTML}
@@ -304,17 +239,9 @@ function crearSalaBuscador(
</div> </div>
`; `;
$("#contenedorSalas").append(salaHTML);
$("#contenedorSalas").append(
salaHTML
);
} }
// =====================================================
// GENERAR HTML DE EQUIPOS Y JUGADORES
// =====================================================
function generarEquiposHTML( function generarEquiposHTML(
partida, partida,
equipos, equipos,
@@ -322,38 +249,23 @@ function generarEquiposHTML(
) { ) {
let equiposHTML = ""; let equiposHTML = "";
equipos.forEach(function (equipo) { equipos.forEach(function (equipo) {
// -----------------------------------------------
// JUGADORES DE ESTE EQUIPO
// -----------------------------------------------
const jugadoresEquipo = const jugadoresEquipo =
jugadores.filter( jugadores.filter(function (jugador) {
function (jugador) {
return ( return (
jugador.idEquipo == jugador.idEquipo ==
equipo.idEquipo equipo.idEquipo
); );
} });
);
let jugadoresHTML = ""; let jugadoresHTML = "";
// -----------------------------------------------
// MOSTRAR JUGADORES
// -----------------------------------------------
if (jugadoresEquipo.length > 0) { if (jugadoresEquipo.length > 0) {
jugadoresEquipo.forEach( jugadoresEquipo.forEach(function (jugador) {
function (jugador) {
const esHost = const esHost =
jugador.idUsuario == jugador.idUsuario ==
partida.idUsuario; partida.idUsuario;
jugadoresHTML += ` jugadoresHTML += `
<div <div
class="jugador border border-2 d-flex align-items-center justify-content-between"> class="jugador border border-2 d-flex align-items-center justify-content-between">
@@ -376,7 +288,6 @@ function generarEquiposHTML(
</div> </div>
${ ${
esHost esHost
? ` ? `
@@ -392,8 +303,7 @@ function generarEquiposHTML(
</div> </div>
`; `;
} });
);
} else { } else {
jugadoresHTML = ` jugadoresHTML = `
<div class="text-muted small"> <div class="text-muted small">
@@ -402,22 +312,14 @@ function generarEquiposHTML(
`; `;
} }
// -----------------------------------------------
// BOTÓN UNIRSE
// -----------------------------------------------
let botonUnirseHTML = ""; let botonUnirseHTML = "";
if (!usuarioYaEstaEnEquipo) { if (!usuarioYaEstaEnEquipo) {
botonUnirseHTML = ` botonUnirseHTML = `
<button <button
type="button" type="button"
class="btn-unirse w-100 btn-unirse-equipo mt-2" class="btn-unirse w-100 btn-unirse-equipo mt-2"
data-id-partida="${partida.idPartida}" data-id-partida="${partida.idPartida}"
data-id-equipo="${equipo.idEquipo}"> data-id-equipo="${equipo.idEquipo}">
Unirse Unirse
@@ -426,11 +328,6 @@ function generarEquiposHTML(
`; `;
} }
// -----------------------------------------------
// EQUIPO
// -----------------------------------------------
equiposHTML += ` equiposHTML += `
<div <div
class="equipo me-2 ms-2 p-3 border rounded"> class="equipo me-2 ms-2 p-3 border rounded">
@@ -453,18 +350,10 @@ function generarEquiposHTML(
`; `;
}); });
return equiposHTML; return equiposHTML;
} }
$("#btnCrearSala").on("click", function () {
// =====================================================
// CREAR SALA
// =====================================================
$("#btnCrearSala").on(
"click",
function () {
const nombreSala = const nombreSala =
$("#nombreSala").val().trim(); $("#nombreSala").val().trim();
@@ -474,24 +363,13 @@ $("#btnCrearSala").on(
const nombreEquipo2 = const nombreEquipo2 =
$("#nombreEquipo2").val().trim(); $("#nombreEquipo2").val().trim();
let valido = true; let valido = true;
// -----------------------------------------------
// LIMPIAR ERRORES
// -----------------------------------------------
$(".mensaje-error-sala").remove(); $(".mensaje-error-sala").remove();
$(".input-kahoot") $(".input-kahoot")
.removeClass("is-invalid"); .removeClass("is-invalid");
// -----------------------------------------------
// VALIDAR NOMBRE DE SALA
// -----------------------------------------------
if ( if (
nombreSala === "" || nombreSala === "" ||
nombreSala.length < 3 nombreSala.length < 3
@@ -504,11 +382,6 @@ $("#btnCrearSala").on(
valido = false; valido = false;
} }
// -----------------------------------------------
// VALIDAR EQUIPO 1
// -----------------------------------------------
if ( if (
nombreEquipo1 === "" || nombreEquipo1 === "" ||
nombreEquipo1.length < 2 nombreEquipo1.length < 2
@@ -521,11 +394,6 @@ $("#btnCrearSala").on(
valido = false; valido = false;
} }
// -----------------------------------------------
// VALIDAR EQUIPO 2
// -----------------------------------------------
if ( if (
nombreEquipo2 === "" || nombreEquipo2 === "" ||
nombreEquipo2.length < 2 nombreEquipo2.length < 2
@@ -538,11 +406,6 @@ $("#btnCrearSala").on(
valido = false; valido = false;
} }
// -----------------------------------------------
// COMPROBAR NOMBRES IGUALES
// -----------------------------------------------
if ( if (
nombreEquipo1 !== "" && nombreEquipo1 !== "" &&
nombreEquipo2 !== "" && nombreEquipo2 !== "" &&
@@ -557,31 +420,16 @@ $("#btnCrearSala").on(
valido = false; valido = false;
} }
// -----------------------------------------------
// SI HAY ERRORES
// -----------------------------------------------
if (!valido) { if (!valido) {
return; return;
} }
// -----------------------------------------------
// BOTÓN
// -----------------------------------------------
const boton = $("#btnCrearSala"); const boton = $("#btnCrearSala");
boton boton
.prop("disabled", true) .prop("disabled", true)
.text("Creando sala..."); .text("Creando sala...");
// -----------------------------------------------
// PETICIÓN
// -----------------------------------------------
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
type: "POST", type: "POST",
@@ -589,11 +437,8 @@ $("#btnCrearSala").on(
data: { data: {
orden: "crear", orden: "crear",
nombrePartida: nombreSala, nombrePartida: nombreSala,
nombreEquipo1: nombreEquipo1, nombreEquipo1: nombreEquipo1,
nombreEquipo2: nombreEquipo2, nombreEquipo2: nombreEquipo2,
}, },
@@ -608,11 +453,8 @@ $("#btnCrearSala").on(
return; return;
} }
if (respuesta.exito) { if (respuesta.exito) {
$("#modalCrearSala").modal( $("#modalCrearSala").modal("hide");
"hide"
);
location.reload(); location.reload();
} }
@@ -633,13 +475,7 @@ $("#btnCrearSala").on(
.text("Crear sala"); .text("Crear sala");
}, },
}); });
} });
);
// =====================================================
// MOSTRAR ERROR
// =====================================================
function mostrarError( function mostrarError(
selector, selector,
@@ -659,11 +495,6 @@ function mostrarError(
`); `);
} }
// =====================================================
// LIMPIAR ERRORES AL ESCRIBIR
// =====================================================
$(document).on( $(document).on(
"input", "input",
".input-kahoot", ".input-kahoot",
+45 -65
View File
@@ -6,10 +6,6 @@ $(document).ready(function () {
comprobarSalaUsuario(); comprobarSalaUsuario();
}); });
// =====================================================
// COMPROBAR SI EL USUARIO YA ESTÁ EN UNA SALA
// =====================================================
function comprobarSalaUsuario() { function comprobarSalaUsuario() {
$("#cargandoSalas").remove(); $("#cargandoSalas").remove();
@@ -38,26 +34,25 @@ function comprobarSalaUsuario() {
}, },
error: function (xhr, status, error) { error: function (xhr, status, error) {
console.error("Error al comprobar la sala del usuario:", error);
usuarioYaEstaEnEquipo = false; usuarioYaEstaEnEquipo = false;
if (intervaloSala) {
clearInterval(intervaloSala);
intervaloSala = null;
}
$("#contenedorSalas").empty();
$("#contenedorCrearSala").show(); $("#contenedorCrearSala").show();
cargarSalas(); iniciarActualizacionSalas();
}, },
}); });
} }
// =====================================================
// CARGAR SALA DEL USUARIO
// =====================================================
function cargarSalaUsuario(idPartida) { function cargarSalaUsuario(idPartida) {
// Primera carga completa
cargarSalaCompleta(idPartida); cargarSalaCompleta(idPartida);
// Evitar intervalos duplicados
if (intervaloSala) { if (intervaloSala) {
clearInterval(intervaloSala); clearInterval(intervaloSala);
} }
@@ -67,10 +62,6 @@ function cargarSalaUsuario(idPartida) {
}, 5000); }, 5000);
} }
// =====================================================
// CARGA COMPLETA DE LA SALA
// =====================================================
function cargarSalaCompleta(idPartida) { function cargarSalaCompleta(idPartida) {
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
@@ -97,10 +88,6 @@ function cargarSalaCompleta(idPartida) {
}); });
} }
// =====================================================
// OBTENER EQUIPOS Y JUGADORES
// =====================================================
function cargarInformacionSalaCompleta(partida) { function cargarInformacionSalaCompleta(partida) {
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
@@ -139,10 +126,6 @@ function cargarInformacionSalaCompleta(partida) {
}); });
} }
// =====================================================
// ACTUALIZAR SALA CADA 5 SEGUNDOS
// =====================================================
function actualizarSalaUsuario(idPartida) { function actualizarSalaUsuario(idPartida) {
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
@@ -169,10 +152,6 @@ function actualizarSalaUsuario(idPartida) {
}); });
} }
// =====================================================
// OBTENER INFORMACIÓN PARA ACTUALIZACIÓN
// =====================================================
function cargarInformacionSala(partida) { function cargarInformacionSala(partida) {
$.ajax({ $.ajax({
url: "controladores/controladorPartida.php", url: "controladores/controladorPartida.php",
@@ -211,10 +190,6 @@ function cargarInformacionSala(partida) {
}); });
} }
// =====================================================
// MOSTRAR SALA COMPLETA
// =====================================================
function mostrarSala(partida, equipos, jugadores) { function mostrarSala(partida, equipos, jugadores) {
const contenedor = $("#contenedorSalas"); const contenedor = $("#contenedorSalas");
@@ -337,16 +312,9 @@ function mostrarSala(partida, equipos, jugadores) {
</div> </div>
`; `;
// IMPORTANTE:
// El usuario está dentro de una única sala.
// Por eso aquí SÍ queremos reemplazar.
contenedor.html(salaHTML); contenedor.html(salaHTML);
} }
// =====================================================
// UNIRSE A UN EQUIPO
// =====================================================
$(document).on("click", ".btn-unirse-equipo", function () { $(document).on("click", ".btn-unirse-equipo", function () {
const boton = $(this); const boton = $(this);
@@ -392,15 +360,12 @@ $(document).on("click", ".btn-unirse-equipo", function () {
}); });
}); });
// =====================================================
// ABANDONAR SALA - ABRIR MODAL
// =====================================================
$(document).on("click", ".btn-abandonar-sala", function () { $(document).on("click", ".btn-abandonar-sala", function () {
botonAbandonarReferencia = $(this); botonAbandonarReferencia = $(this);
const esHost = const esHost =
$(this).data("es-host") === true || $(this).data("es-host") === "true"; $(this).data("es-host") === true ||
$(this).data("es-host") === "true";
const titulo = $("#modalAbandonarSalaLabel"); const titulo = $("#modalAbandonarSalaLabel");
@@ -419,7 +384,9 @@ $(document).on("click", ".btn-abandonar-sala", function () {
} else { } else {
titulo.text("¿Abandonar la sala?"); 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"); botonConfirmar.text("Sí, salir");
} }
@@ -431,18 +398,18 @@ $(document).on("click", ".btn-abandonar-sala", function () {
modal.show(); modal.show();
}); });
// =====================================================
// CONFIRMAR ABANDONAR SALA
// =====================================================
$(document).on("click", "#btnConfirmarAbandonar", function () { $(document).on("click", "#btnConfirmarAbandonar", function () {
const modalEl = document.getElementById("modalAbandonarSala"); const modalEl =
document.getElementById("modalAbandonarSala");
const modalInstance = bootstrap.Modal.getInstance(modalEl); const modalInstance =
bootstrap.Modal.getInstance(modalEl);
const btnConfirmar = $(this); const btnConfirmar = $(this);
btnConfirmar.prop("disabled", true).text("Saliendo..."); btnConfirmar
.prop("disabled", true)
.text("Saliendo...");
$.ajax({ $.ajax({
url: "controladores/controladorEquipoxUsuario.php", url: "controladores/controladorEquipoxUsuario.php",
@@ -454,7 +421,9 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
}, },
success: function (respuesta) { success: function (respuesta) {
btnConfirmar.prop("disabled", false).text("Sí, salir"); btnConfirmar
.prop("disabled", false)
.text("Sí, salir");
if (modalInstance) { if (modalInstance) {
modalInstance.hide(); modalInstance.hide();
@@ -472,17 +441,24 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
intervaloSala = null; intervaloSala = null;
} }
$("#contenedorSalas").empty();
$("#contenedorCrearSala").show(); $("#contenedorCrearSala").show();
cargarSalas(); iniciarActualizacionSalas();
}, },
error: function (xhr, status, error) { error: function (xhr, status, error) {
console.error("Error al salir de la sala:", 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) { if (modalInstance) {
modalInstance.hide(); modalInstance.hide();
@@ -491,21 +467,22 @@ $(document).on("click", "#btnConfirmarAbandonar", function () {
}); });
}); });
// =====================================================
// AUXILIARES
// =====================================================
function escapeHTML(texto) { function escapeHTML(texto) {
return $("<div>") return $("<div>")
.text(texto ?? "") .text(texto ?? "")
.html(); .html();
} }
function mostrarEquipos(partida, equipos, jugadores) { function mostrarEquipos(
partida,
equipos,
jugadores
) {
let equiposHTML = ""; let equiposHTML = "";
equipos.forEach(function (equipo) { equipos.forEach(function (equipo) {
const jugadoresEquipo = jugadores.filter(function (jugador) { const jugadoresEquipo =
jugadores.filter(function (jugador) {
return jugador.idEquipo == equipo.idEquipo; return jugador.idEquipo == equipo.idEquipo;
}); });
@@ -513,7 +490,8 @@ function mostrarEquipos(partida, equipos, jugadores) {
if (jugadoresEquipo.length > 0) { if (jugadoresEquipo.length > 0) {
jugadoresEquipo.forEach(function (jugador) { jugadoresEquipo.forEach(function (jugador) {
const esHost = jugador.idUsuario == partida.idUsuario; const esHost =
jugador.idUsuario == partida.idUsuario;
jugadoresHTML += ` jugadoresHTML += `
<div class="jugador border border-2 d-flex align-items-center justify-content-between ${ <div class="jugador border border-2 d-flex align-items-center justify-content-between ${
@@ -529,7 +507,9 @@ function mostrarEquipos(partida, equipos, jugadores) {
} }
</span> </span>
${escapeHTML(jugador.nombreUsuario)} ${escapeHTML(
jugador.nombreUsuario
)}
</div> </div>
${ ${