This commit is contained in:
2026-10-01 10:53:03 +02:00
4 changed files with 249 additions and 84 deletions
+65 -10
View File
@@ -3,6 +3,43 @@ let usuarioYaEstaEnEquipo = false;
$(document).ready(function () {
comprobarSalaUsuario();
});
// ==========================================================================
// DETECTOR DE INICIO DE PARTIDA PARA JUGADORES INVITADOS (1 VS 1)
// ==========================================================================
$(document).ready(function () {
// Solo activamos el vigilante si estamos en la página del buscador de salas
if (window.location.pathname.includes("buscadorSala.php")) {
setInterval(function () {
// 1. Preguntamos al servidor en qué partida está metido el usuario actual
$.ajax({
url: "controladores/controladorEquipoxUsuario.php",
type: "POST",
dataType: "json",
data: { orden: "obtenerSalaUsuario" },
success: function (sala) {
// Si el usuario está metido en una sala/partida activa...
if (sala.asociado && sala.idPartida) {
// 2. Comprobamos si el anfitrión ya ha iniciado esa partida concreta
$.ajax({
url: "controladores/controladorPartida.php",
type: "POST",
dataType: "json",
data: { orden: "buscar", idPartida: sala.idPartida },
success: function (partida) {
// Si 'fechaInicio' ya no es null, significa que el host le dio a "Jugar"
if (partida && partida.fechaInicio !== null) {
// Redirigimos instantáneamente al invitado a la pantalla del juego
window.location.href =
"juego.php?idPartida=" + sala.idPartida;
}
},
});
}
},
});
}, 2000); // Comprueba el estado de la partida automáticamente cada 2 segundos
}
});
// 1. Comprobar si el usuario actual ya pertenece a una sala
function comprobarSalaUsuario() {
@@ -179,12 +216,12 @@ function mostrarSala(partida, equipos, jugadores) {
// Solo el host puede iniciar la partida
if (esHost) {
// Así debe renderizarse el botón del host dentro de tu función mostrarSala() para que el AJAX funcione:
botonIniciarHTML = `
<a href="juego.php?idPartida=${partida.idPartida}"
class="btn btn-success btn-lg px-4">
<i class="bi bi-controller"></i> ¡Iniciar Partida!
</a>
`;
<button type="button" id="btnInicioJuego" data-id-partida="${partida.idPartida}" class="btn btn-success btn-lg px-4">
<i class="bi bi-controller"></i> ¡Iniciar Partida!
</button>
`;
}
accionesSalaHTML = `
@@ -266,7 +303,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 +317,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 +328,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");
@@ -403,6 +438,7 @@ $("#btnCrearSala").on("click", function () {
if (respuesta.exito) {
$("#modalCrearSala").modal("hide");
location.reload();
}
},
@@ -433,3 +469,22 @@ $(document).on("input", ".input-kahoot", function () {
$(this).removeClass("is-invalid");
$(this).next(".mensaje-error-sala").remove();
});
$(document).on("click", "#btnInicioJuego", function () {
// 1. Capturamos el id de la partida de forma dinámica desde el botón que se ha pulsado
const idPartida = $(this).data("id-partida");
// 2. Enviamos la petición AJAX adecuada con TODOS los datos que el controlador espera recibir
$.ajax({
url: "controladores/controladorPartida.php",
type: "POST",
dataType: "json",
data: {
orden: "iniciar",
idPartida: idPartida,
},
error: function (error) {
console.error("Error al iniciar el juego por AJAX:", error);
},
});
});
+72 -30
View File
@@ -1,38 +1,80 @@
$(document).ready(function () {
const idPartida = $("body").data("id-partida");
comprobarEstadoPartida(idPartida);
// Captura segura del ID de la partida desde el body de la página
const idPartida =
$("body").attr("data-id-partida") || $("body").data("id-partida");
const intervalo = setInterval(function () {
comprobarEstadoPartida(idPartida, intervalo);
}, 3000);
comprobarEstadoPartida(idPartida);
const intervalo = setInterval(function () {
comprobarEstadoPartida(idPartida, intervalo);
}, 3000);
});
function comprobarEstadoPartida(idPartida, intervalo = null) {
$.ajax({
url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "comprobarEstado",
idPartida: idPartida
},
success: function (respuesta) {
if (respuesta.error) {
console.error("Error:", respuesta.error);
return;
}
if (!idPartida || idPartida <= 0) return;
if (respuesta.terminada) {
if (intervalo !== null) clearInterval(intervalo);
$("#pantalla-espera").fadeOut(400, function() {
location.reload();
});
}
},
error: function () {
console.log("Error de comunicación con el controlador.");
$.ajax({
url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "comprobarEstado",
idPartida: idPartida,
},
success: function (respuesta) {
if (respuesta.error) {
console.error("Error del controlador:", respuesta.error);
return;
}
if (respuesta.terminada === true || respuesta.terminada === "true") {
if (intervalo !== null) {
clearInterval(intervalo);
}
});
$("#pantalla-espera").hide();
$("#pantalla-resultados").show();
}
},
error: function () {
console.log("Esperando conexión con el servidor del Trivial...");
},
});
}
// INTERCEPTOR DE SALIDA: Saca al usuario y destruye la sala en cascada
$(document).on("click", "#btnVolverInicio", function (e) {
e.preventDefault(); // Congelamos un instante la redirección
const urlDestino = $(this).attr("href");
// Leemos el ID de forma científica directamente desde el botón pulsado
const idPartida = $(this).attr("data-id");
if (!idPartida) {
window.location.href = urlDestino;
return;
}
$.ajax({
url: "controladores/controladorResultados.php",
type: "POST",
dataType: "json",
data: {
orden: "registrarSalidaUsuario",
idPartida: idPartida,
},
success: function (response) {
console.log(
"Servidor procesó la salida. Usuarios restantes: " +
response.usuarios_quedan,
);
},
error: function (error) {
console.error("Error técnico al salir de la sala:", error);
},
complete: function () {
// Rompemos la pausa y mandamos al jugador al menú de inicio limpio
window.location.href = urlDestino;
},
});
});