From d751e6262cd1081274676a01f052698cbeebe3c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor?= Date: Fri, 25 Sep 2026 09:26:22 +0200 Subject: [PATCH] controlador y clase Partida --- clases/ClasePartida.php | 1232 +++++++++++++++++++++----- controladores/controladorPartida.php | 987 +++++++++++++++++++++ 2 files changed, 2008 insertions(+), 211 deletions(-) create mode 100644 controladores/controladorPartida.php diff --git a/clases/ClasePartida.php b/clases/ClasePartida.php index b681685..d509395 100644 --- a/clases/ClasePartida.php +++ b/clases/ClasePartida.php @@ -1,305 +1,366 @@ idPartida = $idPartida; $this->nombrePartida = $nombrePartida; $this->idUsuario = $idUsuario; + $this->estado = $estado; + $this->preguntaActual = $preguntaActual; } + + + public function insertar() { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { + $consulta = $conexion->prepare(" INSERT INTO partida - (nombrePartida,idUsuario) + ( + nombrePartida, + idUsuario, + estado, + preguntaActual + ) VALUES - (:nombrePartida,:idUsuario) + ( + :nombrePartida, + :idUsuario, + :estado, + :preguntaActual + ) "); - $consulta->bindParam(":nombrePartida", $this->nombrePartida); - $consulta->bindParam(":idUsuario", $this->idUsuario); + + $consulta->bindParam( + ":nombrePartida", + $this->nombrePartida + ); + + $consulta->bindParam( + ":idUsuario", + $this->idUsuario + ); + + $consulta->bindParam( + ":estado", + $this->estado + ); + + $consulta->bindParam( + ":preguntaActual", + $this->preguntaActual, + PDO::PARAM_INT + ); + $consulta->execute(); + return [ "exito" => "La partida se creó correctamente.", "exito_tecnico" => $conexion->lastInsertId() ]; + } catch (PDOException $error) { + return [ "error" => "Ocurrió un error al guardar la partida.", - 'error_tecnico' => $error->getMessage() + "error_tecnico" => $error->getMessage() ]; } } + + + public function listar() { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { - $consulta = $conexion->prepare("SELECT * FROM partida"); + + $consulta = $conexion->prepare(" + SELECT * + FROM partida + "); + $consulta->execute(); + return $consulta->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $error) { + return [ "error" => "Ocurrió un error al obtener el listado.", - 'error_tecnico' => $error->getMessage() + "error_tecnico" => $error->getMessage() ]; } } + + + public function buscar() { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { + $consulta = $conexion->prepare(" SELECT * FROM partida - WHERE idPartida=:idPartida + WHERE idPartida = :idPartida "); - $consulta->bindParam(":idPartida", $this->idPartida); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + $consulta->execute(); + return $consulta->fetch(PDO::FETCH_ASSOC); + } catch (PDOException $error) { + return [ "error" => "Ocurrió un error al buscar la partida.", - 'error_tecnico' => $error->getMessage() + "error_tecnico" => $error->getMessage() ]; } } + + + public function editar() { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { + $consulta = $conexion->prepare(" UPDATE partida SET - nombrePartida=:nombrePartida, - idUsuario=:idUsuario - WHERE idPartida=:idPartida + nombrePartida = :nombrePartida, + idUsuario = :idUsuario, + estado = :estado, + preguntaActual = :preguntaActual + WHERE idPartida = :idPartida "); - $consulta->bindParam(":idPartida", $this->idPartida); - $consulta->bindParam(":nombrePartida", $this->nombrePartida); - $consulta->bindParam(":idUsuario", $this->idUsuario); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->bindParam( + ":nombrePartida", + $this->nombrePartida + ); + + $consulta->bindParam( + ":idUsuario", + $this->idUsuario + ); + + $consulta->bindParam( + ":estado", + $this->estado + ); + + $consulta->bindParam( + ":preguntaActual", + $this->preguntaActual, + PDO::PARAM_INT + ); + $consulta->execute(); + return [ "exito" => "La partida se editó correctamente.", "exito_tecnico" => $this->idPartida ]; + } catch (PDOException $error) { + return [ "error" => "Ocurrió un error al editar la partida.", - 'error_tecnico' => $error->getMessage() + "error_tecnico" => $error->getMessage() ]; } } + + + public function eliminar() { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { + $consulta = $conexion->prepare(" DELETE FROM partida - WHERE idPartida=:idPartida + WHERE idPartida = :idPartida "); - $consulta->bindParam(":idPartida", $this->idPartida); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + $consulta->execute(); + return [ "exito" => "La partida se eliminó correctamente.", "exito_tecnico" => $this->idPartida ]; + } catch (PDOException $error) { + return [ "error" => "No se pudo eliminar la partida.", - 'error_tecnico' => $error->getMessage() + "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 + 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(); + return $consulta->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $error) { + return [ - "error" => "Ocurrió un error al recuperar las preguntas de la partida.", - 'error_tecnico' => $error->getMessage() + "error" => + "Ocurrió un error al recuperar las preguntas de la partida.", + "error_tecnico" => $error->getMessage() ]; } } - /** - * Asocia una pregunta ya existente a esta partida. - */ + + + public function asignarPregunta($idPregunta) { $conexion = conexionBD(); + if (is_array($conexion)) { return $conexion; } + try { + $consulta = $conexion->prepare(" INSERT INTO partidaxpregunta - (idPartida,idPregunta) + (idPartida, idPregunta) VALUES - (:idPartida,:idPregunta) + (:idPartida, :idPregunta) "); - $consulta->bindParam(":idPartida", $this->idPartida); - $consulta->bindParam(":idPregunta", $idPregunta); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->bindParam( + ":idPregunta", + $idPregunta + ); + $consulta->execute(); + return [ - "exito" => "La pregunta se asignó correctamente.", - "exito_tecnico" => $conexion->lastInsertId() + "exito" => + "La pregunta se asignó correctamente.", + "exito_tecnico" => + $conexion->lastInsertId() ]; + } catch (PDOException $error) { + return [ - "error" => "Ocurrió un error al asignar la pregunta.", - 'error_tecnico' => $error->getMessage() - ]; - } - } - //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() - { - $conexion = conexionBD(); - if (is_array($conexion)) { - return $conexion; - } - try { - $consulta = $conexion->prepare(" - SELECT COUNT(*) AS total - FROM partidaxpregunta - WHERE idPartida=:idPartida - "); - $consulta->bindParam(":idPartida", $this->idPartida); - $consulta->execute(); - $fila = $consulta->fetch(PDO::FETCH_ASSOC); - return (int)$fila["total"]; - } catch (PDOException $error) { - return [ - "error" => "Ocurrió un error al contar las preguntas.", - 'error_tecnico' => $error->getMessage() + "error" => + "Ocurrió un error al asignar la pregunta.", + "error_tecnico" => + $error->getMessage() ]; } } - public function contarRespuestasUsuario($idUsuario) - { - $conexion = conexionBD(); - if (is_array($conexion)) { - return $conexion; - } - try { - $consulta = $conexion->prepare(" - SELECT COUNT(*) AS total - 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(":idUsuario", $idUsuario); - $consulta->execute(); - $fila = $consulta->fetch(PDO::FETCH_ASSOC); - return (int)$fila["total"]; - } catch (PDOException $error) { - return [ - "error" => "Ocurrió un error al contar las respuestas del usuario.", - 'error_tecnico' => $error->getMessage() - ]; - } - } - /** - * Sustituye al antiguo campo `terminada`: compara cuántas preguntas - * tiene la partida contra cuántas ha respondido este usuario. - */ - public function estaFinalizadaParaUsuario($idUsuario) - { - $totalPreguntas = $this->contarPreguntasAsignadas(); - if (is_array($totalPreguntas)) { - return $totalPreguntas; - } - $totalRespondidas = $this->contarRespuestasUsuario($idUsuario); - if (is_array($totalRespondidas)) { - return $totalRespondidas; - } - return $totalPreguntas > 0 && $totalPreguntas === $totalRespondidas; - } - /** - * Partidas creadas por un usuario, de más reciente a más antigua. - */ - public function listarDelUsuario() - { - $conexion = conexionBD(); - if (is_array($conexion)) { - return $conexion; - } - try { - $consulta = $conexion->prepare(" - SELECT * - FROM partida - WHERE idUsuario=:idUsuario - ORDER BY idPartida DESC - "); - $consulta->bindParam(":idUsuario", $this->idUsuario); - $consulta->execute(); - return $consulta->fetchAll(PDO::FETCH_ASSOC); - } catch (PDOException $error) { - return [ - "error" => "Ocurrió un error al recuperar las partidas del usuario.", - 'error_tecnico' => $error->getMessage() - ]; - } - } public function preguntaAsignada($idPregunta) { @@ -310,117 +371,303 @@ class Partida } try { + $consulta = $conexion->prepare(" SELECT COUNT(*) AS total FROM partidaxpregunta - WHERE idPartida=:idPartida - AND idPregunta=:idPregunta + WHERE idPartida = :idPartida + AND idPregunta = :idPregunta "); - $consulta->bindParam(":idPartida", $this->idPartida); - $consulta->bindParam(":idPregunta", $idPregunta); + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->bindParam( + ":idPregunta", + $idPregunta + ); + $consulta->execute(); $fila = $consulta->fetch(PDO::FETCH_ASSOC); return (int)$fila["total"] > 0; + } catch (PDOException $error) { return [ - "error" => "Ocurrió un error al comprobar la pregunta.", - 'error_tecnico' => $error->getMessage() - ]; - } - } - /** - * Vincula un equipo a esta partida en la tabla intermedia 'equipoxpartida'. - * Permite registrar qué grupos están participando en este torneo. - */ - public function registrarEquipoEnPartida($idEquipo) { - $conexion = conexionBD(); // Obtenemos la conexión modular del proyecto - - if (is_array($conexion)) { - return $conexion; // Si hay error en la conexión, lo devuelve - } - - 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) - "); - - // Vinculamos los parámetros con el objeto de la partida actual y el equipo recibido - $consulta->bindParam(":idPartida", $this->idPartida); - $consulta->bindParam(":idEquipo", $idEquipo); - $consulta->execute(); - - return [ - "exito" => "El equipo se vinculó a la partida correctamente.", - "exito_tecnico" => $conexion->lastInsertId() - ]; - } catch (PDOException $error) { - // Capturamos el error extrayendo solo el mensaje de texto limpio - return [ - "error" => "Ocurrió un error al asignar el equipo a la partida.", - "error_tecnico" => $error->getMessage() + "error" => + "Ocurrió un error al comprobar la pregunta.", + "error_tecnico" => + $error->getMessage() ]; } } - /** - * Obtiene todos los equipos que están compitiendo en esta partida. - * Es útil para mostrar la lista de rivales antes de empezar a responder. - */ - public function getEquiposParticipantes() { + + + + public function contarPreguntasAsignadas() + { $conexion = conexionBD(); - + if (is_array($conexion)) { return $conexion; } - + try { - // Hacemos un INNER JOIN para traer los nombres de los equipos desde la tabla intermedia + $consulta = $conexion->prepare(" - SELECT + SELECT COUNT(*) AS total + FROM partidaxpregunta + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + $fila = $consulta->fetch(PDO::FETCH_ASSOC); + + return (int)$fila["total"]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al contar las preguntas.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function listarDelUsuario() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + SELECT * + FROM partida + WHERE idUsuario = :idUsuario + ORDER BY idPartida DESC + "); + + $consulta->bindParam( + ":idUsuario", + $this->idUsuario + ); + + $consulta->execute(); + + return $consulta->fetchAll(PDO::FETCH_ASSOC); + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al recuperar las partidas del usuario.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + public function contarRespuestasUsuario($idUsuario) + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + SELECT COUNT(*) AS total + 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( + ":idUsuario", + $idUsuario + ); + + $consulta->execute(); + + $fila = $consulta->fetch(PDO::FETCH_ASSOC); + + return (int)$fila["total"]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al contar las respuestas del usuario.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function estaFinalizadaParaUsuario($idUsuario) + { + $totalPreguntas = + $this->contarPreguntasAsignadas(); + + if (is_array($totalPreguntas)) { + return $totalPreguntas; + } + + $totalRespondidas = + $this->contarRespuestasUsuario($idUsuario); + + if (is_array($totalRespondidas)) { + return $totalRespondidas; + } + + return + $totalPreguntas > 0 && + $totalPreguntas === $totalRespondidas; + } + + + + + public function registrarEquipoEnPartida($idEquipo) + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + INSERT INTO equipoxpartida + (idPartida, idEquipo) + VALUES + (:idPartida, :idEquipo) + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->bindParam( + ":idEquipo", + $idEquipo + ); + + $consulta->execute(); + + return [ + "exito" => + "El equipo se vinculó a la partida correctamente.", + "exito_tecnico" => + $conexion->lastInsertId() + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al asignar el equipo a la partida.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function getEquiposParticipantes() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + SELECT exp.idEquipoxPartida, e.idEquipo, e.nombreEquipo FROM equipoxpartida exp - INNER JOIN equipo e + 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(); - - return $consulta->fetchAll(PDO::FETCH_ASSOC); // Devuelve el array con los equipos rivales + + return $consulta->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $error) { + return [ - "error" => "Ocurrió un error al recuperar los equipos de la partida.", - "error_tecnico" => $error->getMessage() + "error" => + "Ocurrió un error al recuperar los equipos de la partida.", + "error_tecnico" => + $error->getMessage() ]; } } - /** - * Obtiene todos los jugadores reales (Usuarios) que están jugando en esta partida. - * Utiliza la tabla 'equipoxusuario' en SQL para cruzar los datos. - */ - public function getJugadoresDeLaPartida() { + + + + public function getJugadoresDeLaPartida() + { $conexion = conexionBD(); - + if (is_array($conexion)) { return $conexion; } - + try { - // Cruza la partida con los equipos, y luego los equipos con los usuarios - // para saber los nombres de todas las personas que están jugando el torneo. + $consulta = $conexion->prepare(" SELECT DISTINCT u.idUsuario, @@ -428,25 +675,588 @@ class Partida u.email, e.nombreEquipo FROM equipoxpartida exp - INNER JOIN equipoxusuario exu + INNER JOIN equipoxusuario exu ON exp.idEquipo = exu.idEquipo - INNER JOIN usuario u + INNER JOIN usuario u ON exu.idUsuario = u.idUsuario - INNER JOIN equipo e + INNER JOIN equipo e ON exu.idEquipo = e.idEquipo WHERE exp.idPartida = :idPartida "); - - $consulta->bindParam(":idPartida", $this->idPartida); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + $consulta->execute(); - + return $consulta->fetchAll(PDO::FETCH_ASSOC); + } catch (PDOException $error) { + return [ - "error" => "Ocurrió un error al obtener la lista de jugadores.", - "error_tecnico" => $error->getMessage() + "error" => + "Ocurrió un error al obtener la lista de jugadores.", + "error_tecnico" => + $error->getMessage() ]; } } + + + + public function iniciar() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + // Comprobamos el estado actual. + + $consulta = $conexion->prepare(" + SELECT estado + FROM partida + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + $partida = $consulta->fetch(PDO::FETCH_ASSOC); + + if (!$partida) { + return [ + "error" => "La partida no existe." + ]; + } + + + // Solo podemos iniciar una partida + // que esté esperando. + + if ($partida['estado'] !== 'esperando') { + return [ + "error" => + "La partida ya ha sido iniciada o finalizada." + ]; + } + + + // Comprobamos que tenga preguntas. + + $numeroPreguntas = + $this->contarPreguntasAsignadas(); + + if (is_array($numeroPreguntas)) { + return $numeroPreguntas; + } + + if ($numeroPreguntas <= 0) { + return [ + "error" => + "No se puede iniciar una partida sin preguntas." + ]; + } + + + // Ponemos la partida en estado "jugando" + // y empezamos por la primera pregunta. + + $consulta = $conexion->prepare(" + UPDATE partida + SET + estado = 'jugando', + preguntaActual = 1 + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + return [ + "exito" => + "La partida se ha iniciado correctamente.", + "idPartida" => + $this->idPartida, + "preguntaActual" => + 1 + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al iniciar la partida.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function getPreguntaActual() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + SELECT + preguntaActual, + estado + FROM partida + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + $datosPartida = + $consulta->fetch(PDO::FETCH_ASSOC); + + if (!$datosPartida) { + return [ + "error" => "La partida no existe." + ]; + } + + + if ($datosPartida['estado'] === 'esperando') { + return [ + "estado" => "esperando", + "pregunta" => null + ]; + } + + + if ($datosPartida['estado'] === 'finalizada') { + return [ + "estado" => "finalizada", + "pregunta" => null + ]; + } + + + $numeroPregunta = + (int)$datosPartida['preguntaActual']; + + + $consulta = $conexion->prepare(" + SELECT + pxp.idPartidaxPregunta, + pxp.idPregunta, + p.* + FROM partidaxpregunta pxp + INNER JOIN pregunta p + ON pxp.idPregunta = p.idPregunta + WHERE pxp.idPartida = :idPartida + ORDER BY pxp.idPartidaxPregunta + LIMIT 1 OFFSET :offset + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + // SQL empieza a contar desde 0, + // mientras que preguntaActual empieza desde 1. + + $offset = $numeroPregunta - 1; + + $consulta->bindValue( + ":offset", + $offset, + PDO::PARAM_INT + ); + + $consulta->execute(); + + $pregunta = + $consulta->fetch(PDO::FETCH_ASSOC); + + if (!$pregunta) { + return [ + "error" => + "No se ha encontrado la pregunta actual." + ]; + } + + return [ + "estado" => "jugando", + "numeroPregunta" => $numeroPregunta, + "pregunta" => $pregunta + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al obtener la pregunta actual.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function siguientePregunta() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + SELECT + estado, + preguntaActual + FROM partida + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + $datos = + $consulta->fetch(PDO::FETCH_ASSOC); + + if (!$datos) { + return [ + "error" => "La partida no existe." + ]; + } + + if ($datos['estado'] !== 'jugando') { + return [ + "error" => + "La partida no está actualmente en juego." + ]; + } + + + $totalPreguntas = + $this->contarPreguntasAsignadas(); + + if (is_array($totalPreguntas)) { + return $totalPreguntas; + } + + + $siguiente = + (int)$datos['preguntaActual'] + 1; + + + if ($siguiente > $totalPreguntas) { + + $consulta = $conexion->prepare(" + UPDATE partida + SET + estado = 'finalizada' + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + return [ + "exito" => + "La partida ha finalizado.", + "estado" => + "finalizada" + ]; + } + + + $consulta = $conexion->prepare(" + UPDATE partida + SET + preguntaActual = :preguntaActual + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":preguntaActual", + $siguiente, + PDO::PARAM_INT + ); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + return [ + "exito" => + "Se ha avanzado a la siguiente pregunta.", + "preguntaActual" => + $siguiente + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al pasar a la siguiente pregunta.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function registrarRespuesta( + $idUsuario, + $idPregunta, + $idRespuesta + ) { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + // Comprobamos que la pregunta pertenezca + // a esta partida. + + $consulta = $conexion->prepare(" + SELECT idPartidaxPregunta + FROM partidaxpregunta + WHERE idPartida = :idPartida + AND idPregunta = :idPregunta + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->bindParam( + ":idPregunta", + $idPregunta + ); + + $consulta->execute(); + + $pregunta = + $consulta->fetch(PDO::FETCH_ASSOC); + + if (!$pregunta) { + return [ + "error" => + "La pregunta no pertenece a esta partida." + ]; + } + + $idPartidaxPregunta = + $pregunta['idPartidaxPregunta']; + + + // Comprobamos si el usuario ya ha respondido. + + $consulta = $conexion->prepare(" + SELECT idRespuestaAlmacenada + FROM respuestaalmacenada + WHERE idPartidaxPregunta = + :idPartidaxPregunta + AND idUsuario = :idUsuario + "); + + $consulta->bindParam( + ":idPartidaxPregunta", + $idPartidaxPregunta + ); + + $consulta->bindParam( + ":idUsuario", + $idUsuario + ); + + $consulta->execute(); + + $respuestaExistente = + $consulta->fetch(PDO::FETCH_ASSOC); + + if ($respuestaExistente) { + return [ + "error" => + "Ya has respondido esta pregunta." + ]; + } + + + // Comprobamos si existe ya alguien que haya + // respondido primero. + + $consulta = $conexion->prepare(" + SELECT COUNT(*) AS total + FROM respuestaalmacenada + WHERE idPartidaxPregunta = + :idPartidaxPregunta + AND primero = 1 + "); + + $consulta->bindParam( + ":idPartidaxPregunta", + $idPartidaxPregunta + ); + + $consulta->execute(); + + $fila = + $consulta->fetch(PDO::FETCH_ASSOC); + + $primero = + ((int)$fila['total'] === 0) ? 1 : 0; + + + // Guardamos la respuesta. + + $consulta = $conexion->prepare(" + INSERT INTO respuestaalmacenada + ( + idPartidaxPregunta, + idUsuario, + idRespuesta, + primero + ) + VALUES + ( + :idPartidaxPregunta, + :idUsuario, + :idRespuesta, + :primero + ) + "); + + $consulta->bindParam( + ":idPartidaxPregunta", + $idPartidaxPregunta + ); + + $consulta->bindParam( + ":idUsuario", + $idUsuario + ); + + $consulta->bindParam( + ":idRespuesta", + $idRespuesta + ); + + $consulta->bindParam( + ":primero", + $primero + ); + + $consulta->execute(); + + return [ + "exito" => + "La respuesta se ha registrado correctamente.", + "primero" => + $primero == 1 + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al registrar la respuesta.", + "error_tecnico" => + $error->getMessage() + ]; + } + } + + + + + public function finalizar() + { + $conexion = conexionBD(); + + if (is_array($conexion)) { + return $conexion; + } + + try { + + $consulta = $conexion->prepare(" + UPDATE partida + SET + estado = 'finalizada' + WHERE idPartida = :idPartida + "); + + $consulta->bindParam( + ":idPartida", + $this->idPartida + ); + + $consulta->execute(); + + return [ + "exito" => + "La partida ha finalizado correctamente.", + "estado" => + "finalizada" + ]; + + } catch (PDOException $error) { + + return [ + "error" => + "Ocurrió un error al finalizar la partida.", + "error_tecnico" => + $error->getMessage() + ]; + } + } } + +?> + diff --git a/controladores/controladorPartida.php b/controladores/controladorPartida.php new file mode 100644 index 0000000..3cb1559 --- /dev/null +++ b/controladores/controladorPartida.php @@ -0,0 +1,987 @@ + +listar(); + + echo json_encode($listadoPartidas); + + break; + + + + + case 'buscar': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + $partida = new Partida(); + + $partida->idPartida = intval($_POST['idPartida']); + + $resultado = $partida->buscar(); + + echo json_encode($resultado); + + break; + + + + + case 'crear': + + //Comprobamos que haya un usuario conectado + + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión para crear una partida.' + ]); + + break; + } + + + + //Comprobamos que se haya introducido un nombre + + + if ( + !isset($_POST['nombrePartida']) || + trim($_POST['nombrePartida']) === '' + ) { + + echo json_encode([ + 'error' => 'El nombre de la partida es obligatorio.' + ]); + + break; + } + + + + + //Creamos la partida + + + $partida = new Partida(); + + $partida->nombrePartida = trim($_POST['nombrePartida']); + + + //El usuario conectado será el propietario de la partida. + + $partida->idUsuario = $_SESSION['idUsuario']; + + + $resultado = $partida->insertar(); + + echo json_encode($resultado); + + break; + + + + + case 'editar': + + /* + |-------------------------------------------------------------- + | Usuario conectado + |-------------------------------------------------------------- + */ + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + + //Comprobamos los datos + + + if ( + !isset($_POST['idPartida']) || + !isset($_POST['nombrePartida']) + ) { + + echo json_encode([ + 'error' => 'Faltan datos para editar la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = intval($_POST['idPartida']); + + $partida->nombrePartida = trim($_POST['nombrePartida']); + + + + //Buscamos la partida + + + $datosPartida = $partida->buscar(); + + + if (!$datosPartida || isset($datosPartida['error'])) { + + echo json_encode([ + 'error' => 'La partida indicada no existe.' + ]); + + break; + } + + + + //Comprobamos que el usuario sea el propietario + + + if ( + $datosPartida['idUsuario'] != + $_SESSION['idUsuario'] + ) { + + echo json_encode([ + 'error' => 'No tienes permiso para editar esta partida.' + ]); + + break; + } + + + $partida->idUsuario = $datosPartida['idUsuario']; + + $resultado = $partida->editar(); + + echo json_encode($resultado); + + break; + + + + + case 'eliminar': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = intval($_POST['idPartida']); + + + + //Buscamos la partida + + + $datosPartida = $partida->buscar(); + + + if (!$datosPartida || isset($datosPartida['error'])) { + + echo json_encode([ + 'error' => 'La partida no existe.' + ]); + + break; + } + + + + //Solo el propietario puede eliminarla + + + if ( + $datosPartida['idUsuario'] != + $_SESSION['idUsuario'] + ) { + + echo json_encode([ + 'error' => 'No tienes permiso para eliminar esta partida.' + ]); + + break; + } + + + $resultado = $partida->eliminar(); + + echo json_encode($resultado); + + break; + + + + + case 'listarDelUsuario': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idUsuario = $_SESSION['idUsuario']; + + $resultado = $partida->listarDelUsuario(); + + echo json_encode($resultado); + + break; + + + + + case 'getPreguntas': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = intval($_POST['idPartida']); + + $resultado = $partida->getPreguntas(); + + echo json_encode($resultado); + + break; + + + + // ASIGNAR UNA PREGUNTA A UNA PARTIDA + + + case 'asignarPregunta': + + if ( + !isset($_POST['idPartida']) || + !isset($_POST['idPregunta']) + ) { + + echo json_encode([ + 'error' => 'Faltan datos.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = intval($_POST['idPartida']); + + $idPregunta = intval($_POST['idPregunta']); + + + + //Comprobamos que no esté ya asignada + + + if ($partida->preguntaAsignada($idPregunta)) { + + echo json_encode([ + 'error' => + 'La pregunta ya está asignada a esta partida.' + ]); + + break; + } + + + $resultado = + $partida->asignarPregunta($idPregunta); + + echo json_encode($resultado); + + break; + + + + // COMPROBAR SI UNA PREGUNTA ESTÁ ASIGNADA + + case 'preguntaAsignada': + + if ( + !isset($_POST['idPartida']) || + !isset($_POST['idPregunta']) + ) { + + echo json_encode([ + 'error' => 'Faltan datos.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->preguntaAsignada( + intval($_POST['idPregunta']) + ); + + + echo json_encode([ + 'asignada' => $resultado + ]); + + break; + + + + // CONTAR PREGUNTAS DE UNA PARTIDA + + + case 'contarPreguntas': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->contarPreguntasAsignadas(); + + + echo json_encode([ + 'totalPreguntas' => $resultado + ]); + + break; + + + + // REGISTRAR EQUIPO EN UNA PARTIDA + + + case 'registrarEquipo': + + if ( + !isset($_POST['idPartida']) || + !isset($_POST['idEquipo']) + ) { + + echo json_encode([ + 'error' => 'Faltan datos.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->registrarEquipoEnPartida( + intval($_POST['idEquipo']) + ); + + + echo json_encode($resultado); + + break; + + + + // OBTENER EQUIPOS DE UNA PARTIDA + + + case 'getEquipos': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->getEquiposParticipantes(); + + + echo json_encode($resultado); + + break; + + + + // OBTENER JUGADORES DE UNA PARTIDA + + + case 'getJugadores': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->getJugadoresDeLaPartida(); + + + echo json_encode($resultado); + + break; + + + + + case 'iniciar': + + /* + |-------------------------------------------------------------- + | Debe haber un usuario conectado + |-------------------------------------------------------------- + */ + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + + //Comprobamos que se haya indicado la partida + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + + //Buscamos la partida + + + $datosPartida = $partida->buscar(); + + + if (!$datosPartida || isset($datosPartida['error'])) { + + echo json_encode([ + 'error' => 'La partida no existe.' + ]); + + break; + } + + + + //Solo el creador puede iniciar la partida + + + if ( + $datosPartida['idUsuario'] != + $_SESSION['idUsuario'] + ) { + + echo json_encode([ + 'error' => + 'Solo el creador de la partida puede iniciarla.' + ]); + + break; + } + + + + //Comprobamos que haya preguntas + + + $numeroPreguntas = + $partida->contarPreguntasAsignadas(); + + + if ($numeroPreguntas <= 0) { + + echo json_encode([ + 'error' => + 'No puedes iniciar una partida sin preguntas.' + ]); + + break; + } + + + /* + + Iniciamos la partida + + + Este método deberá cambiar el estado de la partida + de "esperando" a "jugando". + + */ + + $resultado = $partida->iniciar(); + + + echo json_encode($resultado); + + break; + + + + // OBTENER LA PREGUNTA ACTUAL + + case 'getPreguntaActual': + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + + + //Obtenemos la pregunta actual + + $resultado = + $partida->getPreguntaActual(); + + + echo json_encode($resultado); + + break; + + + + + case 'siguientePregunta': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + + //Comprobamos que el usuario sea el creador + + $datosPartida = $partida->buscar(); + + + if (!$datosPartida || isset($datosPartida['error'])) { + + echo json_encode([ + 'error' => 'La partida no existe.' + ]); + + break; + } + + + if ( + $datosPartida['idUsuario'] != + $_SESSION['idUsuario'] + ) { + + echo json_encode([ + 'error' => + 'Solo el creador puede pasar a la siguiente pregunta.' + ]); + + break; + } + + + + //Pasamos a la siguiente pregunta + + + $resultado = + $partida->siguientePregunta(); + + + echo json_encode($resultado); + + break; + + + + // REGISTRAR RESPUESTA + + + case 'responder': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if ( + !isset($_POST['idPartida']) || + !isset($_POST['idPregunta']) || + !isset($_POST['idRespuesta']) + ) { + + echo json_encode([ + 'error' => 'Faltan datos para registrar la respuesta.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $idPregunta = + intval($_POST['idPregunta']); + + $idRespuesta = + intval($_POST['idRespuesta']); + + + + //Registramos la respuesta del usuario + + + $resultado = + $partida->registrarRespuesta( + $_SESSION['idUsuario'], + $idPregunta, + $idRespuesta + ); + + + echo json_encode($resultado); + + break; + + + + // COMPROBAR SI LA PARTIDA HA TERMINADO PARA EL USUARIO + + + case 'estaFinalizada': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->estaFinalizadaParaUsuario( + $_SESSION['idUsuario'] + ); + + + echo json_encode([ + 'finalizada' => $resultado + ]); + + break; + + + + // CONTAR RESPUESTAS DEL USUARIO + + + case 'contarRespuestas': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + $resultado = + $partida->contarRespuestasUsuario( + $_SESSION['idUsuario'] + ); + + + echo json_encode([ + 'totalRespondidas' => $resultado + ]); + + break; + + + + + case 'finalizar': + + if (!isset($_SESSION['idUsuario'])) { + + echo json_encode([ + 'error' => 'Debes iniciar sesión.' + ]); + + break; + } + + + if (!isset($_POST['idPartida'])) { + + echo json_encode([ + 'error' => 'No se ha indicado la partida.' + ]); + + break; + } + + + $partida = new Partida(); + + $partida->idPartida = + intval($_POST['idPartida']); + + + + //Buscamos la partida + + $datosPartida = $partida->buscar(); + + + if (!$datosPartida || isset($datosPartida['error'])) { + + echo json_encode([ + 'error' => 'La partida no existe.' + ]); + + break; + } + + + + //Solo el creador puede finalizarla + + if ( + $datosPartida['idUsuario'] != + $_SESSION['idUsuario'] + ) { + + echo json_encode([ + 'error' => + 'Solo el creador puede finalizar la partida.' + ]); + + break; + } + + + + + $resultado = + $partida->finalizar(); + + + echo json_encode($resultado); + + break; + + + + + default: + + echo json_encode([ + 'error' => 'La orden indicada no existe.' + ]); + + break; +} + +?> +