Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5420c83b30 | |||
| d28fbc7160 |
@@ -1,348 +0,0 @@
|
|||||||
<?php
|
|
||||||
require_once __DIR__ . '/../includes/conexionBD.php';
|
|
||||||
require_once __DIR__ . '/ClaseRespuestaAlmacenada.php';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Lógica de la dinámica de juego (la usa juego.php a través de ControladorJuego.php):
|
|
||||||
* - deja preparadas las 10 preguntas de la partida
|
|
||||||
* - se las devuelve al jugador con sus respuestas SIN decir cuál es la correcta
|
|
||||||
* - guarda la respuesta de cada jugador y le dice si ha acertado
|
|
||||||
*
|
|
||||||
* Todos los métodos devuelven un array con la clave 'error' si algo falla,
|
|
||||||
* igual que el resto de clases del proyecto.
|
|
||||||
*/
|
|
||||||
class Juego
|
|
||||||
{
|
|
||||||
const NUM_PREGUNTAS = 10;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Comprueba que el usuario pertenece a alguno de los equipos de la partida.
|
|
||||||
* Devuelve true/false (o el array de error si falla la BD).
|
|
||||||
*/
|
|
||||||
public static function usuarioEnPartida($idPartida, $idUsuario)
|
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
|
||||||
if (is_array($conexion)) {
|
|
||||||
return $conexion;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT COUNT(*) AS total
|
|
||||||
FROM equipoxpartida exp
|
|
||||||
INNER JOIN equipoxusuario exu
|
|
||||||
ON exu.idEquipo = exp.idEquipo
|
|
||||||
WHERE exp.idPartida = :idPartida
|
|
||||||
AND exu.idUsuario = :idUsuario
|
|
||||||
");
|
|
||||||
$consulta->execute([
|
|
||||||
':idPartida' => $idPartida,
|
|
||||||
':idUsuario' => $idUsuario
|
|
||||||
]);
|
|
||||||
return (int)$consulta->fetchColumn() > 0;
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
return [
|
|
||||||
'error' => 'Ocurrió un error al comprobar si perteneces a la partida.',
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Si la partida todavía no tiene preguntas, le asigna 10 al azar.
|
|
||||||
* Se hace dentro de una transacción con la fila de la partida bloqueada
|
|
||||||
* para que, si varios jugadores entran a la vez, las preguntas se
|
|
||||||
* asignen una sola vez.
|
|
||||||
* Devuelve null si todo va bien, o un array de error.
|
|
||||||
*/
|
|
||||||
private static function asegurarPreguntas($conexion, $idPartida)
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$conexion->beginTransaction();
|
|
||||||
|
|
||||||
$bloqueo = $conexion->prepare("
|
|
||||||
SELECT idPartida FROM partida
|
|
||||||
WHERE idPartida = :idPartida
|
|
||||||
FOR UPDATE
|
|
||||||
");
|
|
||||||
$bloqueo->execute([':idPartida' => $idPartida]);
|
|
||||||
|
|
||||||
if (!$bloqueo->fetch()) {
|
|
||||||
$conexion->rollBack();
|
|
||||||
return ['error' => 'La partida no existe.'];
|
|
||||||
}
|
|
||||||
|
|
||||||
$cuenta = $conexion->prepare("
|
|
||||||
SELECT COUNT(*) FROM partidaxpregunta
|
|
||||||
WHERE idPartida = :idPartida
|
|
||||||
");
|
|
||||||
$cuenta->execute([':idPartida' => $idPartida]);
|
|
||||||
|
|
||||||
if ((int)$cuenta->fetchColumn() === 0) {
|
|
||||||
|
|
||||||
// Solo preguntas que tengan alguna respuesta marcada como correcta
|
|
||||||
$elegidas = $conexion->query("
|
|
||||||
SELECT p.idPregunta
|
|
||||||
FROM pregunta p
|
|
||||||
WHERE EXISTS (
|
|
||||||
SELECT 1 FROM respuesta r
|
|
||||||
WHERE r.idPregunta = p.idPregunta
|
|
||||||
AND r.correcta = 1
|
|
||||||
)
|
|
||||||
ORDER BY RAND()
|
|
||||||
LIMIT " . self::NUM_PREGUNTAS
|
|
||||||
)->fetchAll(PDO::FETCH_COLUMN);
|
|
||||||
|
|
||||||
$insertar = $conexion->prepare("
|
|
||||||
INSERT INTO partidaxpregunta (idPartida, idPregunta)
|
|
||||||
VALUES (:idPartida, :idPregunta)
|
|
||||||
");
|
|
||||||
foreach ($elegidas as $idPregunta) {
|
|
||||||
$insertar->execute([
|
|
||||||
':idPartida' => $idPartida,
|
|
||||||
':idPregunta' => $idPregunta
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$conexion->commit();
|
|
||||||
return null;
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
if ($conexion->inTransaction()) {
|
|
||||||
$conexion->rollBack();
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
'error' => 'Ocurrió un error al preparar las preguntas de la partida.',
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Devuelve las preguntas de la partida (máximo 10) con sus respuestas
|
|
||||||
* mezcladas. NO incluye el campo 'correcta' para que no se pueda hacer
|
|
||||||
* trampa mirando la respuesta del servidor.
|
|
||||||
* Cada pregunta indica si este usuario ya la ha respondido, para poder
|
|
||||||
* retomar la partida si recarga la página.
|
|
||||||
*/
|
|
||||||
public static function cargarPreguntas($idPartida, $idUsuario)
|
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
|
||||||
if (is_array($conexion)) {
|
|
||||||
return $conexion;
|
|
||||||
}
|
|
||||||
|
|
||||||
$error = self::asegurarPreguntas($conexion, $idPartida);
|
|
||||||
if ($error !== null) {
|
|
||||||
return $error;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. Las preguntas, siempre en el mismo orden para todos los jugadores
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT
|
|
||||||
pxp.idPartidaxPregunta,
|
|
||||||
p.idPregunta,
|
|
||||||
p.nombrePregunta
|
|
||||||
FROM partidaxpregunta pxp
|
|
||||||
INNER JOIN pregunta p
|
|
||||||
ON p.idPregunta = pxp.idPregunta
|
|
||||||
WHERE pxp.idPartida = :idPartida
|
|
||||||
ORDER BY pxp.idPartidaxPregunta
|
|
||||||
LIMIT " . self::NUM_PREGUNTAS
|
|
||||||
);
|
|
||||||
$consulta->execute([':idPartida' => $idPartida]);
|
|
||||||
$preguntas = $consulta->fetchAll(PDO::FETCH_ASSOC);
|
|
||||||
|
|
||||||
// 2. Las respuestas de todas esas preguntas, agrupadas por pregunta
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT DISTINCT
|
|
||||||
r.idRespuesta,
|
|
||||||
r.idPregunta,
|
|
||||||
r.nombreRespuesta
|
|
||||||
FROM respuesta r
|
|
||||||
INNER JOIN partidaxpregunta pxp
|
|
||||||
ON pxp.idPregunta = r.idPregunta
|
|
||||||
WHERE pxp.idPartida = :idPartida
|
|
||||||
");
|
|
||||||
$consulta->execute([':idPartida' => $idPartida]);
|
|
||||||
|
|
||||||
$respuestasPorPregunta = [];
|
|
||||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
|
||||||
$respuestasPorPregunta[(int)$fila['idPregunta']][] = [
|
|
||||||
'idRespuesta' => (int)$fila['idRespuesta'],
|
|
||||||
'nombreRespuesta' => $fila['nombreRespuesta']
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Qué preguntas ha respondido ya este usuario
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT ra.idPartidaxPregunta
|
|
||||||
FROM respuestaalmacenada ra
|
|
||||||
INNER JOIN partidaxpregunta pxp
|
|
||||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
|
||||||
WHERE pxp.idPartida = :idPartida
|
|
||||||
AND ra.idUsuario = :idUsuario
|
|
||||||
");
|
|
||||||
$consulta->execute([
|
|
||||||
':idPartida' => $idPartida,
|
|
||||||
':idUsuario' => $idUsuario
|
|
||||||
]);
|
|
||||||
$respondidas = array_flip($consulta->fetchAll(PDO::FETCH_COLUMN));
|
|
||||||
|
|
||||||
// 4. Montamos la respuesta final
|
|
||||||
$resultado = [];
|
|
||||||
foreach ($preguntas as $pregunta) {
|
|
||||||
$idPregunta = (int)$pregunta['idPregunta'];
|
|
||||||
$idPxp = (int)$pregunta['idPartidaxPregunta'];
|
|
||||||
|
|
||||||
$respuestas = $respuestasPorPregunta[$idPregunta] ?? [];
|
|
||||||
shuffle($respuestas);
|
|
||||||
|
|
||||||
$resultado[] = [
|
|
||||||
'idPartidaxPregunta' => $idPxp,
|
|
||||||
'idPregunta' => $idPregunta,
|
|
||||||
'nombrePregunta' => $pregunta['nombrePregunta'],
|
|
||||||
'respondida' => isset($respondidas[$idPxp]),
|
|
||||||
'respuestas' => $respuestas
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
return [
|
|
||||||
'total' => count($resultado),
|
|
||||||
'respondidas' => count($respondidas),
|
|
||||||
'preguntas' => $resultado
|
|
||||||
];
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
return [
|
|
||||||
'error' => 'Ocurrió un error al cargar las preguntas.',
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Guarda la respuesta que ha elegido el usuario en una pregunta y
|
|
||||||
* devuelve si ha acertado y cuál era la correcta (para el feedback).
|
|
||||||
* Comprueba en el servidor que:
|
|
||||||
* - la pregunta pertenece a la partida
|
|
||||||
* - la respuesta pertenece a esa pregunta
|
|
||||||
* - el usuario no ha respondido ya esa pregunta
|
|
||||||
*/
|
|
||||||
public static function registrarRespuesta($idPartida, $idUsuario, $idPartidaxPregunta, $idRespuesta)
|
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
|
||||||
if (is_array($conexion)) {
|
|
||||||
return $conexion;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// 1. La pregunta tiene que ser de esta partida
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT idPregunta
|
|
||||||
FROM partidaxpregunta
|
|
||||||
WHERE idPartidaxPregunta = :idPxp
|
|
||||||
AND idPartida = :idPartida
|
|
||||||
");
|
|
||||||
$consulta->execute([
|
|
||||||
':idPxp' => $idPartidaxPregunta,
|
|
||||||
':idPartida' => $idPartida
|
|
||||||
]);
|
|
||||||
$idPregunta = $consulta->fetchColumn();
|
|
||||||
|
|
||||||
if ($idPregunta === false) {
|
|
||||||
return ['error' => 'Esa pregunta no pertenece a esta partida.'];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. La respuesta tiene que ser una de las de esa pregunta
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT idRespuesta, correcta
|
|
||||||
FROM respuesta
|
|
||||||
WHERE idPregunta = :idPregunta
|
|
||||||
");
|
|
||||||
$consulta->execute([':idPregunta' => $idPregunta]);
|
|
||||||
|
|
||||||
$elegida = null;
|
|
||||||
$primeraCorrecta = null;
|
|
||||||
foreach ($consulta->fetchAll(PDO::FETCH_ASSOC) as $fila) {
|
|
||||||
if ((int)$fila['correcta'] === 1 && $primeraCorrecta === null) {
|
|
||||||
$primeraCorrecta = (int)$fila['idRespuesta'];
|
|
||||||
}
|
|
||||||
if ((int)$fila['idRespuesta'] === $idRespuesta) {
|
|
||||||
$elegida = $fila;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($elegida === null) {
|
|
||||||
return ['error' => 'Esa respuesta no pertenece a la pregunta.'];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. Solo se puede responder una vez a cada pregunta
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM respuestaalmacenada
|
|
||||||
WHERE idPartidaxPregunta = :idPxp
|
|
||||||
AND idUsuario = :idUsuario
|
|
||||||
");
|
|
||||||
$consulta->execute([
|
|
||||||
':idPxp' => $idPartidaxPregunta,
|
|
||||||
':idUsuario' => $idUsuario
|
|
||||||
]);
|
|
||||||
|
|
||||||
if ((int)$consulta->fetchColumn() > 0) {
|
|
||||||
return ['error' => 'Ya has respondido a esta pregunta.'];
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Guardamos la respuesta con la clase que ya existía
|
|
||||||
$almacenada = new RespuestaAlmacenada(
|
|
||||||
null,
|
|
||||||
$idPartidaxPregunta,
|
|
||||||
$idUsuario,
|
|
||||||
$idRespuesta
|
|
||||||
);
|
|
||||||
$guardado = $almacenada->guardarRespuesta();
|
|
||||||
|
|
||||||
if (isset($guardado['error'])) {
|
|
||||||
return $guardado;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 5. Progreso del usuario en la partida
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM respuestaalmacenada ra
|
|
||||||
INNER JOIN partidaxpregunta pxp
|
|
||||||
ON pxp.idPartidaxPregunta = ra.idPartidaxPregunta
|
|
||||||
WHERE pxp.idPartida = :idPartida
|
|
||||||
AND ra.idUsuario = :idUsuario
|
|
||||||
");
|
|
||||||
$consulta->execute([
|
|
||||||
':idPartida' => $idPartida,
|
|
||||||
':idUsuario' => $idUsuario
|
|
||||||
]);
|
|
||||||
$respondidas = (int)$consulta->fetchColumn();
|
|
||||||
|
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
SELECT COUNT(*) FROM partidaxpregunta
|
|
||||||
WHERE idPartida = :idPartida
|
|
||||||
");
|
|
||||||
$consulta->execute([':idPartida' => $idPartida]);
|
|
||||||
$total = min((int)$consulta->fetchColumn(), self::NUM_PREGUNTAS);
|
|
||||||
|
|
||||||
$acierto = (int)$elegida['correcta'] === 1;
|
|
||||||
|
|
||||||
return [
|
|
||||||
'exito' => 'Respuesta guardada.',
|
|
||||||
'acierto' => $acierto,
|
|
||||||
'idRespuestaCorrecta' => $acierto ? $idRespuesta : $primeraCorrecta,
|
|
||||||
'respondidas' => $respondidas,
|
|
||||||
'total' => $total,
|
|
||||||
'terminada' => $respondidas >= $total
|
|
||||||
];
|
|
||||||
} catch (PDOException $error) {
|
|
||||||
return [
|
|
||||||
'error' => 'Ocurrió un error al guardar la respuesta.',
|
|
||||||
'error_tecnico' => $error->getMessage()
|
|
||||||
];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+158
-164
@@ -7,17 +7,27 @@ class Partida
|
|||||||
public $idPartida;
|
public $idPartida;
|
||||||
public $nombrePartida;
|
public $nombrePartida;
|
||||||
public $idUsuario;
|
public $idUsuario;
|
||||||
|
public $fechaCreacion;
|
||||||
|
public $fechaInicio;
|
||||||
|
public $fechaFin;
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
$idPartida = null,
|
$idPartida = null,
|
||||||
$nombrePartida = null,
|
$nombrePartida = null,
|
||||||
$idUsuario = null
|
$idUsuario = null,
|
||||||
|
$fechaCreacion = null,
|
||||||
|
$fechaInicio = null,
|
||||||
|
$fechaFin = null
|
||||||
) {
|
) {
|
||||||
$this->idPartida = $idPartida;
|
$this->idPartida = $idPartida;
|
||||||
$this->nombrePartida = $nombrePartida;
|
$this->nombrePartida = $nombrePartida;
|
||||||
$this->idUsuario = $idUsuario;
|
$this->idUsuario = $idUsuario;
|
||||||
|
$this->fechaCreacion = $fechaCreacion;
|
||||||
|
$this->fechaInicio = $fechaInicio;
|
||||||
|
$this->fechaFin = $fechaFin;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public function insertar()
|
public function insertar()
|
||||||
{
|
{
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
@@ -25,12 +35,7 @@ class Partida
|
|||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("INSERT INTO partida (nombrePartida,idUsuario) VALUES (:nombrePartida,:idUsuario)");
|
||||||
INSERT INTO partida
|
|
||||||
(nombrePartida,idUsuario)
|
|
||||||
VALUES
|
|
||||||
(:nombrePartida,:idUsuario)
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
||||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
@@ -46,8 +51,7 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function listar()
|
public function listar(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
@@ -64,18 +68,13 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function buscar()
|
public function buscar(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idPartida=:idPartida");
|
||||||
SELECT *
|
|
||||||
FROM partida
|
|
||||||
WHERE idPartida=:idPartida
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
return $consulta->fetch(PDO::FETCH_ASSOC);
|
return $consulta->fetch(PDO::FETCH_ASSOC);
|
||||||
@@ -87,20 +86,14 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function editar()
|
|
||||||
{
|
public function editar(){
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("UPDATE partida SET nombrePartida=:nombrePartida, idUsuario=:idUsuario WHERE idPartida=:idPartida");
|
||||||
UPDATE partida
|
|
||||||
SET
|
|
||||||
nombrePartida=:nombrePartida,
|
|
||||||
idUsuario=:idUsuario
|
|
||||||
WHERE idPartida=:idPartida
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
$consulta->bindParam(":nombrePartida", $this->nombrePartida);
|
||||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||||
@@ -117,17 +110,13 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function eliminar()
|
public function eliminar(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("DELETE FROM partida WHERE idPartida=:idPartida");
|
||||||
DELETE FROM partida
|
|
||||||
WHERE idPartida=:idPartida
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
return [
|
return [
|
||||||
@@ -142,27 +131,121 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Devuelve las preguntas asignadas a la partida, junto con el
|
public function iniciarPartida(){
|
||||||
* idPartidaxPregunta (necesario para guardar respuestas después).
|
$conexion = conexionBD();
|
||||||
*/
|
if (is_array($conexion)){
|
||||||
public function getPreguntas()
|
return $conexion;
|
||||||
{
|
}
|
||||||
|
try {
|
||||||
|
$consulta = $conexion->prepare("UPDATE partida SET fechaInicio=NOW() WHERE idPartida=:idPartida AND fechaInicio IS NULL");
|
||||||
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
|
$consulta->execute();
|
||||||
|
return [
|
||||||
|
"exito" => "La partida ha comenzado.",
|
||||||
|
"exito_tecnico" => $this->idPartida
|
||||||
|
];
|
||||||
|
} catch (PDOException $error) {
|
||||||
|
return [
|
||||||
|
"error" => "Ocurrió un error al iniciar la partida.",
|
||||||
|
'error_tecnico' => $error->getMessage()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public function finalizar(){
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("UPDATE partida SET fechaFin=NOW() WHERE idPartida=:idPartida AND fechaFin IS NULL");
|
||||||
SELECT
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
pxp.idPartidaxPregunta,
|
$consulta->execute();
|
||||||
p.*
|
return [
|
||||||
FROM partidaxpregunta pxp
|
"exito" => "La partida se finalizó correctamente.",
|
||||||
INNER JOIN pregunta p
|
"exito_tecnico" => $this->idPartida
|
||||||
ON pxp.idPregunta=p.idPregunta
|
];
|
||||||
WHERE pxp.idPartida=:idPartida
|
} catch (PDOException $error) {
|
||||||
ORDER BY pxp.idPartidaxPregunta
|
return [
|
||||||
");
|
"error" => "Ocurrió un error al finalizar la partida.",
|
||||||
|
'error_tecnico' => $error->getMessage()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//true si la partida ya tiene fecha de fin (fechaFin no es NULL)
|
||||||
|
//Devuelve false si la partida no existe
|
||||||
|
|
||||||
|
public function estaFinalizada() {
|
||||||
|
$datos = $this->buscar();
|
||||||
|
if (is_array($datos) && isset($datos["error"])) {
|
||||||
|
return $datos;
|
||||||
|
}
|
||||||
|
if (!$datos) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return $datos["fechaFin"] !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//Devuelve la partida más reciente del usuario que aún no ha
|
||||||
|
//terminado (fechaFin NULL), o false si no tiene ninguna.
|
||||||
|
//Incluye también las salas que todavía no han empezado.
|
||||||
|
|
||||||
|
public function partidaEnCursoDeUsuario(){
|
||||||
|
$conexion = conexionBD();
|
||||||
|
if (is_array($conexion)) {
|
||||||
|
return $conexion;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idUsuario=:idUsuario AND fechaFin IS NULL ORDER BY idPartida DESC LIMIT 1");
|
||||||
|
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||||
|
$consulta->execute();
|
||||||
|
return $consulta->fetch(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $error) {
|
||||||
|
return [
|
||||||
|
"error" => "Ocurrió un error al buscar la partida en curso.",
|
||||||
|
'error_tecnico' => $error->getMessage()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public function listarSalasAbiertas() {
|
||||||
|
$conexion = conexionBD();
|
||||||
|
if (is_array($conexion)) {
|
||||||
|
return $conexion;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$consulta = $conexion->prepare("SELECT p.idPartida, p.nombrePartida, e.idEquipo, e.nombreEquipo, u.idUsuario, u.nombreUsuario
|
||||||
|
FROM partida p INNER JOIN equipoxpartida exp ON exp.idPartida=p.idPartida INNER JOIN equipo e ON e.idEquipo=exp.idEquipo
|
||||||
|
LEFT JOIN equipoxusuario exu ON exu.idEquipo=e.idEquipo LEFT JOIN usuario u ON u.idUsuario=exu.idUsuario WHERE p.fechaInicio IS NULL
|
||||||
|
AND p.fechaFin IS NULL ORDER BY p.idPartida DESC, e.idEquipo ASC");
|
||||||
|
$consulta->execute();
|
||||||
|
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||||
|
} catch (PDOException $error) {
|
||||||
|
return [
|
||||||
|
"error" => "Ocurrió un error al recuperar las salas abiertas.",
|
||||||
|
'error_tecnico' => $error->getMessage()
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Devuelve las preguntas asignadas a la partida, junto con el
|
||||||
|
* idPartidaxPregunta (necesario para guardar respuestas después).
|
||||||
|
*/
|
||||||
|
public function getPreguntas(){
|
||||||
|
$conexion = conexionBD();
|
||||||
|
if (is_array($conexion)) {
|
||||||
|
return $conexion;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$consulta = $conexion->prepare("SELECT pxp.idPartidaxPregunta, p.* FROM partidaxpregunta pxp INNER JOIN pregunta p ON pxp.idPregunta=p.idPregunta
|
||||||
|
WHERE pxp.idPartida=:idPartida ORDER BY pxp.idPartidaxPregunta");
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||||
@@ -174,22 +257,14 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Asocia una pregunta ya existente a esta partida.
|
public function asignarPregunta($idPregunta) {
|
||||||
*/
|
|
||||||
public function asignarPregunta($idPregunta)
|
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("INSERT INTO partidaxpregunta (idPartida,idPregunta) VALUES (:idPartida,:idPregunta)");
|
||||||
INSERT INTO partidaxpregunta
|
|
||||||
(idPartida,idPregunta)
|
|
||||||
VALUES
|
|
||||||
(:idPartida,:idPregunta)
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->bindParam(":idPregunta", $idPregunta);
|
$consulta->bindParam(":idPregunta", $idPregunta);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
@@ -205,18 +280,13 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
//Cuenta cuántas preguntas tiene la partida en total. Es la primera mitad de la comprobación "¿ha terminado el usuario de jugar?".
|
//Cuenta cuántas preguntas tiene la partida en total. Es la primera mitad de la comprobación "¿ha terminado el usuario de jugar?".
|
||||||
public function contarPreguntasAsignadas()
|
public function contarPreguntasAsignadas() {
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM partidaxpregunta WHERE idPartida=:idPartida");
|
||||||
SELECT COUNT(*) AS total
|
|
||||||
FROM partidaxpregunta
|
|
||||||
WHERE idPartida=:idPartida
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
$fila = $consulta->fetch(PDO::FETCH_ASSOC);
|
$fila = $consulta->fetch(PDO::FETCH_ASSOC);
|
||||||
@@ -229,21 +299,14 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function contarRespuestasUsuario($idUsuario)
|
public function contarRespuestasUsuario($idUsuario){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM respuestaalmacenada ra INNER JOIN partidaxpregunta pxp
|
||||||
SELECT COUNT(*) AS total
|
ON ra.idPartidaxPregunta=pxp.idPartidaxPregunta WHERE pxp.idPartida=:idPartida AND ra.idUsuario=:idUsuario");
|
||||||
FROM respuestaalmacenada ra
|
|
||||||
INNER JOIN partidaxpregunta pxp
|
|
||||||
ON ra.idPartidaxPregunta=pxp.idPartidaxPregunta
|
|
||||||
WHERE pxp.idPartida=:idPartida
|
|
||||||
AND ra.idUsuario=:idUsuario
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->bindParam(":idUsuario", $idUsuario);
|
$consulta->bindParam(":idUsuario", $idUsuario);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
@@ -258,11 +321,11 @@ class Partida
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sustituye al antiguo campo `terminada`: compara cuántas preguntas
|
* Indica si ESTE usuario ya ha respondido todas las preguntas:
|
||||||
* tiene la partida contra cuántas ha respondido este usuario.
|
* compara cuántas preguntas tiene la partida contra cuántas ha
|
||||||
|
* respondido él. (La partida completa se marca con finalizar().)
|
||||||
*/
|
*/
|
||||||
public function estaFinalizadaParaUsuario($idUsuario)
|
public function estaFinalizadaParaUsuario($idUsuario){
|
||||||
{
|
|
||||||
$totalPreguntas = $this->contarPreguntasAsignadas();
|
$totalPreguntas = $this->contarPreguntasAsignadas();
|
||||||
if (is_array($totalPreguntas)) {
|
if (is_array($totalPreguntas)) {
|
||||||
return $totalPreguntas;
|
return $totalPreguntas;
|
||||||
@@ -277,19 +340,13 @@ class Partida
|
|||||||
/**
|
/**
|
||||||
* Partidas creadas por un usuario, de más reciente a más antigua.
|
* Partidas creadas por un usuario, de más reciente a más antigua.
|
||||||
*/
|
*/
|
||||||
public function listarDelUsuario()
|
public function listarDelUsuario(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("SELECT * FROM partida WHERE idUsuario=:idUsuario ORDER BY idPartida DESC");
|
||||||
SELECT *
|
|
||||||
FROM partida
|
|
||||||
WHERE idUsuario=:idUsuario
|
|
||||||
ORDER BY idPartida DESC
|
|
||||||
");
|
|
||||||
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
$consulta->bindParam(":idUsuario", $this->idUsuario);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||||
@@ -301,22 +358,13 @@ class Partida
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function preguntaAsignada($idPregunta)
|
public function preguntaAsignada($idPregunta) {
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$consulta = $conexion->prepare("
|
$consulta = $conexion->prepare("SELECT COUNT(*) AS total FROM partidaxpregunta WHERE idPartida=:idPartida AND idPregunta=:idPregunta");
|
||||||
SELECT COUNT(*) AS total
|
|
||||||
FROM partidaxpregunta
|
|
||||||
WHERE idPartida=:idPartida
|
|
||||||
AND idPregunta=:idPregunta
|
|
||||||
");
|
|
||||||
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->bindParam(":idPregunta", $idPregunta);
|
$consulta->bindParam(":idPregunta", $idPregunta);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
@@ -336,24 +384,13 @@ class Partida
|
|||||||
* Vincula un equipo a esta partida en la tabla intermedia 'equipoxpartida'.
|
* Vincula un equipo a esta partida en la tabla intermedia 'equipoxpartida'.
|
||||||
* Permite registrar qué grupos están participando en este torneo.
|
* Permite registrar qué grupos están participando en este torneo.
|
||||||
*/
|
*/
|
||||||
public function registrarEquipoEnPartida($idEquipo)
|
public function registrarEquipoEnPartida($idEquipo){
|
||||||
{
|
$conexion = conexionBD();
|
||||||
$conexion = conexionBD(); // Obtenemos la conexión modular del proyecto
|
|
||||||
|
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion; // Si hay error en la conexión, lo devuelve
|
return $conexion;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Preparamos la consulta para insertar la relación en la tabla intermedia real
|
$consulta = $conexion->prepare("INSERT INTO equipoxpartida (idPartida, idEquipo) VALUES (:idPartida, :idEquipo)");
|
||||||
$consulta = $conexion->prepare("
|
|
||||||
INSERT INTO equipoxpartida
|
|
||||||
(idPartida, idEquipo)
|
|
||||||
VALUES
|
|
||||||
(:idPartida, :idEquipo)
|
|
||||||
");
|
|
||||||
|
|
||||||
// Vinculamos los parámetros con el objeto de la partida actual y el equipo recibido
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->bindParam(":idEquipo", $idEquipo);
|
$consulta->bindParam(":idEquipo", $idEquipo);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
@@ -363,7 +400,6 @@ class Partida
|
|||||||
"exito_tecnico" => $conexion->lastInsertId()
|
"exito_tecnico" => $conexion->lastInsertId()
|
||||||
];
|
];
|
||||||
} catch (PDOException $error) {
|
} catch (PDOException $error) {
|
||||||
// Capturamos el error extrayendo solo el mensaje de texto limpio
|
|
||||||
return [
|
return [
|
||||||
"error" => "Ocurrió un error al asignar el equipo a la partida.",
|
"error" => "Ocurrió un error al asignar el equipo a la partida.",
|
||||||
"error_tecnico" => $error->getMessage()
|
"error_tecnico" => $error->getMessage()
|
||||||
@@ -375,28 +411,14 @@ class Partida
|
|||||||
* Obtiene todos los equipos que están compitiendo en esta partida.
|
* Obtiene todos los equipos que están compitiendo en esta partida.
|
||||||
* Es útil para mostrar la lista de rivales antes de empezar a responder.
|
* Es útil para mostrar la lista de rivales antes de empezar a responder.
|
||||||
*/
|
*/
|
||||||
public function getEquiposParticipantes()
|
public function getEquiposParticipantes(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Hacemos un INNER JOIN para traer los nombres de los equipos desde la tabla intermedia
|
$consulta = $conexion->prepare("SELECT exp.idEquipoxPartida, e.idEquipo, e.nombreEquipo FROM equipoxpartida exp
|
||||||
$consulta = $conexion->prepare("
|
INNER JOIN equipo e ON exp.idEquipo = e.idEquipo WHERE exp.idPartida = :idPartida ORDER BY e.nombreEquipo ASC");
|
||||||
SELECT
|
|
||||||
exp.idEquipoxPartida,
|
|
||||||
e.idEquipo,
|
|
||||||
e.nombreEquipo
|
|
||||||
FROM equipoxpartida exp
|
|
||||||
INNER JOIN equipo e
|
|
||||||
ON exp.idEquipo = e.idEquipo
|
|
||||||
WHERE exp.idPartida = :idPartida
|
|
||||||
ORDER BY e.nombreEquipo ASC
|
|
||||||
");
|
|
||||||
|
|
||||||
$consulta->bindParam(":idPartida", $this->idPartida);
|
$consulta->bindParam(":idPartida", $this->idPartida);
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
|
|
||||||
@@ -413,54 +435,26 @@ class Partida
|
|||||||
* Obtiene todos los jugadores reales (Usuarios) que están jugando en esta partida.
|
* Obtiene todos los jugadores reales (Usuarios) que están jugando en esta partida.
|
||||||
* Utiliza la tabla 'equipoxusuario' en SQL para cruzar los datos.
|
* Utiliza la tabla 'equipoxusuario' en SQL para cruzar los datos.
|
||||||
*/
|
*/
|
||||||
public function getJugadoresDeLaPartida()
|
public function getJugadoresDeLaPartida(){
|
||||||
{
|
|
||||||
$conexion = conexionBD();
|
$conexion = conexionBD();
|
||||||
|
|
||||||
if (is_array($conexion)) {
|
if (is_array($conexion)) {
|
||||||
return $conexion;
|
return $conexion;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
$consulta = $conexion->prepare("SELECT DISTINCT u.idUsuario, u.nombreUsuario, u.email, e.idEquipo, e.nombreEquipo
|
||||||
$consulta = $conexion->prepare("
|
FROM equipoxpartida exp INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo INNER JOIN usuario u
|
||||||
SELECT DISTINCT
|
ON exu.idUsuario = u.idUsuario INNER JOIN equipo e ON exu.idEquipo = e.idEquipo WHERE exp.idPartida = :idPartida
|
||||||
u.idUsuario,
|
ORDER BY e.nombreEquipo ASC, u.nombreUsuario ASC");
|
||||||
u.nombreUsuario,
|
|
||||||
u.email,
|
|
||||||
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
|
|
||||||
|
|
||||||
ORDER BY e.nombreEquipo ASC,
|
|
||||||
u.nombreUsuario ASC
|
|
||||||
");
|
|
||||||
|
|
||||||
$consulta->bindParam(
|
$consulta->bindParam(
|
||||||
":idPartida",
|
":idPartida",
|
||||||
$this->idPartida
|
$this->idPartida
|
||||||
);
|
);
|
||||||
|
|
||||||
$consulta->execute();
|
$consulta->execute();
|
||||||
|
|
||||||
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
return $consulta->fetchAll(PDO::FETCH_ASSOC);
|
||||||
} catch (PDOException $error) {
|
} catch (PDOException $error) {
|
||||||
|
|
||||||
return [
|
return [
|
||||||
"error" =>
|
"error" =>
|
||||||
"Ocurrió un error al obtener la lista de jugadores.",
|
"Ocurrió un error al obtener la lista de jugadores.",
|
||||||
|
|
||||||
"error_tecnico" =>
|
"error_tecnico" =>
|
||||||
$error->getMessage()
|
$error->getMessage()
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
<?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
|
|
||||||
if (!isset($_SESSION['idUsuario'])) {
|
|
||||||
echo json_encode(['error' => 'Debes iniciar sesión para jugar.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
$idUsuario = (int)$_SESSION['idUsuario'];
|
|
||||||
$idPartida = intval($_POST['idPartida'] ?? 0);
|
|
||||||
|
|
||||||
if ($idPartida <= 0) {
|
|
||||||
echo json_encode(['error' => 'No se ha indicado la partida.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Solo pueden jugar los usuarios que están en uno de los equipos de 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.']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
switch ($_POST['orden'] ?? '') {
|
|
||||||
|
|
||||||
// Devuelve las 10 preguntas con sus respuestas (sin marcar la correcta)
|
|
||||||
case 'cargarPreguntas':
|
|
||||||
|
|
||||||
echo json_encode(Juego::cargarPreguntas($idPartida, $idUsuario));
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
// 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
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
|
|
||||||
if (!isset($_SESSION['aciertosPorPartida'])) {
|
|
||||||
$_SESSION['aciertosPorPartida'] = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$_SESSION['aciertosPorPartida'][$idPartida] = $aciertos;
|
|
||||||
|
|
||||||
echo json_encode([
|
|
||||||
'exito' => 'Aciertos registrados correctamente.',
|
|
||||||
'idPartida' => $idPartida,
|
|
||||||
'aciertos' => $aciertos
|
|
||||||
]);
|
|
||||||
|
|
||||||
break;
|
|
||||||
|
|
||||||
|
|
||||||
default:
|
|
||||||
|
|
||||||
echo json_encode(['error' => 'La orden indicada no existe.']);
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
@@ -55,11 +55,10 @@ switch ($_POST['orden']) {
|
|||||||
|
|
||||||
if ($resultado instanceof Usuario) {
|
if ($resultado instanceof Usuario) {
|
||||||
|
|
||||||
// === GUARDAR EN SESIÓN (incluido avatar)===
|
// === AÑADIR ESTAS LÍNEAS PARA GUARDAR EN SESIÓN ===
|
||||||
$_SESSION['idUsuario'] = $resultado->getIdUsuario();
|
$_SESSION['idUsuario'] = $resultado->getIdUsuario();
|
||||||
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
$_SESSION['nombreUsuario'] = $resultado->getNombreUsuario();
|
||||||
$_SESSION['email'] = $resultado->getEmail();
|
$_SESSION['email'] = $resultado->getEmail();
|
||||||
$_SESSION['avatar'] = $resultado->getAvatar();
|
|
||||||
// =================================================
|
// =================================================
|
||||||
|
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
@@ -84,7 +83,6 @@ switch ($_POST['orden']) {
|
|||||||
unset($_SESSION['idUsuario']);
|
unset($_SESSION['idUsuario']);
|
||||||
unset($_SESSION['email']);
|
unset($_SESSION['email']);
|
||||||
unset($_SESSION['nombreUsuario']);
|
unset($_SESSION['nombreUsuario']);
|
||||||
unset($_SESSION['avatar']);
|
|
||||||
|
|
||||||
// Destruimos la sesión
|
// Destruimos la sesión
|
||||||
session_destroy();
|
session_destroy();
|
||||||
@@ -94,6 +92,7 @@ switch ($_POST['orden']) {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'mostrarEstadisticas':
|
case 'mostrarEstadisticas':
|
||||||
|
|
||||||
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
$usuario = Usuario::buscarPorId($_SESSION['idUsuario']);
|
||||||
@@ -238,17 +237,16 @@ switch ($_POST['orden']) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case 'comprobarSesion':
|
case 'comprobarSesion':
|
||||||
if (isset($_SESSION['idUsuario']) && !empty($_SESSION['idUsuario'])) {
|
if (isset($_SESSION['idUsuario']) && !empty($_SESSION['idUsuario'])) {
|
||||||
echo json_encode([
|
echo json_encode([
|
||||||
'activa' => true,
|
'activa' => true,
|
||||||
'usuario' => [
|
'usuario' => [
|
||||||
'idUsuario' => $_SESSION['idUsuario'],
|
'idUsuario' => $_SESSION['idUsuario'],
|
||||||
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? '',
|
'nombreUsuario' => $_SESSION['nombreUsuario'] ?? ''
|
||||||
'avatar' => $_SESSION['avatar'] ?? ''
|
]
|
||||||
]
|
]);
|
||||||
]);
|
} else {
|
||||||
} else {
|
echo json_encode(['activa' => false]);
|
||||||
echo json_encode(['activa' => false]);
|
}
|
||||||
}
|
break;
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -117,65 +117,3 @@
|
|||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ===== Lógica de juego (js/juego.js) ===== */
|
|
||||||
|
|
||||||
.game-header {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
font-weight: 600;
|
|
||||||
color: #333;
|
|
||||||
margin-bottom: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.progress-track {
|
|
||||||
height: 8px;
|
|
||||||
background-color: #ddd;
|
|
||||||
border-radius: 4px;
|
|
||||||
overflow: hidden;
|
|
||||||
margin-bottom: 16px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.progress-fill {
|
|
||||||
height: 100%;
|
|
||||||
width: 0;
|
|
||||||
background-color: #1368ce;
|
|
||||||
transition: width 0.3s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.feedback {
|
|
||||||
min-height: 1.5em;
|
|
||||||
margin-top: 12px;
|
|
||||||
font-size: 18px;
|
|
||||||
font-weight: 600;
|
|
||||||
}
|
|
||||||
|
|
||||||
.feedback.ok { color: #26890c; }
|
|
||||||
.feedback.ko { color: #e21b3c; }
|
|
||||||
|
|
||||||
/* Mientras se envía la respuesta o se ve el feedback no se puede volver a pulsar */
|
|
||||||
.answers-grid.bloqueado .btn-answer {
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-answer.correcta {
|
|
||||||
box-shadow: 0 0 0 6px #fff, 0 0 0 10px #26890c;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-answer.incorrecta,
|
|
||||||
.btn-answer.atenuada {
|
|
||||||
opacity: 0.45;
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-answer:focus-visible {
|
|
||||||
outline: 4px solid #333;
|
|
||||||
outline-offset: 3px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-reduced-motion: reduce) {
|
|
||||||
.progress-fill,
|
|
||||||
.btn-answer {
|
|
||||||
transition: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+17
-15
@@ -26,7 +26,7 @@ $(document).ready(function () {
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Comprueba con el servidor si existe una sesión PHP
|
* Comprueba con el servidor si existe una sesión PHP activa.
|
||||||
*/
|
*/
|
||||||
function comprobarEstadoSesion() {
|
function comprobarEstadoSesion() {
|
||||||
$.ajax({
|
$.ajax({
|
||||||
@@ -37,6 +37,7 @@ function comprobarEstadoSesion() {
|
|||||||
success: function (respuesta) {
|
success: function (respuesta) {
|
||||||
if (respuesta.activa) {
|
if (respuesta.activa) {
|
||||||
renderizarCabeceraConSesion(respuesta.usuario);
|
renderizarCabeceraConSesion(respuesta.usuario);
|
||||||
|
// Si existe el contenedor del botón Jugar en index, lo mostramos
|
||||||
$('#colBotonJugar').removeClass('d-none');
|
$('#colBotonJugar').removeClass('d-none');
|
||||||
} else {
|
} else {
|
||||||
renderizarCabeceraSinSesion();
|
renderizarCabeceraSinSesion();
|
||||||
@@ -78,8 +79,13 @@ function ejecutarLogin() {
|
|||||||
$('#modalLogin').modal('hide');
|
$('#modalLogin').modal('hide');
|
||||||
$('#formLogin')[0].reset();
|
$('#formLogin')[0].reset();
|
||||||
|
|
||||||
// Cargar datos de la sesión actualizados
|
renderizarCabeceraConSesion({
|
||||||
comprobarEstadoSesion();
|
idUsuario: respuesta.idUsuario,
|
||||||
|
nombreUsuario: respuesta.nombreUsuario,
|
||||||
|
avatar: respuesta.avatar
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#colBotonJugar').removeClass('d-none');
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
error: function () {
|
error: function () {
|
||||||
@@ -126,7 +132,7 @@ function ejecutarRegistro() {
|
|||||||
$('#modalRegistro').modal('hide');
|
$('#modalRegistro').modal('hide');
|
||||||
$('#formRegistro')[0].reset();
|
$('#formRegistro')[0].reset();
|
||||||
|
|
||||||
// Autologin tras registrarse
|
// Autologin
|
||||||
$('#loginEmail').val(email);
|
$('#loginEmail').val(email);
|
||||||
$('#loginPassword').val(pass);
|
$('#loginPassword').val(pass);
|
||||||
ejecutarLogin();
|
ejecutarLogin();
|
||||||
@@ -159,21 +165,15 @@ function cerrarSesion() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renderiza la cabecera cuando HAY sesión iniciada
|
* Renderiza la cabecera cuando HAY sesión iniciada (Menú Perfil + Avatar)
|
||||||
*/
|
*/
|
||||||
function renderizarCabeceraConSesion(usuario) {
|
function renderizarCabeceraConSesion(usuario) {
|
||||||
//Mete el avatar en cabecera
|
let avatarImg = usuario.avatar ? usuario.avatar : 'img/avatars/defaultProfile.jpeg';
|
||||||
let avatarImg = (usuario.avatar && usuario.avatar !== '')
|
|
||||||
? usuario.avatar
|
|
||||||
: 'img/avatars/defaultProfile.jpeg';
|
|
||||||
|
|
||||||
// Refrescar avatar si se cambia
|
|
||||||
let avatarConCacheBuster = avatarImg + '?v=' + new Date().getTime();
|
|
||||||
|
|
||||||
let html = `
|
let html = `
|
||||||
<div class="dropdown">
|
<div class="dropdown">
|
||||||
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
<button class="btn btn-outline-light dropdown-toggle d-flex align-items-center gap-2 rounded-pill px-3 py-1 fw-bold" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
|
||||||
<img src="${avatarConCacheBuster}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
<img src="${avatarImg}" alt="Avatar" class="rounded-circle border" style="width: 32px; height: 32px; object-fit: cover;">
|
||||||
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
<span>${escapeHtml(usuario.nombreUsuario)}</span>
|
||||||
</button>
|
</button>
|
||||||
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
<ul class="dropdown-menu dropdown-menu-end shadow border-0 mt-2" aria-labelledby="userMenu">
|
||||||
@@ -195,11 +195,13 @@ function renderizarCabeceraConSesion(usuario) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renderiza los botones en la cabecera cuando NO hay sesión (Iniciar sesión azul)
|
* Renderiza los botones originales:
|
||||||
|
* - "Iniciar Sesión" (Rojo -> btn-danger)
|
||||||
|
* - "Registrarse" (Verde -> btn-success)
|
||||||
*/
|
*/
|
||||||
function renderizarCabeceraSinSesion() {
|
function renderizarCabeceraSinSesion() {
|
||||||
let html = `
|
let html = `
|
||||||
<button class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
<button class="btn btn-danger rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalLogin">
|
||||||
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
<i class="fa-solid fa-right-to-bracket me-1"></i> Iniciar sesión
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
<button class="btn btn-success rounded-pill px-4 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#modalRegistro">
|
||||||
|
|||||||
-219
@@ -1,219 +0,0 @@
|
|||||||
// Lógica de juego.php
|
|
||||||
// Carga las preguntas de la partida, las muestra de una en una,
|
|
||||||
// guarda cada respuesta en el servidor y al terminar lleva a resultados.php
|
|
||||||
|
|
||||||
const URL_CONTROLADOR = "controladores/ControladorJuego.php";
|
|
||||||
const PAUSA_FEEDBACK = 1800; // ms que se ve si has acertado o fallado
|
|
||||||
|
|
||||||
// Colores y formas de los botones (estilo Kahoot, definidos en juego.css)
|
|
||||||
const ESTILOS_BOTON = [
|
|
||||||
{ color: "red", forma: "triangle" },
|
|
||||||
{ color: "blue", forma: "diamond" },
|
|
||||||
{ color: "yellow", forma: "circle" },
|
|
||||||
{ color: "green", forma: "square" },
|
|
||||||
];
|
|
||||||
|
|
||||||
let idPartida = 0;
|
|
||||||
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
|
|
||||||
|
|
||||||
$(document).ready(function () {
|
|
||||||
idPartida = parseInt($("body").data("id-partida"), 10);
|
|
||||||
|
|
||||||
// Un solo listener para todos los botones de respuesta
|
|
||||||
$("#respuestas").on("click", ".btn-answer", function () {
|
|
||||||
responder($(this));
|
|
||||||
});
|
|
||||||
|
|
||||||
cargarPreguntas();
|
|
||||||
});
|
|
||||||
|
|
||||||
// 1. Pedir las preguntas al servidor
|
|
||||||
function cargarPreguntas() {
|
|
||||||
$.ajax({
|
|
||||||
url: URL_CONTROLADOR,
|
|
||||||
type: "POST",
|
|
||||||
dataType: "json",
|
|
||||||
data: { orden: "cargarPreguntas", idPartida: idPartida },
|
|
||||||
success: function (datos) {
|
|
||||||
if (datos.error) {
|
|
||||||
mostrarError(datos.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
preguntas = datos.preguntas;
|
|
||||||
|
|
||||||
if (preguntas.length === 0) {
|
|
||||||
mostrarError("Esta partida no tiene preguntas.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retomamos por la primera pregunta sin responder (por si recarga la página)
|
|
||||||
indice = preguntas.findIndex(function (p) {
|
|
||||||
return !p.respondida;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (indice === -1) {
|
|
||||||
irAResultados();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
mostrarPregunta();
|
|
||||||
},
|
|
||||||
error: function () {
|
|
||||||
mostrarError("No se pudo conectar con el servidor.");
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Pintar la pregunta actual y sus respuestas
|
|
||||||
function mostrarPregunta() {
|
|
||||||
const pregunta = preguntas[indice];
|
|
||||||
|
|
||||||
bloqueado = false;
|
|
||||||
|
|
||||||
$("#textoPregunta").text(pregunta.nombrePregunta);
|
|
||||||
$("#feedback").text("").removeClass("ok ko");
|
|
||||||
$("#contadorPregunta").text(
|
|
||||||
"Pregunta " + (indice + 1) + " de " + preguntas.length,
|
|
||||||
);
|
|
||||||
$("#barraProgreso").css("width", (indice / preguntas.length) * 100 + "%");
|
|
||||||
|
|
||||||
const $respuestas = $("#respuestas").empty();
|
|
||||||
|
|
||||||
pregunta.respuestas.forEach(function (respuesta, i) {
|
|
||||||
const estilo = ESTILOS_BOTON[i % ESTILOS_BOTON.length];
|
|
||||||
|
|
||||||
// .text() y createTextNode evitan que el texto de la BD se interprete como HTML
|
|
||||||
const $boton = $("<button>")
|
|
||||||
.attr("type", "button")
|
|
||||||
.addClass("btn-answer " + estilo.color)
|
|
||||||
.attr("data-id-respuesta", respuesta.idRespuesta)
|
|
||||||
.append($("<span>").addClass("shape " + estilo.forma))
|
|
||||||
.append(document.createTextNode(respuesta.nombreRespuesta));
|
|
||||||
|
|
||||||
$respuestas.append($boton);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. El usuario pulsa una respuesta: se guarda y se enseña si ha acertado
|
|
||||||
function responder($botonPulsado) {
|
|
||||||
if (bloqueado) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
bloqueado = true;
|
|
||||||
|
|
||||||
const pregunta = preguntas[indice];
|
|
||||||
const idRespuesta = parseInt($botonPulsado.attr("data-id-respuesta"), 10);
|
|
||||||
|
|
||||||
$("#respuestas").addClass("bloqueado");
|
|
||||||
|
|
||||||
$.ajax({
|
|
||||||
url: URL_CONTROLADOR,
|
|
||||||
type: "POST",
|
|
||||||
dataType: "json",
|
|
||||||
data: {
|
|
||||||
orden: "responder",
|
|
||||||
idPartida: idPartida,
|
|
||||||
idPartidaxPregunta: pregunta.idPartidaxPregunta,
|
|
||||||
idRespuesta: idRespuesta,
|
|
||||||
},
|
|
||||||
success: function (datos) {
|
|
||||||
if (datos.error) {
|
|
||||||
// No se guardó: dejamos que vuelva a intentarlo
|
|
||||||
$("#feedback").text(datos.error).removeClass("ok").addClass("ko");
|
|
||||||
$("#respuestas").removeClass("bloqueado");
|
|
||||||
bloqueado = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
pregunta.respondida = true;
|
|
||||||
mostrarFeedback($botonPulsado, datos);
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
if (datos.terminada || indice >= preguntas.length - 1) {
|
|
||||||
terminar();
|
|
||||||
} else {
|
|
||||||
indice++;
|
|
||||||
$("#respuestas").removeClass("bloqueado");
|
|
||||||
mostrarPregunta();
|
|
||||||
}
|
|
||||||
}, PAUSA_FEEDBACK);
|
|
||||||
},
|
|
||||||
error: function () {
|
|
||||||
$("#feedback")
|
|
||||||
.text("No se pudo guardar la respuesta. Inténtalo de nuevo.")
|
|
||||||
.removeClass("ok")
|
|
||||||
.addClass("ko");
|
|
||||||
$("#respuestas").removeClass("bloqueado");
|
|
||||||
bloqueado = false;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Marca la respuesta correcta en verde y atenúa el resto
|
|
||||||
function mostrarFeedback($botonPulsado, datos) {
|
|
||||||
$("#respuestas .btn-answer").each(function () {
|
|
||||||
const $boton = $(this);
|
|
||||||
const esLaCorrecta =
|
|
||||||
parseInt($boton.attr("data-id-respuesta"), 10) ===
|
|
||||||
datos.idRespuestaCorrecta;
|
|
||||||
|
|
||||||
if (esLaCorrecta) {
|
|
||||||
$boton.addClass("correcta");
|
|
||||||
} else {
|
|
||||||
$boton.addClass("atenuada");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (datos.acierto) {
|
|
||||||
$("#feedback").text("¡Correcto!").removeClass("ko").addClass("ok");
|
|
||||||
numeroAciertos++;
|
|
||||||
} else {
|
|
||||||
$botonPulsado.addClass("incorrecta");
|
|
||||||
$("#feedback")
|
|
||||||
.text("Respuesta incorrecta. La correcta está marcada.")
|
|
||||||
.removeClass("ok")
|
|
||||||
.addClass("ko");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Última pregunta respondida: se avisa al backend con los aciertos y luego se va a resultados
|
|
||||||
function terminar() {
|
|
||||||
$("#barraProgreso").css("width", "100%");
|
|
||||||
$("#respuestas").empty();
|
|
||||||
$("#contadorPregunta").text("Partida terminada");
|
|
||||||
$("#textoPregunta").text("¡Has terminado! Cargando resultados…");
|
|
||||||
$("#feedback").text("").removeClass("ok ko");
|
|
||||||
|
|
||||||
setTimeout(function () {
|
|
||||||
$.ajax({
|
|
||||||
url: URL_CONTROLADOR,
|
|
||||||
type: "POST",
|
|
||||||
dataType: "json",
|
|
||||||
data: {
|
|
||||||
orden: "finalizarPartida",
|
|
||||||
idPartida: idPartida,
|
|
||||||
aciertos: numeroAciertos,
|
|
||||||
},
|
|
||||||
complete: function () {
|
|
||||||
// Se va a resultados tanto si el AJAX ha ido bien como si ha fallado
|
|
||||||
irAResultados();
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}, 1200);
|
|
||||||
}
|
|
||||||
|
|
||||||
function irAResultados() {
|
|
||||||
window.location.href = "resultados.php?idPartida=" + idPartida;
|
|
||||||
}
|
|
||||||
|
|
||||||
function mostrarError(mensaje) {
|
|
||||||
$("#respuestas").empty();
|
|
||||||
$("#textoPregunta").text(mensaje);
|
|
||||||
$("#feedback").html(
|
|
||||||
'<a href="buscadorSala.php">Volver al buscador de salas</a>',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+27
-20
@@ -26,10 +26,6 @@ $.ajax({
|
|||||||
function cambiarNombre() {
|
function cambiarNombre() {
|
||||||
let nuevoNombre = $("#nuevoNombre").val().trim();
|
let nuevoNombre = $("#nuevoNombre").val().trim();
|
||||||
|
|
||||||
if (nuevoNombre === "") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "controladores/controladorUsuario.php",
|
url: "controladores/controladorUsuario.php",
|
||||||
@@ -46,13 +42,8 @@ function cambiarNombre() {
|
|||||||
// Actualizamos el nombre mostrado en la página
|
// Actualizamos el nombre mostrado en la página
|
||||||
$("#nombre").text(respuesta.nombreUsuario);
|
$("#nombre").text(respuesta.nombreUsuario);
|
||||||
|
|
||||||
|
// Limpiamos el input
|
||||||
$("#nuevoNombre").val("");
|
$("#nuevoNombre").val("");
|
||||||
|
|
||||||
|
|
||||||
if (typeof comprobarEstadoSesion === "function") {
|
|
||||||
comprobarEstadoSesion();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -83,11 +74,14 @@ $("#inputFoto").change(function () {
|
|||||||
// Comprobamos que sea una imagen
|
// Comprobamos que sea una imagen
|
||||||
if (!archivo.type.startsWith("image/")) {
|
if (!archivo.type.startsWith("image/")) {
|
||||||
alert("El archivo seleccionado no es una imagen.");
|
alert("El archivo seleccionado no es una imagen.");
|
||||||
|
|
||||||
$("#inputFoto").val("");
|
$("#inputFoto").val("");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let datos = new FormData();
|
let datos = new FormData();
|
||||||
|
|
||||||
datos.append("avatar", archivo);
|
datos.append("avatar", archivo);
|
||||||
datos.append("orden", "cambiarAvatar");
|
datos.append("orden", "cambiarAvatar");
|
||||||
|
|
||||||
@@ -103,23 +97,18 @@ $("#inputFoto").change(function () {
|
|||||||
if (respuesta.error) {
|
if (respuesta.error) {
|
||||||
alert(respuesta.error);
|
alert(respuesta.error);
|
||||||
} else {
|
} else {
|
||||||
// Actualizamos la imagen en la página de perfil sin recargar
|
// Actualizamos la imagen sin recargar la página
|
||||||
$("#fotoPerfil").attr(
|
$("#fotoPerfil").attr(
|
||||||
"src",
|
"src",
|
||||||
respuesta.avatar + "?t=" + new Date().getTime()
|
respuesta.avatar + "?t=" + new Date().getTime(),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Actualizamos también el avatar superior en la cabecera
|
|
||||||
if (typeof comprobarEstadoSesion === "function") {
|
|
||||||
comprobarEstadoSesion();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// RECOGER CATEGORIAS
|
// RECOGER CATEGORIAS
|
||||||
// =========================
|
// ====
|
||||||
|
|
||||||
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
$("#modalCrearPregunta").on("show.bs.modal", function () {
|
||||||
const selectCategoria = $("#idCategoria");
|
const selectCategoria = $("#idCategoria");
|
||||||
@@ -152,14 +141,16 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
|||||||
$("<option>", {
|
$("<option>", {
|
||||||
value: categoria.idCategoria,
|
value: categoria.idCategoria,
|
||||||
text: categoria.nombreCategoria,
|
text: categoria.nombreCategoria,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
error: function (xhr, status, error) {
|
error: function (xhr, status, error) {
|
||||||
console.error("Error al cargar las categorías:", error);
|
console.error("Error al cargar las categorías:", error);
|
||||||
|
|
||||||
console.error("Respuesta del servidor:", xhr.responseText);
|
console.error("Respuesta del servidor:", xhr.responseText);
|
||||||
|
|
||||||
alert("No se han podido cargar las categorías.");
|
alert("No se han podido cargar las categorías.");
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -167,7 +158,7 @@ $("#modalCrearPregunta").on("show.bs.modal", function () {
|
|||||||
|
|
||||||
// =========================
|
// =========================
|
||||||
// CREAR PREGUNTA
|
// CREAR PREGUNTA
|
||||||
// =========================
|
// ====
|
||||||
|
|
||||||
$("#formCrearPregunta").on("submit", function (e) {
|
$("#formCrearPregunta").on("submit", function (e) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -197,15 +188,24 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
|
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: "controladores/controladorPregunta.php",
|
url: "controladores/controladorPregunta.php",
|
||||||
|
|
||||||
type: "POST",
|
type: "POST",
|
||||||
|
|
||||||
dataType: "json",
|
dataType: "json",
|
||||||
|
|
||||||
data: {
|
data: {
|
||||||
orden: "crearPregunta",
|
orden: "crearPregunta",
|
||||||
|
|
||||||
idCategoria: $("#idCategoria").val(),
|
idCategoria: $("#idCategoria").val(),
|
||||||
|
|
||||||
nombrePregunta: pregunta,
|
nombrePregunta: pregunta,
|
||||||
|
|
||||||
respuestaCorrecta: respuestaCorrecta,
|
respuestaCorrecta: respuestaCorrecta,
|
||||||
|
|
||||||
respuestaIncorrecta1: respuestaIncorrecta1,
|
respuestaIncorrecta1: respuestaIncorrecta1,
|
||||||
|
|
||||||
respuestaIncorrecta2: respuestaIncorrecta2,
|
respuestaIncorrecta2: respuestaIncorrecta2,
|
||||||
|
|
||||||
respuestaIncorrecta3: respuestaIncorrecta3,
|
respuestaIncorrecta3: respuestaIncorrecta3,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -214,8 +214,10 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
|
|
||||||
if (respuesta.error) {
|
if (respuesta.error) {
|
||||||
alert(respuesta.error);
|
alert(respuesta.error);
|
||||||
|
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
boton.text("Crear pregunta");
|
boton.text("Crear pregunta");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,12 +233,17 @@ $("#formCrearPregunta").on("submit", function (e) {
|
|||||||
// Volvemos a activar el botón
|
// Volvemos a activar el botón
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
boton.text("Crear pregunta");
|
boton.text("Crear pregunta");
|
||||||
|
|
||||||
|
// Si tienes que actualizar la lista de preguntas:
|
||||||
|
// cargarPreguntas();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
error: function (xhr, status, error) {
|
error: function (xhr, status, error) {
|
||||||
console.error("Error al crear la pregunta:", error);
|
console.error("Error al crear la pregunta:", error);
|
||||||
|
|
||||||
console.error("Respuesta del servidor:", xhr.responseText);
|
console.error("Respuesta del servidor:", xhr.responseText);
|
||||||
|
|
||||||
alert("No se ha podido crear la pregunta.");
|
alert("No se ha podido crear la pregunta.");
|
||||||
|
|
||||||
boton.prop("disabled", false);
|
boton.prop("disabled", false);
|
||||||
|
|||||||
@@ -1,20 +1,3 @@
|
|||||||
<?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>
|
<!DOCTYPE html>
|
||||||
<html lang="es">
|
<html lang="es">
|
||||||
<head>
|
<head>
|
||||||
@@ -25,27 +8,39 @@ if (!$idPartida || $idPartida < 1) {
|
|||||||
<link rel="stylesheet" href="css/juego.css">
|
<link rel="stylesheet" href="css/juego.css">
|
||||||
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
<link rel="icon" type="image/svg+xml" href="img/favicon/favicon.svg">
|
||||||
</head>
|
</head>
|
||||||
<body data-id-partida="<?= (int)$idPartida ?>">
|
<body>
|
||||||
|
|
||||||
<!-- Progreso: "Pregunta 3 de 10" + barra -->
|
<!-- Contenedor de la Pregunta -->
|
||||||
<div class="game-header">
|
|
||||||
<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) -->
|
|
||||||
<div class="question-container">
|
<div class="question-container">
|
||||||
<div id="textoPregunta">Cargando preguntas…</div>
|
¿Cuál es el planeta más grande de nuestro sistema solar?
|
||||||
<div id="feedback" class="feedback" aria-live="polite"></div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Contenedor de Respuestas (Estilo Kahoot, lo rellena js/juego.js) -->
|
<!-- Contenedor de Respuestas (Estilo Kahoot) -->
|
||||||
<div class="answers-grid" id="respuestas"></div>
|
<div class="answers-grid">
|
||||||
|
<button class="btn-answer red" onclick="checkAnswer('Marte')">
|
||||||
|
<span class="shape triangle"></span>
|
||||||
|
Marte
|
||||||
|
</button>
|
||||||
|
|
||||||
<script src="js/jquery-4.0.0.min.js"></script>
|
<button class="btn-answer blue" onclick="checkAnswer('Júpiter')">
|
||||||
<script src="js/juego.js"></script>
|
<span class="shape diamond"></span>
|
||||||
|
Júpiter
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button class="btn-answer yellow" onclick="checkAnswer('Saturno')">
|
||||||
|
<span class="shape circle"></span>
|
||||||
|
Saturno
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button class="btn-answer green" onclick="checkAnswer('Tierra')">
|
||||||
|
<span class="shape square"></span>
|
||||||
|
Tierra
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -166,6 +166,9 @@ CREATE TABLE `partida` (
|
|||||||
`idPartida` int(11) NOT NULL AUTO_INCREMENT,
|
`idPartida` int(11) NOT NULL AUTO_INCREMENT,
|
||||||
`nombrePartida` varchar(100) NOT NULL,
|
`nombrePartida` varchar(100) NOT NULL,
|
||||||
`idUsuario` int(11) NOT NULL,
|
`idUsuario` int(11) NOT NULL,
|
||||||
|
`fechaCreacion` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
`fechaInicio` DATETIME NULL,
|
||||||
|
`fechaFin` DATETIME NULL,
|
||||||
PRIMARY KEY (`idPartida`),
|
PRIMARY KEY (`idPartida`),
|
||||||
KEY `FK idUsuario tabla usuario` (`idUsuario`),
|
KEY `FK idUsuario tabla usuario` (`idUsuario`),
|
||||||
CONSTRAINT `FK idUsuario tabla usuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`)
|
CONSTRAINT `FK idUsuario tabla usuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`)
|
||||||
@@ -178,10 +181,10 @@ CREATE TABLE `partida` (
|
|||||||
|
|
||||||
LOCK TABLES `partida` WRITE;
|
LOCK TABLES `partida` WRITE;
|
||||||
/*!40000 ALTER TABLE `partida` DISABLE KEYS */;
|
/*!40000 ALTER TABLE `partida` DISABLE KEYS */;
|
||||||
INSERT INTO `partida` VALUES
|
INSERT INTO `partida` (idPartida, nombrePartida, idUsuario, fechaInicio, fechaFin) VALUES
|
||||||
(1,'Partida de prueba 1',1),
|
(1,'Partida de prueba 1',1, NULL, NULL),
|
||||||
(2,'Partida de prueba 2',4),
|
(2,'Partida de prueba 2',4, NULL, NULL),
|
||||||
(3,'Partida de prueba 3',9);
|
(3,'Partida de prueba 3',9, NULL, NULL);
|
||||||
/*!40000 ALTER TABLE `partida` ENABLE KEYS */;
|
/*!40000 ALTER TABLE `partida` ENABLE KEYS */;
|
||||||
UNLOCK TABLES;
|
UNLOCK TABLES;
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user