10 Commits

5 changed files with 306 additions and 1095 deletions
+82 -38
View File
@@ -1,79 +1,118 @@
<?php
session_start();
require_once '../clases/claseJuego.php';
header('Content-Type: application/json; charset=utf-8');
// Hay que estar logueado y decir de qué partida se trata
// Comprobamos que haya un usuario conectado
if (!isset($_SESSION['idUsuario'])) {
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
echo json_encode([
'error' => 'Debes iniciar sesión para jugar.'
]);
exit;
}
$idUsuario = (int)$_SESSION['idUsuario'];
$idPartida = intval($_POST['idPartida'] ?? 0);
$idUsuario = (int) $_SESSION['idUsuario'];
// Comprobamos que se haya indicado la partida
if (!isset($_POST['idPartida'])) {
echo json_encode([
'error' => 'No se ha indicado la partida.'
]);
exit;
}
$idPartida = intval($_POST['idPartida']);
if ($idPartida <= 0) {
echo json_encode(['error' => 'No se ha indicado la partida.']);
echo json_encode([
'error' => 'La partida indicada no es válida.'
]);
exit;
}
// Solo pueden jugar los usuarios que están en uno de los equipos de la partida
$perteneceAPartida = Juego::usuarioEnPartida($idPartida, $idUsuario);
// Comprobamos que el usuario pertenezca a la partida
$perteneceAPartida = Juego::usuarioEnPartida($idPartida,$idUsuario);
if (is_array($perteneceAPartida)) {
echo json_encode($perteneceAPartida);
exit;
}
if (!$perteneceAPartida) {
echo json_encode(['error' => 'No formas parte de esta partida.']);
echo json_encode([
'error' => 'No formas parte de esta partida.'
]);
exit;
}
// Comprobamos la orden
switch ($_POST['orden'] ?? '') {
$orden = $_POST['orden'] ?? '';
switch ($orden) {
// CARGAR LAS PREGUNTAS DE LA PARTIDA
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
case 'cargarPreguntas':
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
$resultado = Juego::cargarPreguntas($idPartida, $idUsuario);
echo json_encode($resultado);
break;
break;
// REGISTRAR RESPUESTA
// Guarda la respuesta del usuario y dice si ha acertado
case 'responder':
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta'] ?? 0);
$idRespuesta = intval($_POST['idRespuesta'] ?? 0);
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0) {
echo json_encode(['error' => 'Faltan datos para registrar la respuesta.']);
break;
}
echo json_encode(
Juego::registrarRespuesta(
$idPartida,
$idUsuario,
$idPartidaxPregunta,
$idRespuesta
)
);
if (!isset($_POST['idPartidaxPregunta']) || !isset($_POST['idRespuesta'])){
echo json_encode([
'error' => 'Faltan datos para registrar la respuesta.'
]);
break;
}
$idPartidaxPregunta = intval($_POST['idPartidaxPregunta']);
$idRespuesta = intval($_POST['idRespuesta']);
if ($idPartidaxPregunta <= 0 || $idRespuesta <= 0){
echo json_encode([
'error' => 'Los datos de la respuesta no son válidos.'
]);
break;
}
// Registramos la respuesta del usuario
$resultado = Juego::registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta);
echo json_encode($resultado);
break;
// Finalizar la partida y registrar los aciertos del usuario
// Recibe los aciertos del jugador al terminar sus 10 preguntas,
// para que resultados.php los pueda usar al montar la hoja de resultados
case 'finalizarPartida':
$aciertos = intval($_POST['aciertos'] ?? 0);
// Guardamos los aciertos en la sesión
if (!isset($_SESSION['aciertosPorPartida'])) {
$_SESSION['aciertosPorPartida'] = [];
}
@@ -81,16 +120,21 @@ switch ($_POST['orden'] ?? '') {
echo json_encode([
'exito' => 'Aciertos registrados correctamente.',
'idPartida' => $idPartida,
'aciertos' => $aciertos
]);
break;
break;
default:
echo json_encode(['error' => 'La orden indicada no existe.']);
echo json_encode([
'error' => 'La orden indicada no existe.'
]);
break;
}
break;
}
?>
+26 -3
View File
@@ -18,9 +18,22 @@ let preguntas = [];
let indice = 0; // pregunta que se está mostrando
let bloqueado = false; // true mientras se envía una respuesta o se ve el feedback
let numeroAciertos = 0; // número de aciertos del jugador
let tiempoRespuesta = 0;
let intervaloTiempo;
$(document).ready(function () {
idPartida = parseInt($("body").data("id-partida"), 10);
// Obtenemos el idPartida de la URL
// Ejemplo: juego.php?idPartida=3
const parametros = new URLSearchParams(window.location.search);
idPartida = parseInt(parametros.get("idPartida"), 10);
if (!idPartida || idPartida < 1) {
mostrarError("La partida indicada no es válida.");
return;
}
// Un solo listener para todos los botones de respuesta
$("#respuestas").on("click", ".btn-answer", function () {
@@ -70,6 +83,11 @@ function cargarPreguntas() {
// 2. Pintar la pregunta actual y sus respuestas
function mostrarPregunta() {
console.log("entro en mostrarPregunta");
tiempoRespuesta = 0;
intervaloTiempo = setInterval(function () {
tiempoRespuesta++;
}, 100);
const pregunta = preguntas[indice];
bloqueado = false;
@@ -100,9 +118,13 @@ function mostrarPregunta() {
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
function responder($botonPulsado) {
console.log("entro en responder");
clearInterval(intervaloTiempo);
console.log("Tiempo de respuesta: " + tiempoRespuesta /10 + " segundos");
if (bloqueado) {
return;
}
bloqueado = true;
const pregunta = preguntas[indice];
@@ -118,7 +140,8 @@ function responder($botonPulsado) {
orden: "responder",
idPartida: idPartida,
idPartidaxPregunta: pregunta.idPartidaxPregunta,
idRespuesta: idRespuesta,
idRespuesta: idRespuesta,
tiempoRespuesta: tiempoRespuesta,
},
success: function (datos) {
if (datos.error) {
@@ -216,4 +239,4 @@ function mostrarError(mensaje) {
$("#feedback").html(
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
);
}
}
+27 -23
View File
@@ -1,22 +1,6 @@
<?php
session_start();
// Hay que estar logueado para jugar
if (!isset($_SESSION['idUsuario'])) {
header('Location: index.php');
exit;
}
// La partida llega por la URL: juego.php?idPartida=3
$idPartida = filter_input(INPUT_GET, 'idPartida', FILTER_VALIDATE_INT);
if (!$idPartida || $idPartida < 1) {
header('Location: buscadorSala.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
@@ -24,28 +8,48 @@ if (!$idPartida || $idPartida < 1) {
<title>Proyecto Trivial</title>
<link rel="stylesheet" href="css/juego.css">
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
</head>
<body data-id-partida="<?= (int)$idPartida ?>">
<!-- Progreso: "Pregunta 3 de 10" + barra -->
<body>
<!-- CABECERA Y PROGRESO -->
<div class="game-header">
<span id="contadorPregunta">Cargando…</span>
<span id="contadorPregunta">
Cargando…
</span>
</div>
<div class="progress-track">
<div class="progress-fill" id="barraProgreso"></div>
</div>
<!-- Contenedor de la Pregunta (lo rellena js/juego.js) -->
<!-- PREGUNTA -->
<div class="question-container">
<div id="textoPregunta">Cargando preguntas…</div>
<div id="textoPregunta">
Cargando preguntas…
</div>
<div id="feedback" class="feedback" aria-live="polite"></div>
</div>
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
<!-- RESPUESTAS -->
<div class="answers-grid" id="respuestas"></div>
<!-- JAVASCRIPT -->
<script src="js/jquery-4.0.0.min.js"></script>
<script src="js/juego.js"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
+155 -155
View File
@@ -1,156 +1,156 @@
<?php
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/conexionBD.php';
$idPartida = intval($_GET['idPartida'] ?? 0);
if ($idPartida <= 0) {
die("Partida no válida.");
}
$conexion = conexionBD();
if (is_array($conexion)) {
die("Error de conexión a la base de datos.");
}
// Obtener listado de jugadores y sus equipos en esta partida
$stmt = $conexion->prepare("
SELECT u.idUsuario, u.nombreUsuario, e.idEquipo, e.nombreEquipo
FROM equipoxpartida exp
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
INNER JOIN equipo e ON exu.idEquipo = e.idEquipo
WHERE exp.idPartida = :idPartida
");
$stmt->execute([':idPartida' => $idPartida]);
$listaJugadoresRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
$primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
$jugadoresFinales = [];
$equiposFinales = [];
// Respuestas de velocidad (+2 o +1)
foreach ($listaJugadoresRaw as $jugador) {
$idU = (int)$jugador['idUsuario'];
$idE = (int)$jugador['idEquipo'];
$stmtRespuestas = $conexion->prepare("
SELECT ra.idPartidaxPregunta, r.correcta
FROM respuestaalmacenada ra
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario
");
$stmtRespuestas->execute([':idPartida' => $idPartida, ':idUsuario' => $idU]);
$respuestasUsuario = $stmtRespuestas->fetchAll(PDO::FETCH_ASSOC);
$aciertos = 0;
$puntosTotalesJugador = 0;
foreach ($respuestasUsuario as $resp) {
if ((int)$resp['correcta'] === 1) {
$aciertos++;
$idPxp = $resp['idPartidaxPregunta'];
// Si el ID de usuario coincide con el primero guardado de esa pregunta se lleva 2 puntos
if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) {
$puntosTotalesJugador += 2;
} else {
$puntosTotalesJugador += 1;
}
}
}
$jugadoresFinales[] = [
'nombre' => $jugador['nombreUsuario'],
'equipo' => $jugador['nombreEquipo'],
'aciertos' => $aciertos,
'puntos' => $puntosTotalesJugador
];
if (!isset($equiposFinales[$idE])) {
$equiposFinales[$idE] = [
'nombre' => $jugador['nombreEquipo'],
'puntos' => 0
];
}
$equiposFinales[$idE]['puntos'] += $puntosTotalesJugador;
}
// Ordenar según la puntuación final de mayor a menor
usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resultados - Trivial</title>
<link rel="stylesheet" href="css/resultados.css">
<script src="https://jquery.com"></script>
</head>
<body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor">
<h2>⌛ Esperando a que todos los jugadores terminen...</h2>
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
<div class="loader"></div>
</div>
<div id="pantalla-resultados" class="contenedor" style="display:none;">
<h1>🏆 Resultados de la Partida 🏆</h1>
<h2>Clasificación por Equipos</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Equipo</th>
<th>Puntos Totales</th>
</tr>
</thead>
<tbody>
<?php foreach ($equiposFinales as $index => $eq): ?>
<tr class="<?php echo $index === 0 ? 'top-team' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($eq['nombre']); ?></td>
<td><strong><?php echo $eq['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2>Rendimiento Individual</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Jugador</th>
<th>Equipo</th>
<th>Aciertos</th>
<th>Puntos Logrados</th>
</tr>
</thead>
<tbody>
<?php foreach ($jugadoresFinales as $index => $jug): ?>
<tr class="<?php echo $index === 0 ? 'top-player' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($jug['nombre']); ?></td>
<td><?php echo htmlspecialchars($jug['equipo']); ?></td>
<td><?php echo $jug['aciertos']; ?> / 10</td>
<td><strong><?php echo $jug['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="contenedor-boton">
<a href="/triviagmatico/buscadorSala.php" class="btn-inicio">Volver al Inicio 🏠</a>
</div>
</div>
<script src="js/resultados.js"></script>
</body>
<?php
session_start();
require_once 'includes/conexionBD.php';
$idPartida = intval($_GET['idPartida'] ?? 0);
if ($idPartida <= 0) {
die("Partida no válida.");
}
$conexion = conexionBD();
if (is_array($conexion)) {
die("Error de conexión a la base de datos.");
}
// Obtener listado de jugadores y sus equipos en esta partida
$stmt = $conexion->prepare("
SELECT u.idUsuario, u.nombreUsuario, e.idEquipo, e.nombreEquipo
FROM equipoxpartida exp
INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo
INNER JOIN usuario u ON exu.idUsuario = u.idUsuario
INNER JOIN equipo e ON exu.idEquipo = e.idEquipo
WHERE exp.idPartida = :idPartida
");
$stmt->execute([':idPartida' => $idPartida]);
$listaJugadoresRaw = $stmt->fetchAll(PDO::FETCH_ASSOC);
$primerosEnAcertar = $_SESSION['primeros_en_acertar'][$idPartida] ?? [];
$jugadoresFinales = [];
$equiposFinales = [];
// Respuestas de velocidad (+2 o +1)
foreach ($listaJugadoresRaw as $jugador) {
$idU = (int)$jugador['idUsuario'];
$idE = (int)$jugador['idEquipo'];
$stmtRespuestas = $conexion->prepare("
SELECT ra.idPartidaxPregunta, r.correcta
FROM respuestaalmacenada ra
INNER JOIN respuesta r ON ra.idRespuesta = r.idRespuesta
INNER JOIN partidaxpregunta pxp ON ra.idPartidaxPregunta = pxp.idPartidaxPregunta
WHERE pxp.idPartida = :idPartida AND ra.idUsuario = :idUsuario
");
$stmtRespuestas->execute([':idPartida' => $idPartida, ':idUsuario' => $idU]);
$respuestasUsuario = $stmtRespuestas->fetchAll(PDO::FETCH_ASSOC);
$aciertos = 0;
$puntosTotalesJugador = 0;
foreach ($respuestasUsuario as $resp) {
if ((int)$resp['correcta'] === 1) {
$aciertos++;
$idPxp = $resp['idPartidaxPregunta'];
// Si el ID de usuario coincide con el primero guardado de esa pregunta se lleva 2 puntos
if (isset($primerosEnAcertar[$idPxp]) && $primerosEnAcertar[$idPxp] === $idU) {
$puntosTotalesJugador += 2;
} else {
$puntosTotalesJugador += 1;
}
}
}
$jugadoresFinales[] = [
'nombre' => $jugador['nombreUsuario'],
'equipo' => $jugador['nombreEquipo'],
'aciertos' => $aciertos,
'puntos' => $puntosTotalesJugador
];
if (!isset($equiposFinales[$idE])) {
$equiposFinales[$idE] = [
'nombre' => $jugador['nombreEquipo'],
'puntos' => 0
];
}
$equiposFinales[$idE]['puntos'] += $puntosTotalesJugador;
}
// Ordenar según la puntuación final de mayor a menor
usort($jugadoresFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
usort($equiposFinales, function($a, $b) { return $b['puntos'] <=> $a['puntos']; });
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resultados - Trivial</title>
<link rel="stylesheet" href="css/resultados.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js"></script>
</head>
<body data-id-partida="<?php echo $idPartida; ?>">
<div id="pantalla-espera" class="contenedor">
<h2>⌛ Esperando a que todos los jugadores terminen...</h2>
<p>Calculando estadísticas de velocidad y actualizando perfiles históricos en el servidor.</p>
<div class="loader"></div>
</div>
<div id="pantalla-resultados" class="contenedor" style="display:none;">
<h1>🏆 Resultados de la Partida 🏆</h1>
<h2>Clasificación por Equipos</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Equipo</th>
<th>Puntos Totales</th>
</tr>
</thead>
<tbody>
<?php foreach ($equiposFinales as $index => $eq): ?>
<tr class="<?php echo $index === 0 ? 'top-team' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($eq['nombre']); ?></td>
<td><strong><?php echo $eq['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<h2>Rendimiento Individual</h2>
<table class="tabla-ranking">
<thead>
<tr>
<th>Posición</th>
<th>Jugador</th>
<th>Equipo</th>
<th>Aciertos</th>
<th>Puntos Logrados</th>
</tr>
</thead>
<tbody>
<?php foreach ($jugadoresFinales as $index => $jug): ?>
<tr class="<?php echo $index === 0 ? 'top-player' : ''; ?>">
<td>#<?php echo $index + 1; ?></td>
<td><?php echo htmlspecialchars($jug['nombre']); ?></td>
<td><?php echo htmlspecialchars($jug['equipo']); ?></td>
<td><?php echo $jug['aciertos']; ?> / 10</td>
<td><strong><?php echo $jug['puntos']; ?> pts</strong></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="contenedor-boton">
<a href="/triviagmatico/buscadorSala.php" class="btn-inicio">Volver al Inicio 🏠</a>
</div>
</div>
<script src="js/resultados.js"></script>
</body>
</html>