Compare commits

...

2 Commits

Author SHA1 Message Date
1f0184fde2 clang-tidy modernize 2025-07-20 12:51:24 +02:00
bfda842d3c clang-tidy 2025-07-20 12:16:25 +02:00
83 changed files with 1129 additions and 1128 deletions

View File

@@ -1,5 +1,6 @@
Checks: >
readability-identifier-naming
readability-identifier-naming,
modernize-*
WarningsAsErrors: '*'
# Solo incluir archivos de tu código fuente

View File

@@ -9,16 +9,16 @@
#include "utils.h" // Para getFileName
// Singleton
Asset *Asset::instance_ = nullptr;
Asset *Asset::instance = nullptr;
// Inicializa la instancia única del singleton
void Asset::init(const std::string &executable_path) { Asset::instance_ = new Asset(executable_path); }
void Asset::init(const std::string &executable_path) { Asset::instance = new Asset(executable_path); }
// Libera la instancia
void Asset::destroy() { delete Asset::instance_; }
void Asset::destroy() { delete Asset::instance; }
// Obtiene la instancia
auto Asset::get() -> Asset * { return Asset::instance_; }
auto Asset::get() -> Asset * { return Asset::instance; }
// Añade un elemento a la lista
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute) {

View File

@@ -41,8 +41,8 @@ class Asset { // Gestor de recursos (singleton)
AssetType type; // Tipo de recurso
bool required; // Indica si el fichero es obligatorio
AssetItem(std::string filePath, AssetType assetType, bool isRequired)
: file(std::move(filePath)), type(assetType), required(isRequired) {} // Constructor
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
: file(std::move(file_path)), type(asset_type), required(is_required) {} // Constructor
};
// --- Variables internas ---
@@ -60,5 +60,5 @@ class Asset { // Gestor de recursos (singleton)
~Asset() = default; // Destructor
// --- Singleton ---
static Asset *instance_; // Instancia singleton
static Asset *instance; // Instancia singleton
};

View File

@@ -9,16 +9,16 @@
#include "resource.h" // Para Resource
// Singleton
Audio *Audio::instance_ = nullptr;
Audio *Audio::instance = nullptr;
// Inicializa la instancia única del singleton
void Audio::init() { Audio::instance_ = new Audio(); }
void Audio::init() { Audio::instance = new Audio(); }
// Libera la instancia
void Audio::destroy() { delete Audio::instance_; }
void Audio::destroy() { delete Audio::instance; }
// Obtiene la instancia
auto Audio::get() -> Audio * { return Audio::instance_; }
auto Audio::get() -> Audio * { return Audio::instance; }
// Constructor
Audio::Audio() { initSDLAudio(); }

View File

@@ -90,5 +90,5 @@ class Audio {
~Audio(); // Destructor privado
// --- Singleton ---
static Audio *instance_;
static Audio *instance;
};

View File

@@ -321,7 +321,11 @@ void Background::createSunPath() {
constexpr float RADIUS = 120;
// Generar puntos de la curva desde 90 a 180 grados
for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01) {
constexpr double STEP = 0.01;
const int NUM_STEPS = static_cast<int>((M_PI - M_PI / 2) / STEP) + 1;
for (int i = 0; i < NUM_STEPS; ++i) {
double theta = M_PI / 2 + i * STEP;
float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
sun_path_.push_back({x, y});
@@ -342,7 +346,11 @@ void Background::createMoonPath() {
constexpr float RADIUS = 140;
// Generar puntos de la curva desde 0 a 90 grados
for (double theta = 0; theta <= M_PI / 2; theta += 0.01) {
constexpr double STEP = 0.01;
const int NUM_STEPS = static_cast<int>((M_PI / 2 - 0) / STEP) + 1;
for (int i = 0; i < NUM_STEPS; ++i) {
double theta = 0 + i * STEP;
float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
moon_path_.push_back({x, y});

View File

@@ -1,10 +1,10 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer
#include <stddef.h> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr
#include <vector> // Para vector
#include <cstddef> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr
#include <vector> // Para vector
#include "utils.h" // Para Color

View File

@@ -319,8 +319,8 @@ void Balloon::shiftSprite() {
// Establece el nivel de zoom del sprite
void Balloon::zoomSprite() {
sprite_->setZoomW(bouncing_.zoomW);
sprite_->setZoomH(bouncing_.zoomH);
sprite_->setZoomW(bouncing_.zoom_w);
sprite_->setZoomH(bouncing_.zoom_h);
}
// Activa el efecto
@@ -341,8 +341,8 @@ void Balloon::disableBounce() {
void Balloon::updateBounce() {
if (bouncing_.enabled) {
const int INDEX = bouncing_.counter / bouncing_.speed;
bouncing_.zoomW = bouncing_.w[INDEX];
bouncing_.zoomH = bouncing_.h[INDEX];
bouncing_.zoom_w = bouncing_.w[INDEX];
bouncing_.zoom_h = bouncing_.h[INDEX];
zoomSprite();

View File

@@ -77,23 +77,23 @@ class Balloon {
void useNormalColor(); // Pone el color normal en el globo
// --- Getters ---
float getPosX() const { return x_; }
float getPosY() const { return y_; }
int getWidth() const { return w_; }
int getHeight() const { return h_; }
BalloonSize getSize() const { return size_; }
BalloonType getType() const { return type_; }
Uint16 getScore() const { return score_; }
Circle &getCollider() { return collider_; }
Uint8 getMenace() const { return isEnabled() ? menace_ : 0; }
Uint8 getPower() const { return power_; }
bool isStopped() const { return stopped_; }
bool isPowerBall() const { return type_ == BalloonType::POWERBALL; }
bool isInvulnerable() const { return invulnerable_; }
bool isBeingCreated() const { return being_created_; }
bool isEnabled() const { return enabled_; }
bool isUsingReversedColor() { return use_reversed_colors_; }
bool canBePopped() const { return !isBeingCreated(); }
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getWidth() const -> int { return w_; }
[[nodiscard]] auto getHeight() const -> int { return h_; }
[[nodiscard]] auto getSize() const -> BalloonSize { return size_; }
[[nodiscard]] auto getType() const -> BalloonType { return type_; }
[[nodiscard]] auto getScore() const -> Uint16 { return score_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; }
[[nodiscard]] auto getPower() const -> Uint8 { return power_; }
[[nodiscard]] auto isStopped() const -> bool { return stopped_; }
[[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
auto isUsingReversedColor() -> bool { return use_reversed_colors_; }
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
// --- Setters ---
void setVelY(float vel_y) { vy_ = vel_y; }
@@ -109,10 +109,10 @@ class Balloon {
bool enabled = false; // Si el efecto está activo
Uint8 counter = 0; // Contador para el efecto
Uint8 speed = 2; // Velocidad del efecto
float zoomW = 1.0f; // Zoom en anchura
float zoomH = 1.0f; // Zoom en altura
float despX = 0.0f; // Desplazamiento X antes de pintar
float despY = 0.0f; // Desplazamiento Y antes de pintar
float zoom_w = 1.0f; // Zoom en anchura
float zoom_h = 1.0f; // Zoom en altura
float desp_x = 0.0f; // Desplazamiento X antes de pintar
float desp_y = 0.0f; // Desplazamiento Y antes de pintar
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
@@ -120,10 +120,10 @@ class Balloon {
Bouncing() = default;
void reset() {
counter = 0;
zoomW = 1.0f;
zoomH = 1.0f;
despX = 0.0f;
despY = 0.0f;
zoom_w = 1.0f;
zoom_h = 1.0f;
desp_x = 0.0f;
desp_y = 0.0f;
}
} bouncing_;

View File

@@ -52,11 +52,11 @@ class BalloonFormations {
~BalloonFormations() = default;
// --- Getters ---
const BalloonFormationPool &getPool(int pool) { return balloon_formation_pool_.at(pool); }
const BalloonFormationUnit &getSet(int pool, int set) { return *balloon_formation_pool_.at(pool).at(set); }
const BalloonFormationUnit &getSet(int set) const { return balloon_formation_.at(set); }
auto getPool(int pool) -> const BalloonFormationPool & { return balloon_formation_pool_.at(pool); }
auto getSet(int pool, int set) -> const BalloonFormationUnit & { return *balloon_formation_pool_.at(pool).at(set); }
[[nodiscard]] auto getSet(int set) const -> const BalloonFormationUnit & { return balloon_formation_.at(set); }
private:
private:
// --- Datos ---
std::vector<BalloonFormationUnit> balloon_formation_; // Vector con todas las formaciones enemigas
std::vector<BalloonFormationPool> balloon_formation_pool_; // Conjuntos de formaciones enemigas

View File

@@ -1,8 +1,7 @@
#include "balloon_manager.h"
#include <stdlib.h> // Para rand
#include <algorithm> // Para remove_if
#include <cstdlib> // Para rand
#include <numeric> // Para accumulate
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX...
@@ -149,15 +148,15 @@ void BalloonManager::updateBalloonDeployCounter() {
}
// Indica si se puede crear una powerball
bool BalloonManager::canPowerBallBeCreated() { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
auto BalloonManager::canPowerBallBeCreated() -> bool { return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0); }
// Calcula el poder actual de los globos en pantalla
int BalloonManager::calculateScreenPower() {
auto BalloonManager::calculateScreenPower() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
}
// Crea un globo nuevo en el vector de globos
std::shared_ptr<Balloon> BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) {
auto BalloonManager::createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon> {
if (can_deploy_balloons_) {
const int INDEX = static_cast<int>(size);
balloons_.emplace_back(std::make_shared<Balloon>(x, y, type, size, velx, speed, creation_timer, play_area_, balloon_textures_.at(INDEX), balloon_animations_.at(INDEX)));
@@ -230,7 +229,7 @@ void BalloonManager::setBalloonSpeed(float speed) {
}
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
auto BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) -> int {
Stage::addPower(1);
int score = 0;
@@ -255,7 +254,7 @@ int BalloonManager::popBalloon(std::shared_ptr<Balloon> balloon) {
}
// Explosiona un globo. Lo destruye = no crea otros globos
int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
auto BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int {
int score = 0;
// Calcula la puntuación y el poder que generaria el globo en caso de romperlo a él y a sus hijos
@@ -288,7 +287,7 @@ int BalloonManager::destroyBalloon(std::shared_ptr<Balloon> &balloon) {
}
// Destruye todos los globos
int BalloonManager::destroyAllBalloons() {
auto BalloonManager::destroyAllBalloons() -> int {
int score = 0;
for (auto &balloon : balloons_) {
score += destroyBalloon(balloon);
@@ -344,7 +343,7 @@ void BalloonManager::createRandomBalloons() {
for (int i = 0; i < NUM_BALLOONS; ++i) {
const float X = param.game.game_area.rect.x + (rand() % static_cast<int>(param.game.game_area.rect.w)) - BALLOON_SIZE[3];
const int Y = param.game.game_area.rect.y + (rand() % 50);
const BalloonSize SIZE = static_cast<BalloonSize>(rand() % 4);
const auto SIZE = static_cast<BalloonSize>(rand() % 4);
const float VEL_X = (rand() % 2 == 0) ? BALLOON_VELX_POSITIVE : BALLOON_VELX_NEGATIVE;
const int CREATION_COUNTER = 0;
createBalloon(X, Y, BalloonType::BALLOON, SIZE, VEL_X, balloon_speed_, CREATION_COUNTER);
@@ -352,7 +351,7 @@ void BalloonManager::createRandomBalloons() {
}
// Obtiene el nivel de ameza actual generado por los globos
int BalloonManager::getMenace() {
auto BalloonManager::getMenace() -> int {
return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
}

View File

@@ -36,7 +36,7 @@ class BalloonManager {
void deploySet(int set, int y); // Crea una formación específica con coordenadas
// Creación de globos
std::shared_ptr<Balloon> createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer); // Crea un nuevo globo
auto createBalloon(float x, int y, BalloonType type, BalloonSize size, float velx, float speed, int creation_timer) -> std::shared_ptr<Balloon>; // Crea un nuevo globo
void createChildBalloon(const std::shared_ptr<Balloon> &balloon, const std::string &direction); // Crea un globo a partir de otro
void createPowerBall(); // Crea una PowerBall
void createTwoBigBalloons(); // Crea dos globos grandes
@@ -47,13 +47,13 @@ class BalloonManager {
void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base
void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos
void updateBalloonDeployCounter(); // Actualiza el contador de despliegue
bool canPowerBallBeCreated(); // Indica si se puede crear una PowerBall
int calculateScreenPower(); // Calcula el poder de los globos en pantalla
auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall
auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla
// Manipulación de globos existentes
int popBalloon(std::shared_ptr<Balloon> balloon); // Explosiona un globo, creando otros si aplica
int destroyBalloon(std::shared_ptr<Balloon> &balloon); // Explosiona un globo sin crear otros
int destroyAllBalloons(); // Destruye todos los globos
auto popBalloon(std::shared_ptr<Balloon> balloon) -> int; // Explosiona un globo, creando otros si aplica
auto destroyBalloon(std::shared_ptr<Balloon> &balloon) -> int; // Explosiona un globo sin crear otros
auto destroyAllBalloons() -> int; // Destruye todos los globos
void stopAllBalloons(); // Detiene el movimiento de los globos
void startAllBalloons(); // Reactiva el movimiento de los globos
@@ -72,12 +72,12 @@ class BalloonManager {
void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos
// Obtención de información
int getMenace(); // Obtiene el nivel de amenaza generado por los globos
float getBalloonSpeed() const { return balloon_speed_; }
Balloons &getBalloons() { return balloons_; }
int getNumBalloons() const { return balloons_.size(); }
auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos
[[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; }
auto getBalloons() -> Balloons & { return balloons_; }
[[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); }
private:
private:
Balloons balloons_; // Vector con los globos activos
std::unique_ptr<Explosions> explosions_; // Objeto para gestionar explosiones
std::unique_ptr<BalloonFormations> balloon_formations_; // Objeto para manejar formaciones enemigas

View File

@@ -13,8 +13,8 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
pos_y_(y),
bullet_type_(bullet_type),
owner_(owner) {
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT_
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT_
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT
: 0;
std::string powered_type = powered ? "powered_" : "normal_";
@@ -46,20 +46,20 @@ void Bullet::render() {
}
// Actualiza el estado del objeto
BulletMoveStatus Bullet::update() {
auto Bullet::update() -> BulletMoveStatus {
sprite_->update();
return move();
}
// Implementación del movimiento usando BulletMoveStatus
BulletMoveStatus Bullet::move() {
auto Bullet::move() -> BulletMoveStatus {
pos_x_ += vel_x_;
if (pos_x_ < param.game.play_area.rect.x - WIDTH || pos_x_ > param.game.play_area.rect.w) {
disable();
return BulletMoveStatus::OUT;
}
pos_y_ += VEL_Y_;
pos_y_ += VEL_Y;
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
disable();
return BulletMoveStatus::OUT;
@@ -71,7 +71,7 @@ BulletMoveStatus Bullet::move() {
return BulletMoveStatus::OK;
}
bool Bullet::isEnabled() const {
auto Bullet::isEnabled() const -> bool {
return bullet_type_ != BulletType::NONE;
}
@@ -79,11 +79,11 @@ void Bullet::disable() {
bullet_type_ = BulletType::NONE;
}
int Bullet::getOwner() const {
auto Bullet::getOwner() const -> int {
return owner_;
}
Circle &Bullet::getCollider() {
auto Bullet::getCollider() -> Circle& {
return collider_;
}

View File

@@ -34,35 +34,35 @@ class Bullet {
// Métodos principales
void render(); // Dibuja la bala en pantalla
BulletMoveStatus update(); // Actualiza el estado del objeto
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
// Estado de la bala
bool isEnabled() const; // Comprueba si está activa
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
void disable(); // Desactiva la bala
// Getters
int getOwner() const; // Devuelve el identificador del dueño
Circle &getCollider(); // Devuelve el círculo de colisión
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
auto getCollider() -> Circle &; // Devuelve el círculo de colisión
private:
private:
// Constantes
static constexpr float VEL_Y_ = -3.0f;
static constexpr float VEL_X_LEFT_ = -2.0f;
static constexpr float VEL_X_RIGHT_ = 2.0f;
static constexpr float VEL_Y = -3.0f;
static constexpr float VEL_X_LEFT = -2.0f;
static constexpr float VEL_X_RIGHT = 2.0f;
// Propiedades
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
// Propiedades
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
float pos_x_; // Posición en el eje X
float pos_y_; // Posición en el eje Y
float vel_x_; // Velocidad en el eje X
float pos_x_; // Posición en el eje X
float pos_y_; // Posición en el eje Y
float vel_x_; // Velocidad en el eje X
BulletType bullet_type_; // Tipo de bala
int owner_; // Identificador del dueño
Circle collider_; // Círculo de colisión
BulletType bullet_type_; // Tipo de bala
int owner_; // Identificador del dueño
Circle collider_; // Círculo de colisión
// Métodos internos
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
// Métodos internos
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado
};

View File

@@ -73,7 +73,7 @@ void DefineButtons::checkEvents(const SDL_Event &event) {
}
// Habilita el objeto
bool DefineButtons::enable(int index) {
auto DefineButtons::enable(int index) -> bool {
if (index < input_->getNumControllers()) {
enabled_ = true;
finished_ = false;
@@ -87,7 +87,7 @@ bool DefineButtons::enable(int index) {
}
// Comprueba si está habilitado
bool DefineButtons::isEnabled() const { return enabled_; }
auto DefineButtons::isEnabled() const -> bool { return enabled_; }
// Incrementa el indice de los botones
void DefineButtons::incIndexButton() {
@@ -109,7 +109,7 @@ void DefineButtons::saveBindingsToOptions() {
}
// Comprueba que un botón no esté ya asignado
bool DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) {
auto DefineButtons::checkButtonNotInUse(SDL_GamepadButton button) -> bool {
for (const auto &b : buttons_) {
if (b.button == button) {
return false;

View File

@@ -1,10 +1,11 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_Event, SDL_GamepadButtonEvent
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <utility>
#include <vector> // Para vector
// Declaraciones adelantadas
@@ -18,8 +19,8 @@ struct DefineButtonsButton {
InputAction input; // Acción asociada
SDL_GamepadButton button; // Botón del mando
DefineButtonsButton(const std::string &lbl, InputAction inp, SDL_GamepadButton btn)
: label(lbl), input(inp), button(btn) {}
DefineButtonsButton(std::string lbl, InputAction inp, SDL_GamepadButton btn)
: label(std::move(lbl)), input(inp), button(btn) {}
};
// Clase DefineButtons
@@ -30,10 +31,10 @@ class DefineButtons {
void render(); // Dibuja el objeto en pantalla
void checkEvents(const SDL_Event &event); // Procesa los eventos
bool enable(int index_controller); // Habilita la redefinición de botones
bool isEnabled() const; // Comprueba si está habilitado
auto enable(int index_controller) -> bool; // Habilita la redefinición de botones
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está habilitado
private:
private:
// Objetos
Input *input_ = nullptr; // Gestión de entrada
std::shared_ptr<Text> text_; // Renderizado de texto
@@ -52,7 +53,7 @@ class DefineButtons {
void doControllerButtonDown(const SDL_GamepadButtonEvent &event); // Procesa pulsaciones
void bindButtons(); // Asigna botones al sistema de entrada
void saveBindingsToOptions(); // Guarda configuraciones
bool checkButtonNotInUse(SDL_GamepadButton button); // Verifica uso de botones
auto checkButtonNotInUse(SDL_GamepadButton button) -> bool; // Verifica uso de botones
void clearButtons(); // Limpia asignaciones actuales
void checkEnd(); // Comprueba si ha finalizado
};

View File

@@ -2,12 +2,12 @@
#include "director.h"
#include <SDL3/SDL.h> // Para SDL_Scancode, SDL_GamepadButton
#include <errno.h> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <stdio.h> // Para printf, perror
#include <sys/stat.h> // Para mkdir, stat, S_IRWXU
#include <unistd.h> // Para getuid
#include <algorithm> // Para min
#include <cerrno> // Para errno, EEXIST, EACCES, ENAMETOOLONG
#include <cstdio> // Para printf, perror
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time
#include <memory> // Para make_unique, unique_ptr
@@ -596,7 +596,7 @@ void Director::reset() {
Section::name = Section::Name::LOGO;
}
int Director::run() {
auto Director::run() -> int {
// Bucle principal
while (Section::name != Section::Name::QUIT) {
switch (Section::name) {

View File

@@ -13,9 +13,9 @@ class Director {
~Director();
// --- Bucle principal ---
int run();
auto run() -> int;
private:
private:
// --- Variables internas ---
std::string executable_path_; // Ruta del ejecutable
std::string system_folder_; // Carpeta del sistema para almacenar datos
@@ -46,7 +46,7 @@ class Director {
void reset(); // Reinicia objetos y vuelve a la sección inicial
// --- Gestión de archivos de idioma ---
std::string getLangFile(Lang::Code code); // Obtiene un fichero de idioma según el código
auto getLangFile(Lang::Code code) -> std::string; // Obtiene un fichero de idioma según el código
// --- Apagado del sistema ---
void shutdownSystem(bool should_shutdown); // Apaga el sistema

View File

@@ -1,8 +1,7 @@
#include "enter_name.h"
#include <stddef.h> // Para size_t
#include <stdlib.h> // Para rand
#include <cstddef> // Para size_t
#include <cstdlib> // Para rand
#include <string_view> // Para basic_string_view, string_view
#include "utils.h" // Para trim
@@ -133,7 +132,7 @@ void EnterName::initCharacterIndex(const std::string &name) {
}
// Encuentra el indice de un caracter en "character_list_"
int EnterName::findIndex(char character) const {
auto EnterName::findIndex(char character) const -> int {
for (size_t i = 0; i < character_list_.size(); ++i) {
if (character == character_list_.at(i)) {
return i;
@@ -143,13 +142,13 @@ int EnterName::findIndex(char character) const {
}
// Devuelve un nombre al azar
std::string EnterName::getRandomName() {
auto EnterName::getRandomName() -> std::string {
static constexpr std::array<std::string_view, 8> NAMES = {
"BAL1", "TABE", "DOC", "MON", "SAM1", "JORDI", "JDES", "PEPE"};
return std::string(NAMES[rand() % NAMES.size()]);
}
// Obtiene el nombre final introducido
std::string EnterName::getFinalName() {
auto EnterName::getFinalName() -> std::string {
auto name = trim(name_.substr(0, position_));
if (name.empty()) {
name = getRandomName();

View File

@@ -1,9 +1,8 @@
#pragma once
#include <stddef.h> // Para size_t
#include <array> // Para array
#include <string> // Para string, basic_string
#include <array> // Para array
#include <cstddef> // Para size_t
#include <string> // Para string, basic_string
#include "utils.h" // Para trim
@@ -23,13 +22,13 @@ class EnterName {
void incIndex(); // Incrementa el índice del carácter en la lista
void decIndex(); // Decrementa el índice del carácter en la lista
std::string getFinalName(); // Obtiene el nombre final introducido
std::string getCurrentName() const { return trim(name_); } // Obtiene el nombre actual en proceso
auto getFinalName() -> std::string; // Obtiene el nombre final introducido
[[nodiscard]] auto getCurrentName() const -> std::string { return trim(name_); } // Obtiene el nombre actual en proceso
int getPosition() const { return position_; } // Posición actual del carácter editado
bool getPositionOverflow() const { return position_overflow_; } // Indica si la posición excede el límite
[[nodiscard]] auto getPosition() const -> int { return position_; } // Posición actual del carácter editado
[[nodiscard]] auto getPositionOverflow() const -> bool { return position_overflow_; } // Indica si la posición excede el límite
private:
private:
std::string character_list_; // Lista de caracteres permitidos
std::string name_; // Nombre en proceso
size_t position_ = 0; // Índice del carácter que se edita
@@ -38,6 +37,6 @@ class EnterName {
void updateNameFromCharacterIndex(); // Actualiza "name_" según "character_index_"
void initCharacterIndex(const std::string &name); // Inicializa índices desde el nombre
int findIndex(char character) const; // Busca el índice de un carácter en "character_list_"
static std::string getRandomName(); // Devuelve un nombre al azar
[[nodiscard]] auto findIndex(char character) const -> int; // Busca el índice de un carácter en "character_list_"
static auto getRandomName() -> std::string; // Devuelve un nombre al azar
};

View File

@@ -23,7 +23,7 @@ void Explosions::render() {
// Añade texturas al objeto
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation) {
textures_.emplace_back(ExplosionTexture(size, texture, animation));
textures_.emplace_back(size, texture, animation);
}
// Añade una explosión
@@ -45,7 +45,7 @@ void Explosions::freeExplosions() {
}
// Busca una textura a partir del tamaño
int Explosions::getIndexBySize(int size) {
auto Explosions::getIndexBySize(int size) -> int {
for (int i = 0; i < (int)textures_.size(); ++i) {
if (size == textures_[i].size) {
return i;

View File

@@ -2,6 +2,7 @@
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string
#include <utility>
#include <vector> // Para vector
#include "animated_sprite.h" // Para AnimatedSprite
@@ -15,7 +16,7 @@ struct ExplosionTexture {
std::vector<std::string> animation; // Animación para la textura
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
: size(sz), texture(tex), animation(anim) {}
: size(sz), texture(std::move(tex)), animation(anim) {}
};
// Clase Explosions
@@ -48,5 +49,5 @@ class Explosions {
void freeExplosions();
// Busca una textura a partir del tamaño
int getIndexBySize(int size);
auto getIndexBySize(int size) -> int;
};

1
source/external/.clang-tidy vendored Normal file
View File

@@ -0,0 +1 @@
Checks: '-*'

View File

@@ -6059,7 +6059,7 @@ inline void to_json(BasicJsonType& j, const std::pair<T1, T2>& p)
j = { p.first, p.second };
}
// Para https://github.com/nlohmann/json/pull/1134
// for https://github.com/nlohmann/json/pull/1134
template<typename BasicJsonType, typename T,
enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0>
inline void to_json(BasicJsonType& j, const T& b)
@@ -6624,7 +6624,7 @@ class iterator_input_adapter
return char_traits<char_type>::eof();
}
// Para general iterators, we cannot really do something better than falling back to processing the range one-by-one
// for general iterators, we cannot really do something better than falling back to processing the range one-by-one
template<class T>
std::size_t get_elements(T* dest, std::size_t count = 1)
{
@@ -14558,7 +14558,7 @@ class json_pointer
};
public:
// Para backwards compatibility accept BasicJsonType
// for backwards compatibility accept BasicJsonType
using string_t = typename string_t_helper<RefStringType>::type;
/// @brief create JSON pointer
@@ -18087,7 +18087,7 @@ inline cached_power get_cached_power_for_binary_exponent(int e)
// This computation gives exactly the same results for k as
// k = ceil((kAlpha - e - 1) * 0.30102999566398114)
// Para |e| <= 1500, but doesn't require floating-point operations.
// for |e| <= 1500, but doesn't require floating-point operations.
// NB: log_10(2) ~= 78913 / 2^18
JSON_ASSERT(e >= -1500);
JSON_ASSERT(e <= 1500);
@@ -19727,7 +19727,7 @@ NLOHMANN_JSON_NAMESPACE_END
#include <initializer_list> // initializer_list
#include <iterator> // input_iterator_tag, iterator_traits
#include <memory> // allocator
#include <stdexcept> // Para out_of_range
#include <stdexcept> // for out_of_range
#include <type_traits> // enable_if, is_convertible
#include <utility> // pair
#include <vector> // vector
@@ -19740,7 +19740,7 @@ NLOHMANN_JSON_NAMESPACE_END
NLOHMANN_JSON_NAMESPACE_BEGIN
/// ordered_map: a minimal map-like container that preserves insertion order
/// Para use within nlohmann::basic_json<ordered_map>
/// for use within nlohmann::basic_json<ordered_map>
template <class Key, class T, class IgnoredLess = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T>>>
struct ordered_map : std::vector<std::pair<const Key, T>, Allocator>

View File

@@ -1,9 +1,9 @@
#include "fade.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderT...
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para min, max
#include <cstdlib> // Para rand, size_t
#include "param.h" // Para Param, param, ParamGame, ParamFade
#include "screen.h" // Para Screen
@@ -312,7 +312,7 @@ void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
}
// Calcula el valor del estado del fade
int Fade::calculateValue(int min, int max, int current) {
auto Fade::calculateValue(int min, int max, int current) -> int {
if (current < min) {
return 0;
}

View File

@@ -50,11 +50,11 @@ class Fade {
void setPreDuration(int value) { pre_duration_ = value; }
// --- Getters ---
int getValue() const { return value_; }
bool isEnabled() const { return state_ != FadeState::NOT_ENABLED; }
bool hasEnded() const { return state_ == FadeState::FINISHED; }
[[nodiscard]] auto getValue() const -> int { return value_; }
[[nodiscard]] auto isEnabled() const -> bool { return state_ != FadeState::NOT_ENABLED; }
[[nodiscard]] auto hasEnded() const -> bool { return state_ == FadeState::FINISHED; }
private:
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // Renderizador de la ventana
SDL_Texture *backbuffer_; // Backbuffer para efectos
@@ -86,5 +86,5 @@ class Fade {
// --- Métodos internos ---
void init(); // Inicializa variables
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
int calculateValue(int min, int max, int current); // Calcula el valor del fade
auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
};

View File

@@ -219,12 +219,12 @@ void GameLogo::enable() {
}
// Indica si ha terminado la animación
bool GameLogo::hasFinished() const {
auto GameLogo::hasFinished() const -> bool {
return post_finished_counter_ == 0;
}
// Calcula el desplazamiento vertical inicial
int GameLogo::getInitialVerticalDesp() {
auto GameLogo::getInitialVerticalDesp() -> int {
const float OFFSET_UP = y_;
const float OFFSET_DOWN = param.game.height - y_;

View File

@@ -21,9 +21,9 @@ class GameLogo {
void enable(); // Activa la clase
// --- Getters ---
bool hasFinished() const; // Indica si ha terminado la animación
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado la animación
private:
private:
// --- Tipos internos ---
enum class Status {
DISABLED,
@@ -78,5 +78,5 @@ class GameLogo {
// --- Métodos internos ---
void init(); // Inicializa las variables
int getInitialVerticalDesp(); // Calcula el desplazamiento vertical inicial
auto getInitialVerticalDesp() -> int; // Calcula el desplazamiento vertical inicial
};

View File

@@ -65,7 +65,7 @@ void toggleShaders() {
}
// Obtiene una fichero a partir de un lang::Code
std::string getLangFile(Lang::Code code) {
auto getLangFile(Lang::Code code) -> std::string {
switch (code) {
case Lang::Code::VALENCIAN:
return Asset::get()->get("ba_BA.json");
@@ -80,7 +80,7 @@ std::string getLangFile(Lang::Code code) {
}
// Obtiene una cadena a partir de un lang::Code
std::string getLangName(Lang::Code code) {
auto getLangName(Lang::Code code) -> std::string {
switch (code) {
case Lang::Code::VALENCIAN:
return " \"ba_BA\"";
@@ -161,7 +161,7 @@ void incWindowSize() {
}
// Comprueba el boton de servicio
bool checkServiceButton() {
auto checkServiceButton() -> bool {
// Teclado
if (Input::get()->checkInput(InputAction::SERVICE, INPUT_DO_NOT_ALLOW_REPEAT, InputDevice::KEYBOARD)) {
toggleServiceMenu();
@@ -181,7 +181,7 @@ bool checkServiceButton() {
}
// Comprueba las entradas del menú de servicio
bool checkServiceInputs() {
auto checkServiceInputs() -> bool {
if (!ServiceMenu::get()->isEnabled())
return false;
@@ -268,7 +268,7 @@ bool checkServiceInputs() {
}
// Comprueba las entradas fuera del menú de servicio
bool checkInputs() {
auto checkInputs() -> bool {
// Teclado
{
// Comprueba el teclado para cambiar entre pantalla completa y ventana
@@ -361,7 +361,7 @@ bool checkInputs() {
}
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
bool check() {
auto check() -> bool {
if (checkServiceButton())
return true;
if (checkServiceInputs())

View File

@@ -2,5 +2,5 @@
namespace GlobalInputs {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
bool check();
auto check() -> bool;
} // namespace GlobalInputs

View File

@@ -1,28 +1,28 @@
#include "input.h"
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa...
#include <stddef.h> // Para size_t
#include <algorithm> // Para find
#include <cstddef> // Para size_t
#include <iterator> // Para distance
#include <unordered_map> // Para unordered_map, _Node_const_iterator, operat...
#include <utility> // Para pair
// Singleton
Input *Input::instance_ = nullptr;
Input *Input::instance = nullptr;
// Inicializa la instancia única del singleton
void Input::init(const std::string &game_controller_db_path) { Input::instance_ = new Input(game_controller_db_path); }
void Input::init(const std::string &game_controller_db_path) { Input::instance = new Input(game_controller_db_path); }
// Libera la instancia
void Input::destroy() { delete Input::instance_; }
void Input::destroy() { delete Input::instance; }
// Obtiene la instancia
Input *Input::get() { return Input::instance_; }
auto Input::get() -> Input * { return Input::instance; }
// Constructor
Input::Input(const std::string &game_controller_db_path)
: game_controller_db_path_(game_controller_db_path) {
Input::Input(std::string game_controller_db_path)
: game_controller_db_path_(std::move(game_controller_db_path)) {
// Inicializa el subsistema SDL_INIT_GAMEPAD
initSDLGamePad();
@@ -54,7 +54,7 @@ void Input::bindGameControllerButton(int controller_index, InputAction input_tar
}
// Comprueba si un input esta activo
bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) {
auto Input::checkInput(InputAction input, bool repeat, InputDevice device, int controller_index) -> bool {
bool success_keyboard = false;
bool success_controller = false;
const int INPUT_INDEX = static_cast<int>(input);
@@ -85,7 +85,7 @@ bool Input::checkInput(InputAction input, bool repeat, InputDevice device, int c
}
// Comprueba si hay almenos un input activo
bool Input::checkAnyInput(InputDevice device, int controller_index) {
auto Input::checkAnyInput(InputDevice device, int controller_index) -> bool {
// Obtenemos el número total de acciones posibles para iterar sobre ellas.
const int NUM_ACTIONS = static_cast<int>(InputAction::SIZE);
@@ -119,7 +119,7 @@ bool Input::checkAnyInput(InputDevice device, int controller_index) {
}
// Comprueba si hay algún botón pulsado. Devuelve 0 en caso de no encontrar nada o el indice del dispositivo + 1. Se hace así para poder gastar el valor devuelto como un valor "booleano"
int Input::checkAnyButton(bool repeat) {
auto Input::checkAnyButton(bool repeat) -> int {
// Solo comprueba los botones definidos previamente
for (auto bi : button_inputs_) {
// Comprueba el teclado
@@ -139,7 +139,7 @@ int Input::checkAnyButton(bool repeat) {
}
// Busca si hay mandos conectados
bool Input::discoverGameControllers() {
auto Input::discoverGameControllers() -> bool {
bool found = false;
if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
@@ -207,16 +207,16 @@ bool Input::discoverGameControllers() {
}
// Comprueba si hay algun mando conectado
bool Input::gameControllerFound() { return num_gamepads_ > 0 ? true : false; }
auto Input::gameControllerFound() -> bool { return num_gamepads_ > 0 ? true : false; }
// Obten el nombre de un mando de juego
std::string Input::getControllerName(int controller_index) const { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
// Obten el número de mandos conectados
int Input::getNumControllers() const { return num_gamepads_; }
auto Input::getNumControllers() const -> int { return num_gamepads_; }
// Obtiene el indice del controlador a partir de un event.id
int Input::getJoyIndex(SDL_JoystickID id) const {
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
for (int i = 0; i < num_joysticks_; ++i) {
if (SDL_GetJoystickID(joysticks_[i]) == id) {
return i;
@@ -247,18 +247,18 @@ void Input::printBindings(InputDevice device, int controller_index) const {
}
// Obtiene el SDL_GamepadButton asignado a un input
SDL_GamepadButton Input::getControllerBinding(int controller_index, InputAction input) const {
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
return controller_bindings_[controller_index][static_cast<int>(input)].button;
}
// Obtiene el indice a partir del nombre del mando
int Input::getIndexByName(const std::string &name) const {
auto Input::getIndexByName(const std::string &name) const -> int {
auto it = std::find(controller_names_.begin(), controller_names_.end(), name);
return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}
// Convierte un InputAction a std::string
std::string Input::inputToString(InputAction input) const {
auto Input::inputToString(InputAction input) const -> std::string {
switch (input) {
case InputAction::FIRE_LEFT:
return "input_fire_left";
@@ -276,7 +276,7 @@ std::string Input::inputToString(InputAction input) const {
}
// Convierte un std::string a InputAction
InputAction Input::stringToInput(const std::string &name) const {
auto Input::stringToInput(const std::string &name) const -> InputAction {
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
{"input_fire_left", InputAction::FIRE_LEFT},
{"input_fire_center", InputAction::FIRE_CENTER},
@@ -289,7 +289,7 @@ InputAction Input::stringToInput(const std::string &name) const {
}
// Comprueba el eje del mando
bool Input::checkAxisInput(InputAction input, int controller_index, bool repeat) {
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
// Umbral para considerar el eje como activo
bool axis_active_now = false;
@@ -362,12 +362,12 @@ void Input::update() {
// --- TECLADO ---
const bool *key_states = SDL_GetKeyboardState(nullptr);
for (size_t i = 0; i < key_bindings_.size(); ++i) {
bool key_is_down_now = key_states[key_bindings_[i].scancode];
for (auto &key_binding : key_bindings_) {
bool key_is_down_now = key_states[key_binding.scancode];
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
key_bindings_[i].just_pressed = key_is_down_now && !key_bindings_[i].is_held;
key_bindings_[i].is_held = key_is_down_now;
key_binding.just_pressed = key_is_down_now && !key_binding.is_held;
key_binding.is_held = key_is_down_now;
}
// --- MANDOS ---

View File

@@ -72,7 +72,7 @@ class Input {
// --- Métodos de singleton ---
static void init(const std::string &game_controller_db_path); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Input *get(); // Obtiene la instancia
static auto get() -> Input *; // Obtiene la instancia
// --- Métodos de configuración de controles ---
void bindKey(InputAction input, SDL_Scancode code); // Asigna inputs a teclas
@@ -81,23 +81,23 @@ class Input {
// --- Métodos de consulta de entrada ---
void update(); // Comprueba fisicamente los botones y teclas que se han pulsado
bool checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si un input está activo
bool checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0); // Comprueba si hay al menos un input activo
int checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT); // Comprueba si hay algún botón pulsado
auto checkInput(InputAction input, bool repeat = true, InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si un input está activo
auto checkAnyInput(InputDevice device = InputDevice::ANY, int controller_index = 0) -> bool; // Comprueba si hay al menos un input activo
auto checkAnyButton(bool repeat = INPUT_DO_NOT_ALLOW_REPEAT) -> int; // Comprueba si hay algún botón pulsado
// --- Métodos de gestión de mandos ---
bool discoverGameControllers(); // Busca si hay mandos conectados
bool gameControllerFound(); // Comprueba si hay algún mando conectado
int getNumControllers() const; // Obtiene el número de mandos conectados
std::string getControllerName(int controller_index) const; // Obtiene el nombre de un mando de juego
int getJoyIndex(SDL_JoystickID id) const; // Obtiene el índice del controlador a partir de un event.id
auto discoverGameControllers() -> bool; // Busca si hay mandos conectados
auto gameControllerFound() -> bool; // Comprueba si hay algún mando conectado
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string; // Obtiene el nombre de un mando de juego
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
// --- Métodos de consulta y utilidades ---
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
SDL_GamepadButton getControllerBinding(int controller_index, InputAction input) const; // Obtiene el SDL_GamepadButton asignado a un input
std::string inputToString(InputAction input) const; // Convierte un InputAction a std::string
InputAction stringToInput(const std::string &name) const; // Convierte un std::string a InputAction
int getIndexByName(const std::string &name) const; // Obtiene el índice a partir del nombre del mando
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] auto inputToString(InputAction input) const -> std::string; // Convierte un InputAction a std::string
[[nodiscard]] auto stringToInput(const std::string &name) const -> InputAction; // Convierte un std::string a InputAction
[[nodiscard]] auto getIndexByName(const std::string &name) const -> int; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada ---
void resetInputStates(); // Pone todos los KeyBindings.active y ControllerBindings.active a false
@@ -139,12 +139,12 @@ class Input {
// --- Métodos internos ---
void initSDLGamePad(); // Inicializa SDL para la gestión de mandos
bool checkAxisInput(InputAction input, int controller_index, bool repeat); // Comprueba el eje del mando
auto checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool; // Comprueba el eje del mando
// --- Constructor y destructor ---
explicit Input(const std::string &game_controller_db_path); // Constructor privado
explicit Input(std::string game_controller_db_path); // Constructor privado
~Input() = default; // Destructor privado
// --- Singleton ---
static Input *instance_;
static Input *instance;
};

View File

@@ -1,8 +1,7 @@
#include "item.h"
#include <stdlib.h> // Para rand
#include <algorithm> // Para clamp
#include <cstdlib> // Para rand
#include "animated_sprite.h" // Para AnimatedSprite
#include "param.h" // Para Param, ParamGame, param
@@ -161,7 +160,7 @@ void Item::shiftSprite() {
}
// Calcula la zona de aparición de la máquina de café
int Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) {
auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin) -> int {
// Distancia mínima del jugador (ajusta según necesites)
const int MIN_DISTANCE_FROM_PLAYER = area_width / 2;

View File

@@ -54,16 +54,16 @@ class Item {
void update();
// Getters
float getPosX() const { return pos_x_; }
float getPosY() const { return pos_y_; }
int getWidth() const { return width_; }
int getHeight() const { return height_; }
ItemType getType() const { return type_; }
bool isEnabled() const { return enabled_; }
bool isOnFloor() const { return floor_collision_; }
Circle &getCollider() { return collider_; }
[[nodiscard]] auto getPosX() const -> float { return pos_x_; }
[[nodiscard]] auto getPosY() const -> float { return pos_y_; }
[[nodiscard]] auto getWidth() const -> int { return width_; }
[[nodiscard]] auto getHeight() const -> int { return height_; }
[[nodiscard]] auto getType() const -> ItemType { return type_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto isOnFloor() const -> bool { return floor_collision_; }
auto getCollider() -> Circle & { return collider_; }
private:
private:
// Objetos y punteros
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos del objeto
@@ -100,5 +100,5 @@ class Item {
void updateTimeToLive();
// Calcula la zona de aparición de la máquina de café
int getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2);
auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
};

View File

@@ -1,7 +1,6 @@
#include "lang.h"
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <exception> // Para exception
#include <fstream> // Para basic_ifstream, basic_istream, ifstream
#include <unordered_map> // Para unordered_map, _Node_iterator, operator==
@@ -24,7 +23,7 @@ std::vector<Language> languages = {
{Code::ENGLISH, "Ingles", "en_UK.json"}};
// Inicializa los textos del juego en el idioma seleccionado
bool loadFromFile(const std::string &file_path) {
auto loadFromFile(const std::string &file_path) -> bool {
texts.clear();
std::ifstream rfile(file_path);
@@ -47,7 +46,7 @@ bool loadFromFile(const std::string &file_path) {
}
// Obtiene el texto por clave
std::string getText(const std::string &key) {
auto getText(const std::string &key) -> std::string {
auto it = texts.find(key);
if (it != texts.end())
return it->second;
@@ -56,7 +55,7 @@ std::string getText(const std::string &key) {
}
// Obtiene el código del siguiente idioma disponible
Code getNextLangCode(Code lang) {
auto getNextLangCode(Code lang) -> Code {
for (size_t i = 0; i < languages.size(); ++i) {
if (languages[i].code == lang) {
return languages[(i + 1) % languages.size()].code;
@@ -67,7 +66,7 @@ Code getNextLangCode(Code lang) {
}
// Obtiene un idioma del vector de idiomas a partir de un código
Language getLanguage(Code code) {
auto getLanguage(Code code) -> Language {
for (const auto &lang : languages) {
if (lang.code == code)
return lang;
@@ -77,7 +76,7 @@ Language getLanguage(Code code) {
}
// Devuelve el código de un idioma a partir de un nombre
Code getCodeFromName(const std::string &name) {
auto getCodeFromName(const std::string &name) -> Code {
for (const auto &lang : languages) {
if (lang.name == name)
return lang.code;
@@ -87,7 +86,7 @@ Code getCodeFromName(const std::string &name) {
}
// Devuelve el nombre de un idioma a partir de un código
std::string getNameFromCode(Code code) {
auto getNameFromCode(Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
return lang.name;
@@ -137,7 +136,7 @@ void updateDifficultyNames() {
}
// Obtiene una fichero a partir de un lang::Code
std::string getLanguageFileName(Lang::Code code) {
auto getLanguageFileName(Lang::Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
return Asset::get()->get(lang.file_name);

View File

@@ -11,7 +11,7 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
#include "director.h" // Para Director
int main(int argc, char *argv[]) {
auto main(int argc, char *argv[]) -> int {
// Crea el objeto Director
auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));

View File

@@ -13,22 +13,22 @@ void ManageHiScoreTable::clear() {
table_.clear();
// Añade 10 entradas predefinidas
table_.push_back(HiScoreEntry("BRY", 1000000));
table_.push_back(HiScoreEntry("USUFO", 500000));
table_.push_back(HiScoreEntry("GLUCA", 100000));
table_.push_back(HiScoreEntry("PARRA", 50000));
table_.push_back(HiScoreEntry("CAGAM", 10000));
table_.push_back(HiScoreEntry("PEPE", 5000));
table_.push_back(HiScoreEntry("ROSIT", 1000));
table_.push_back(HiScoreEntry("SAM", 500));
table_.push_back(HiScoreEntry("PACMQ", 200));
table_.push_back(HiScoreEntry("PELEC", 100));
table_.emplace_back("BRY", 1000000);
table_.emplace_back("USUFO", 500000);
table_.emplace_back("GLUCA", 100000);
table_.emplace_back("PARRA", 50000);
table_.emplace_back("CAGAM", 10000);
table_.emplace_back("PEPE", 5000);
table_.emplace_back("ROSIT", 1000);
table_.emplace_back("SAM", 500);
table_.emplace_back("PACMQ", 200);
table_.emplace_back("PELEC", 100);
sort();
}
// Añade un elemento a la tabla
int ManageHiScoreTable::add(const HiScoreEntry &entry) {
auto ManageHiScoreTable::add(const HiScoreEntry &entry) -> int {
// Añade la entrada a la tabla
table_.push_back(entry);
@@ -63,14 +63,14 @@ int ManageHiScoreTable::add(const HiScoreEntry &entry) {
void ManageHiScoreTable::sort() {
struct
{
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
auto operator()(const HiScoreEntry &a, const HiScoreEntry &b) const -> bool { return a.score > b.score; }
} score_descending_comparator;
std::sort(table_.begin(), table_.end(), score_descending_comparator);
}
// Carga la tabla desde un fichero
bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
clear();
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "rb");
@@ -117,7 +117,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) {
}
// Guarda la tabla en un fichero
bool ManageHiScoreTable::saveToFile(const std::string &file_path) {
auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");

View File

@@ -36,15 +36,15 @@ class ManageHiScoreTable {
void clear();
// Añade un elemento a la tabla (devuelve la posición en la que se inserta)
int add(const HiScoreEntry &entry);
auto add(const HiScoreEntry &entry) -> int;
// Carga la tabla con los datos de un fichero
bool loadFromFile(const std::string &file_path);
auto loadFromFile(const std::string &file_path) -> bool;
// Guarda la tabla en un fichero
bool saveToFile(const std::string &file_path);
auto saveToFile(const std::string &file_path) -> bool;
private:
private:
// Referencia a la tabla con los records
std::vector<HiScoreEntry> &table_;

View File

@@ -23,8 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture),
x_(0.0f),
y_(0.0f),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),

View File

@@ -4,7 +4,8 @@
#include <algorithm> // Para remove_if
#include <string> // Para basic_string, string
#include <vector> // Para vector
#include <utility>
#include <vector> // Para vector
#include "audio.h" // Para Audio
#include "param.h" // Para Param, param, ParamNotification, ParamGame
@@ -14,22 +15,22 @@
#include "texture.h" // Para Texture
// Singleton
Notifier *Notifier::instance_ = nullptr;
Notifier *Notifier::instance = nullptr;
// Inicializa la instancia única del singleton
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance_ = new Notifier(icon_file, text); }
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance = new Notifier(icon_file, text); }
// Libera la instancia
void Notifier::destroy() { delete Notifier::instance_; }
void Notifier::destroy() { delete Notifier::instance; }
// Obtiene la instancia
Notifier *Notifier::get() { return Notifier::instance_; }
auto Notifier::get() -> Notifier * { return Notifier::instance; }
// Constructor
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text)
: renderer_(Screen::get()->getRenderer()),
icon_texture_(!icon_file.empty() ? std::make_unique<Texture>(renderer_, icon_file) : nullptr),
text_(text),
text_(std::move(text)),
bg_color_(param.notification.color),
wait_time_(150),
stack_(false),
@@ -264,7 +265,7 @@ void Notifier::clearAllNotifications() {
}
// Obtiene los códigos de las notificaciones
std::vector<std::string> Notifier::getCodes() {
auto Notifier::getCodes() -> std::vector<std::string> {
std::vector<std::string> codes;
for (const auto &notification : notifications_) {
codes.emplace_back(notification.code);

View File

@@ -18,7 +18,7 @@ class Notifier {
// --- Métodos de singleton ---
static void init(const std::string &icon_file, std::shared_ptr<Text> text); // Inicializa el singleton
static void destroy(); // Libera el singleton
static Notifier *get(); // Obtiene la instancia
static auto get() -> Notifier *; // Obtiene la instancia
// --- Métodos principales ---
void render(); // Dibuja las notificaciones por pantalla
@@ -26,43 +26,43 @@ class Notifier {
// --- Gestión de notificaciones ---
void show(std::vector<std::string> texts, int icon = -1, const std::string &code = std::string()); // Muestra una notificación de texto por pantalla
bool isActive() const { return !notifications_.empty(); } // Indica si hay notificaciones activas
std::vector<std::string> getCodes(); // Obtiene los códigos de las notificaciones activas
bool checkCode(const std::string &code) { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
[[nodiscard]] auto isActive() const -> bool { return !notifications_.empty(); } // Indica si hay notificaciones activas
auto getCodes() -> std::vector<std::string>; // Obtiene los códigos de las notificaciones activas
auto checkCode(const std::string &code) -> bool { return stringInVector(getCodes(), code); } // Comprueba si hay alguna notificación con un código concreto
private:
private:
// --- Singleton ---
static Notifier *instance_;
static Notifier *instance;
// --- Tipos internos ---
enum class NotificationStatus {
RISING,
STAY,
VANISHING,
FINISHED,
};
// --- Tipos internos ---
enum class NotificationStatus {
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationShape {
ROUNDED,
SQUARED,
};
enum class NotificationShape {
ROUNDED,
SQUARED,
};
// --- Estructura Notification ---
struct Notification {
std::shared_ptr<Texture> texture; // Textura de la notificación
std::shared_ptr<Sprite> sprite; // Sprite asociado
std::vector<std::string> texts; // Textos a mostrar
int counter; // Contador de tiempo
NotificationStatus state; // Estado de la notificación
NotificationShape shape; // Forma de la notificación
SDL_FRect rect; // Rectángulo de la notificación
int y; // Posición vertical
int travel_dist; // Distancia a recorrer
std::string code; // Código identificador de la notificación
// --- Estructura Notification ---
struct Notification {
std::shared_ptr<Texture> texture; // Textura de la notificación
std::shared_ptr<Sprite> sprite; // Sprite asociado
std::vector<std::string> texts; // Textos a mostrar
int counter{0}; // Contador de tiempo
NotificationStatus state{NotificationStatus::RISING}; // Estado de la notificación
NotificationShape shape{NotificationShape::SQUARED}; // Forma de la notificación
SDL_FRect rect; // Rectángulo de la notificación
int y{0}; // Posición vertical
int travel_dist{0}; // Distancia a recorrer
std::string code; // Código identificador de la notificación
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), counter(0), state(NotificationStatus::RISING), shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), rect{0, 0, 0, 0}, code("") {}
};
// --- Objetos y punteros ---

View File

@@ -28,7 +28,7 @@ std::vector<Difficulty> difficulties = {
{DifficultyCode::HARD, "Hard"}};
// Declaraciones
bool set(const std::string &var, const std::string &value);
auto set(const std::string &var, const std::string &value) -> bool;
// Inicializa las opciones del programa
void init() {
@@ -49,7 +49,7 @@ void init() {
}
// Carga el fichero de configuración
bool loadFromFile() {
auto loadFromFile() -> bool {
// Inicializa las opciones del programa
init();
@@ -94,7 +94,7 @@ bool loadFromFile() {
}
// Guarda el fichero de configuración
bool saveToFile() {
auto saveToFile() -> bool {
std::ofstream file(settings.config_file);
if (!file.good()) {
@@ -167,7 +167,7 @@ bool saveToFile() {
}
// Asigna variables a partir de dos cadenas
bool set(const std::string &var, const std::string &value) {
auto set(const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación
auto success = true;
@@ -281,7 +281,7 @@ void swapControllers() {
}
// Averigua quien está usando el teclado
int getPlayerWhoUsesKeyboard() {
auto getPlayerWhoUsesKeyboard() -> int {
for (const auto &controller : controllers) {
if (controller.type == InputDevice::ANY) {
return controller.player_id;
@@ -308,7 +308,7 @@ void checkPendingChanges() {
}
}
DifficultyCode getDifficultyCodeFromName(const std::string &name) {
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode {
for (const auto &difficulty : difficulties) {
if (difficulty.name == name)
return difficulty.code;
@@ -317,7 +317,7 @@ DifficultyCode getDifficultyCodeFromName(const std::string &name) {
return difficulties[0].code;
}
std::string getDifficultyNameFromCode(DifficultyCode code) {
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string {
for (const auto &difficulty : difficulties) {
if (difficulty.code == code)
return difficulty.name;

View File

@@ -3,6 +3,7 @@
#include <SDL3/SDL.h> // Para SDL_GamepadButton, SDL_ScaleMode
#include <string> // Para string, basic_string
#include <utility>
#include <vector> // Para vector
#include "input.h" // Para InputAction, InputDevice
@@ -24,102 +25,89 @@ struct Difficulty {
DifficultyCode code; // Código que identifica la dificultad
std::string name; // Nombre que identifica la dificultad
Difficulty(DifficultyCode c, const std::string &n)
: code(c), name(n) {}
Difficulty(DifficultyCode c, std::string n)
: code(c), name(std::move(n)) {}
};
// --- Opciones de ventana ---
struct WindowOptions {
std::string caption; // Texto que aparece en la barra de título de la ventana
int size; // Valor por el que se multiplica el tamaño de la ventana
int max_size; // Tamaño máximo para que la ventana no sea mayor que la pantalla
int size{2}; // Valor por el que se multiplica el tamaño de la ventana
int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla
// Constructor por defecto con valores iniciales
WindowOptions()
: caption("Coffee Crisis Arcade Edition"),
size(2),
max_size(2) {}
: caption("Coffee Crisis Arcade Edition") {}
};
// --- Opciones de vídeo ---
struct VideoOptions {
SDL_ScaleMode scale_mode; // Filtro usado para el escalado de la imagen
bool fullscreen; // Indica si se usa pantalla completa
bool v_sync; // Indica si se usa vsync
bool integer_scale; // Indica si se usa escalado entero
bool shaders; // Indica si se usan shaders para los filtros de vídeo
std::string info; // Información sobre el modo de vídeo
SDL_ScaleMode scale_mode{SDL_ScaleMode::SDL_SCALEMODE_NEAREST}; // Filtro usado para el escalado de la imagen
bool fullscreen{false}; // Indica si se usa pantalla completa
bool v_sync{true}; // Indica si se usa vsync
bool integer_scale{true}; // Indica si se usa escalado entero
bool shaders{false}; // Indica si se usan shaders para los filtros de vídeo
std::string info; // Información sobre el modo de vídeo
// Constructor por defecto con valores iniciales
VideoOptions()
: scale_mode(SDL_ScaleMode::SDL_SCALEMODE_NEAREST),
fullscreen(false),
v_sync(true),
integer_scale(true),
shaders(false),
info() {}
// Constructor por defecto con valores iniciales
VideoOptions()
: info() {}
};
// --- Opciones de música ---
struct MusicOptions {
bool enabled; // Indica si la música suena o no
int volume; // Volumen de la música
bool enabled{true}; // Indica si la música suena o no
int volume{100}; // Volumen de la música
// Constructor por defecto
MusicOptions()
: enabled(true),
volume(100) {}
// Constructor por defecto
MusicOptions()
{}
};
// --- Opciones de sonido ---
struct SoundOptions {
bool enabled; // Indica si los sonidos suenan o no
int volume; // Volumen de los sonidos
bool enabled{true}; // Indica si los sonidos suenan o no
int volume{100}; // Volumen de los sonidos
// Constructor por defecto
SoundOptions()
: enabled(true),
volume(100) {}
// Constructor por defecto
SoundOptions()
{}
};
// --- Opciones de audio ---
struct AudioOptions {
MusicOptions music; // Opciones para la música
SoundOptions sound; // Opciones para los efectos de sonido
bool enabled; // Indica si el audio está activo o no
int volume; // Volumen general del audio
bool enabled{true}; // Indica si el audio está activo o no
int volume{100}; // Volumen general del audio
// Constructor por defecto
AudioOptions()
: music(),
sound(),
enabled(true),
volume(100) {}
sound() {}
};
// --- Opciones de configuración ---
struct SettingsOptions {
DifficultyCode difficulty; // Dificultad del juego
Lang::Code language; // Idioma usado en el juego
bool autofire; // Indicador de autofire
bool shutdown_enabled; // Especifica si se puede apagar el sistema
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
std::vector<int> last_hi_score_entry; // Últimas posiciones de entrada en la tabla
std::string config_file; // Ruta al fichero donde guardar la configuración y las opciones del juego
DifficultyCode difficulty{DifficultyCode::NORMAL}; // Dificultad del juego
Lang::Code language{Lang::Code::VALENCIAN}; // Idioma usado en el juego
bool autofire{true}; // Indicador de autofire
bool shutdown_enabled{false}; // Especifica si se puede apagar el sistema
std::vector<HiScoreEntry> hi_score_table; // Tabla de mejores puntuaciones
std::vector<int> last_hi_score_entry; // Últimas posiciones de entrada en la tabla
std::string config_file; // Ruta al fichero donde guardar la configuración y las opciones del juego
// Constructor por defecto con valores iniciales
SettingsOptions()
: difficulty(DifficultyCode::NORMAL),
language(Lang::Code::VALENCIAN),
autofire(true),
shutdown_enabled(false),
last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
config_file() {}
// Constructor por defecto con valores iniciales
SettingsOptions()
: last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
config_file() {}
// Reinicia las últimas entradas de puntuación
void clearLastHiScoreEntries() {
last_hi_score_entry[0] = INVALID_INDEX;
last_hi_score_entry[1] = INVALID_INDEX;
// Reinicia las últimas entradas de puntuación
void clearLastHiScoreEntries() {
last_hi_score_entry[0] = INVALID_INDEX;
last_hi_score_entry[1] = INVALID_INDEX;
}
};
@@ -127,9 +115,9 @@ struct SettingsOptions {
struct GamepadOptions {
int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando
InputDevice type; // Indica si se usará teclado, mando o ambos
InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando está conectado
bool plugged{false}; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
@@ -137,9 +125,9 @@ struct GamepadOptions {
GamepadOptions()
: index(INVALID_INDEX),
player_id(INVALID_INDEX),
type(InputDevice::CONTROLLER),
name(),
plugged(false),
inputs{
InputAction::FIRE_LEFT,
InputAction::FIRE_CENTER,
@@ -156,15 +144,14 @@ struct GamepadOptions {
// --- Opciones pendientes de aplicar ---
struct PendingChanges {
Lang::Code new_language; // Idioma en espera de aplicar
DifficultyCode new_difficulty; // Dificultad en espera de aplicar
bool has_pending_changes; // Indica si hay cambios pendientes
Lang::Code new_language{Lang::Code::VALENCIAN}; // Idioma en espera de aplicar
DifficultyCode new_difficulty{DifficultyCode::NORMAL}; // Dificultad en espera de aplicar
bool has_pending_changes{false}; // Indica si hay cambios pendientes
// Constructor por defecto con valores iniciales
PendingChanges()
: new_language(Lang::Code::VALENCIAN),
new_difficulty(DifficultyCode::NORMAL),
has_pending_changes(false) {}
// Constructor por defecto con valores iniciales
PendingChanges()
{}
};
// --- Variables globales ---
@@ -178,14 +165,14 @@ extern std::vector<Difficulty> difficulties; // Lista de los diferentes tipo
// --- Funciones de configuración ---
void init(); // Inicializa las opciones del programa
bool loadFromFile(); // Carga el fichero de configuración
bool saveToFile(); // Guarda el fichero de configuración
auto loadFromFile() -> bool; // Carga el fichero de configuración
auto saveToFile() -> bool; // Guarda el fichero de configuración
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
void swapKeyboard(); // Intercambia el teclado de jugador
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
int getPlayerWhoUsesKeyboard(); // Averigua quién está usando el teclado
auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
void checkPendingChanges(); // Verifica si hay cambios pendientes
DifficultyCode getDifficultyCodeFromName(const std::string &name); // Obtiene el código de dificultad a partir del nombre
std::string getDifficultyNameFromCode(DifficultyCode code); // Obtiene el nombre de la dificultad a partir del código
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode; // Obtiene el código de dificultad a partir del nombre
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string; // Obtiene el nombre de la dificultad a partir del código
} // namespace Options

View File

@@ -15,7 +15,7 @@ Param param;
void precalculateZones();
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value);
auto setParams(const std::string &var, const std::string &value) -> bool;
// Establece valores por defecto a las variables
void initParam() {
@@ -127,7 +127,7 @@ void loadParamsFromFile(const std::string &file_path) {
}
// Asigna variables a partir de dos cadenas
bool setParams(const std::string &var, const std::string &value) {
auto setParams(const std::string &var, const std::string &value) -> bool {
// Indicador de éxito en la asignación
auto success = true;

View File

@@ -6,7 +6,7 @@
#include <utility> // Para move
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) {
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint> {
std::vector<SDL_FPoint> v;
v.reserve(steps);
@@ -141,4 +141,4 @@ void PathSprite::goToNextPathOrDie() {
}
// Indica si ha terminado todos los recorridos
bool PathSprite::hasFinished() { return has_finished_; }
auto PathSprite::hasFinished() -> bool { return has_finished_; }

View File

@@ -37,7 +37,7 @@ struct Path {
};
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction);
auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function) -> std::vector<SDL_FPoint>;
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
class PathSprite : public Sprite {
@@ -54,16 +54,16 @@ class PathSprite : public Sprite {
// --- Gestión de recorridos ---
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0); // Añade un recorrido generado
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
// --- Estado y control ---
void enable(); // Habilita el objeto
bool hasFinished(); // Indica si ha terminado todos los recorridos
auto hasFinished() -> bool; // Indica si ha terminado todos los recorridos
// --- Getters ---
int getCurrentPath() const { return current_path_; } // Devuelve el índice del recorrido actual
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual
private:
private:
// --- Variables internas ---
bool enabled_ = false; // Indica si el objeto está habilitado
bool has_finished_ = false; // Indica si el objeto ha finalizado el recorrido

View File

@@ -1,9 +1,9 @@
#include "player.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_FlipMode, SDL_FRect
#include <stdlib.h> // Para rand
#include <algorithm> // Para clamp, max, min
#include <cstdlib> // Para rand
#include "animated_sprite.h" // Para AnimatedSprite
#include "asset.h" // Para Asset
@@ -46,7 +46,7 @@ void Player::init() {
firing_state_ = PlayerState::FIRING_NONE;
playing_state_ = PlayerState::WAITING;
power_up_ = false;
power_up_counter_ = POWERUP_COUNTER_;
power_up_counter_ = POWERUP_COUNTER;
extra_hit_ = false;
coffees_ = 0;
continue_ticks_ = 0;
@@ -91,12 +91,12 @@ void Player::setInput(InputAction input) {
void Player::setInputPlaying(InputAction input) {
switch (input) {
case InputAction::LEFT: {
vel_x_ = -BASE_SPEED_;
vel_x_ = -BASE_SPEED;
setWalkingState(PlayerState::WALKING_LEFT);
break;
}
case InputAction::RIGHT: {
vel_x_ = BASE_SPEED_;
vel_x_ = BASE_SPEED;
setWalkingState(PlayerState::WALKING_RIGHT);
break;
}
@@ -153,7 +153,7 @@ void Player::move() {
// Si el jugador abandona el area de juego por los laterales, restaura su posición
const float MIN_X = play_area_.x - 5;
const float MAX_X = play_area_.w + 5 - WIDTH_;
const float MAX_X = play_area_.w + 5 - WIDTH;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -163,7 +163,7 @@ void Player::move() {
// Si el jugador abandona el area de juego por los laterales lo hace rebotar
const int X = player_sprite_->getPosX();
const int MIN_X = play_area_.x;
const int MAX_X = play_area_.x + play_area_.w - WIDTH_;
const int MAX_X = play_area_.x + play_area_.w - WIDTH;
if ((X < MIN_X) || (X > MAX_X)) {
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
player_sprite_->setVelX(-player_sprite_->getVelX());
@@ -171,10 +171,10 @@ void Player::move() {
}
// Si el jugador toca el suelo rebota y si tiene poca velocidad, se detiene y cambia de estado
if (player_sprite_->getPosY() > play_area_.h - HEIGHT_) {
if (player_sprite_->getPosY() > play_area_.h - HEIGHT) {
if (player_sprite_->getVelY() < 2.0f) {
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
const auto NEXT_PLAYER_STATUS = IsEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
pos_x_ = player_sprite_->getPosX();
pos_y_ = default_pos_y_;
@@ -183,7 +183,7 @@ void Player::move() {
playSound("jump.wav");
} else {
// Decrementa las velocidades de rebote
player_sprite_->setPosY(play_area_.h - HEIGHT_);
player_sprite_->setPosY(play_area_.h - HEIGHT);
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5f);
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75f);
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
@@ -195,7 +195,7 @@ void Player::move() {
case PlayerState::TITLE_ANIMATION: {
// Si el jugador abandona el area de juego por los laterales lo detiene
/*const int X = player_sprite_->getPosX();
const int MIN_X = play_area_.x - WIDTH_;
const int MIN_X = play_area_.x - WIDTH;
const int MAX_X = play_area_.x + play_area_.w;
if ((X < MIN_X) || (X > MAX_X))
{
@@ -219,7 +219,7 @@ void Player::move() {
break;
}
pos_x_ += vel_x_ * 2.0f;
const float MIN_X = -WIDTH_;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -253,7 +253,7 @@ void Player::move() {
break;
}
pos_x_ += vel_x_;
const float MIN_X = -WIDTH_;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -298,8 +298,8 @@ void Player::move() {
pos_x_ += vel_x_ / 2.0f;
if (vel_x_ > 0) {
// setInputPlaying(InputAction::RIGHT);
if (pos_x_ > param.game.game_area.rect.w - WIDTH_) {
pos_x_ = param.game.game_area.rect.w - WIDTH_;
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
pos_x_ = param.game.game_area.rect.w - WIDTH;
vel_x_ *= -1;
}
} else {
@@ -310,7 +310,7 @@ void Player::move() {
}
}
if (pos_x_ > param.game.game_area.center_x - WIDTH_ / 2) {
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) {
setWalkingState(PlayerState::WALKING_LEFT);
} else {
setWalkingState(PlayerState::WALKING_RIGHT);
@@ -326,7 +326,7 @@ void Player::move() {
// Pinta el jugador en pantalla
void Player::render() {
if (power_up_ && isPlaying()) {
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4) {
if (power_up_counter_ > (POWERUP_COUNTER / 4) || power_up_counter_ % 20 > 4) {
power_sprite_->render();
}
}
@@ -406,7 +406,7 @@ void Player::setAnimation() {
void Player::updateCooldown() {
if (playing_state_ == PlayerState::PLAYING) {
if (cant_fire_counter_ > 0) {
cooling_state_counter_ = COOLING_DURATION_;
cooling_state_counter_ = COOLING_DURATION;
// La mitad del tiempo que no puede disparar tiene el brazo arriba (PlayerState::FIRING)
// y la otra mitad en retroceso (PlayerState::RECOILING)
@@ -434,8 +434,8 @@ void Player::updateCooldown() {
if (recoiling_state_counter_ > 0) {
--recoiling_state_counter_;
} else {
if (cooling_state_counter_ > COOLING_COMPLETE_) {
if (cooling_state_counter_ == COOLING_DURATION_) {
if (cooling_state_counter_ > COOLING_COMPLETE) {
if (cooling_state_counter_ == COOLING_DURATION) {
switch (firing_state_) {
case PlayerState::RECOILING_LEFT:
setFiringState(PlayerState::COOLING_LEFT);
@@ -454,7 +454,7 @@ void Player::updateCooldown() {
--cooling_state_counter_;
}
if (cooling_state_counter_ == COOLING_COMPLETE_) {
if (cooling_state_counter_ == COOLING_COMPLETE) {
setFiringState(PlayerState::FIRING_NONE);
cooling_state_counter_ = -1;
}
@@ -608,7 +608,7 @@ void Player::setPlayingState(PlayerState state) {
setScoreboardMode(ScoreboardMode::SCORE);
switch (id_) {
case 1:
pos_x_ = param.game.game_area.rect.x - WIDTH_;
pos_x_ = param.game.game_area.rect.x - WIDTH;
break;
case 2:
@@ -621,7 +621,7 @@ void Player::setPlayingState(PlayerState state) {
break;
}
case PlayerState::CREDITS: {
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED_ : -BASE_SPEED_;
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED : -BASE_SPEED;
break;
}
default:
@@ -644,7 +644,7 @@ void Player::decScoreMultiplier() {
// Establece el valor del estado
void Player::setInvulnerable(bool value) {
invulnerable_ = value;
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER : 0;
}
// Monitoriza el estado
@@ -664,7 +664,7 @@ void Player::updateInvulnerable() {
// Establece el valor de la variable
void Player::setPowerUp() {
power_up_ = true;
power_up_counter_ = POWERUP_COUNTER_;
power_up_counter_ = POWERUP_COUNTER;
}
// Actualiza el valor de la variable
@@ -698,8 +698,8 @@ void Player::removeExtraHit() {
// Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() {
collider_.x = static_cast<int>(pos_x_ + (WIDTH_ / 2));
collider_.y = static_cast<int>(pos_y_ + (HEIGHT_ / 2));
collider_.x = static_cast<int>(pos_x_ + (WIDTH / 2));
collider_.y = static_cast<int>(pos_y_ + (HEIGHT / 2));
}
// Pone las texturas del jugador
@@ -772,7 +772,7 @@ void Player::decNameEntryCounter() {
}
// Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
int Player::getRecordNamePos() const {
auto Player::getRecordNamePos() const -> int {
if (enter_name_) {
return enter_name_->getPosition();
}

View File

@@ -101,50 +101,50 @@ class Player {
void decContinueCounter(); // Decrementa el contador de continuar
// --- Getters y comprobaciones de estado ---
int getRecordNamePos() const; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
[[nodiscard]] auto getRecordNamePos() const -> int; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// Comprobación de playing_state
bool isLyingOnTheFloorForever() const { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
bool isCelebrating() const { return playing_state_ == PlayerState::CELEBRATING; }
bool isContinue() const { return playing_state_ == PlayerState::CONTINUE; }
bool isDying() const { return playing_state_ == PlayerState::ROLLING; }
bool isEnteringName() const { return playing_state_ == PlayerState::ENTERING_NAME; }
bool isShowingName() const { return playing_state_ == PlayerState::SHOWING_NAME; }
bool isEnteringNameGameCompleted() const { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
bool isLeavingScreen() const { return playing_state_ == PlayerState::LEAVING_SCREEN; }
bool isGameOver() const { return playing_state_ == PlayerState::GAME_OVER; }
bool isPlaying() const { return playing_state_ == PlayerState::PLAYING; }
bool isWaiting() const { return playing_state_ == PlayerState::WAITING; }
bool isTitleHidden() const { return playing_state_ == PlayerState::TITLE_HIDDEN; }
[[nodiscard]] auto isLyingOnTheFloorForever() const -> bool { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
[[nodiscard]] auto isCelebrating() const -> bool { return playing_state_ == PlayerState::CELEBRATING; }
[[nodiscard]] auto isContinue() const -> bool { return playing_state_ == PlayerState::CONTINUE; }
[[nodiscard]] auto isDying() const -> bool { return playing_state_ == PlayerState::ROLLING; }
[[nodiscard]] auto isEnteringName() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME; }
[[nodiscard]] auto isShowingName() const -> bool { return playing_state_ == PlayerState::SHOWING_NAME; }
[[nodiscard]] auto isEnteringNameGameCompleted() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
[[nodiscard]] auto isLeavingScreen() const -> bool { return playing_state_ == PlayerState::LEAVING_SCREEN; }
[[nodiscard]] auto isGameOver() const -> bool { return playing_state_ == PlayerState::GAME_OVER; }
[[nodiscard]] auto isPlaying() const -> bool { return playing_state_ == PlayerState::PLAYING; }
[[nodiscard]] auto isWaiting() const -> bool { return playing_state_ == PlayerState::WAITING; }
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == PlayerState::TITLE_HIDDEN; }
// Getters
bool canFire() const { return cant_fire_counter_ <= 0; }
bool hasExtraHit() const { return extra_hit_; }
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
bool isRecoiling() const { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
bool IsEligibleForHighScore() const { return score_ > Options::settings.hi_score_table.back().score; }
bool isInvulnerable() const { return invulnerable_; }
bool isPowerUp() const { return power_up_; }
Circle &getCollider() { return collider_; }
float getScoreMultiplier() const { return score_multiplier_; }
int getCoffees() const { return coffees_; }
int getContinueCounter() const { return continue_counter_; }
int getController() const { return controller_index_; }
int getHeight() const { return HEIGHT_; }
int getId() const { return id_; }
int getInvulnerableCounter() const { return invulnerable_counter_; }
int getPosX() const { return static_cast<int>(pos_x_); }
int getPosY() const { return pos_y_; }
int getPowerUpCounter() const { return power_up_counter_; }
std::string getRecordName() const { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
std::string getLastEnterName() const { return last_enter_name_; }
int getScore() const { return score_; }
int getScoreBoardPanel() const { return scoreboard_panel_; }
int getWidth() const { return WIDTH_; }
PlayerState getPlayingState() const { return playing_state_; }
const std::string &getName() const { return name_; }
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
bool getEnterNamePositionOverflow() const { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
[[nodiscard]] auto isEligibleForHighScore() const -> bool { return score_ > Options::settings.hi_score_table.back().score; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isPowerUp() const -> bool { return power_up_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getScoreMultiplier() const -> float { return score_multiplier_; }
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
[[nodiscard]] auto getController() const -> int { return controller_index_; }
[[nodiscard]] auto getHeight() const -> int { return HEIGHT; }
[[nodiscard]] auto getId() const -> int { return id_; }
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
[[nodiscard]] auto getPosX() const -> int { return static_cast<int>(pos_x_); }
[[nodiscard]] auto getPosY() const -> int { return pos_y_; }
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
[[nodiscard]] auto getScore() const -> int { return score_; }
[[nodiscard]] auto getScoreBoardPanel() const -> int { return scoreboard_panel_; }
[[nodiscard]] auto getWidth() const -> int { return WIDTH; }
[[nodiscard]] auto getPlayingState() const -> PlayerState { return playing_state_; }
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
// Setters inline
void setController(int index) { controller_index_ = index; }
@@ -161,71 +161,71 @@ class Player {
private:
// --- Constantes ---
static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp
static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable
static constexpr int WIDTH_ = 30; // Anchura
static constexpr int HEIGHT_ = 30; // Altura
static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador
static constexpr int COOLING_DURATION_ = 50;
static constexpr int COOLING_COMPLETE_ = 0;
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable
static constexpr int WIDTH = 30; // Anchura
static constexpr int HEIGHT = 30; // Altura
static constexpr float BASE_SPEED = 1.5f; // Velocidad base del jugador
static constexpr int COOLING_DURATION = 50;
static constexpr int COOLING_COMPLETE = 0;
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
// --- Variables de estado ---
int id_; // Número de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_FRect play_area_; // Rectángulo con la zona de juego
float pos_x_ = 0.0f; // Posición en el eje X
int pos_y_ = 0; // Posición en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje X
int vel_y_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje Y
int cant_fire_counter_ = 0; // Contador durante el cual no puede disparar
int recoiling_state_counter_ = 0; // Contador para la animación del estado de retroceso
int recoiling_state_duration_ = 0; // Numero de frames que dura el estado de retroceso
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
bool demo_ = false; // Para que el jugador sepa si está en el modo demostración
int name_entry_idle_counter_ = 0; // Contador para poner nombre
int name_entry_total_counter_ = 0; // Segundos totales que lleva acumulados poniendo nombre
Uint32 name_entry_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
bool game_completed_ = false; // Indica si ha completado el juego
int credits_used_ = 1; // Indica el número de veces que ha continuado
std::string last_enter_name_; // Último nombre introducido en la tabla de puntuaciones
// --- Variables de estado ---
int id_; // Número de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_FRect play_area_; // Rectángulo con la zona de juego
float pos_x_ = 0.0f; // Posición en el eje X
int pos_y_ = 0; // Posición en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje X
int vel_y_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje Y
int cant_fire_counter_ = 0; // Contador durante el cual no puede disparar
int recoiling_state_counter_ = 0; // Contador para la animación del estado de retroceso
int recoiling_state_duration_ = 0; // Numero de frames que dura el estado de retroceso
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
bool demo_ = false; // Para que el jugador sepa si está en el modo demostración
int name_entry_idle_counter_ = 0; // Contador para poner nombre
int name_entry_total_counter_ = 0; // Segundos totales que lleva acumulados poniendo nombre
Uint32 name_entry_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
bool game_completed_ = false; // Indica si ha completado el juego
int credits_used_ = 1; // Indica el número de veces que ha continuado
std::string last_enter_name_; // Último nombre introducido en la tabla de puntuaciones
// --- Métodos internos ---
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
void shiftSprite(); // Recoloca el sprite
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
void updateContinueCounter(); // Actualiza el contador de continue
void updateEnterNameCounter(); // Actualiza el contador de entrar nombre
void updateShowingName(); // Actualiza el estado SHOWING_NAME
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
void updateScoreboard(); // Actualiza el panel del marcador
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
void playSound(const std::string &name); // Hace sonar un sonido
bool isRenderable() const { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
// --- Métodos internos ---
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
void shiftSprite(); // Recoloca el sprite
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
void updateContinueCounter(); // Actualiza el contador de continue
void updateEnterNameCounter(); // Actualiza el contador de entrar nombre
void updateShowingName(); // Actualiza el estado SHOWING_NAME
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
void updateScoreboard(); // Actualiza el panel del marcador
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
void playSound(const std::string &name); // Hace sonar un sonido
[[nodiscard]] auto isRenderable() const -> bool { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
};

View File

@@ -1,11 +1,12 @@
#include "resource.h"
#include <SDL3/SDL.h> // Para SDL_LogInfo, SDL_LogCategory, SDL_L...
#include <stdlib.h> // Para exit
#include <algorithm> // Para find_if
#include <array> // Para array
#include <cstdlib> // Para exit
#include <stdexcept> // Para runtime_error
#include <utility>
#include "asset.h" // Para Asset, AssetType
#include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_...
@@ -18,16 +19,16 @@ struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12
// Singleton
Resource *Resource::instance_ = nullptr;
Resource *Resource::instance = nullptr;
// Inicializa la instancia única del singleton
void Resource::init() { Resource::instance_ = new Resource(); }
void Resource::init() { Resource::instance = new Resource(); }
// Libera la instancia
void Resource::destroy() { delete Resource::instance_; }
void Resource::destroy() { delete Resource::instance; }
// Obtiene la instancia
Resource *Resource::get() { return Resource::instance_; }
auto Resource::get() -> Resource * { return Resource::instance; }
// Constructor
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
@@ -87,7 +88,7 @@ void Resource::reloadTextures() {
}
// Obtiene el sonido a partir de un nombre. Lanza excepción si no existe.
JA_Sound_t *Resource::getSound(const std::string &name) {
auto Resource::getSound(const std::string &name) -> JA_Sound_t * {
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) { return s.name == name; });
if (it != sounds_.end()) {
@@ -99,7 +100,7 @@ JA_Sound_t *Resource::getSound(const std::string &name) {
}
// Obtiene la música a partir de un nombre. Lanza excepción si no existe.
JA_Music_t *Resource::getMusic(const std::string &name) {
auto Resource::getMusic(const std::string &name) -> JA_Music_t * {
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) { return m.name == name; });
if (it != musics_.end()) {
@@ -111,7 +112,7 @@ JA_Music_t *Resource::getMusic(const std::string &name) {
}
// Obtiene la textura a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
auto Resource::getTexture(const std::string &name) -> std::shared_ptr<Texture> {
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) { return t.name == name; });
if (it != textures_.end()) {
@@ -123,7 +124,7 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name) {
}
// Obtiene el fichero de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
auto Resource::getTextFile(const std::string &name) -> std::shared_ptr<TextFile> {
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) { return t.name == name; });
if (it != text_files_.end()) {
@@ -135,7 +136,7 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) {
}
// Obtiene el objeto de texto a partir de un nombre. Lanza excepción si no existe.
std::shared_ptr<Text> Resource::getText(const std::string &name) {
auto Resource::getText(const std::string &name) -> std::shared_ptr<Text> {
auto it = std::find_if(texts_.begin(), texts_.end(), [&name](const auto &t) { return t.name == name; });
if (it != texts_.end()) {
@@ -147,7 +148,7 @@ std::shared_ptr<Text> Resource::getText(const std::string &name) {
}
// Obtiene la animación a partir de un nombre. Lanza excepción si no existe.
AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
auto Resource::getAnimation(const std::string &name) -> AnimationsFileBuffer & {
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](const auto &a) { return a.name == name; });
if (it != animations_.end()) {
@@ -159,7 +160,7 @@ AnimationsFileBuffer &Resource::getAnimation(const std::string &name) {
}
// Obtiene el fichero con los datos para el modo demostración a partir de un índice
DemoData &Resource::getDemoData(int index) {
auto Resource::getDemoData(int index) -> DemoData & {
return demos_.at(index);
}
@@ -172,7 +173,7 @@ void Resource::loadSounds() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
sounds_.emplace_back(Resource::ResourceSound(name, JA_LoadSound(l.c_str())));
sounds_.emplace_back(name, JA_LoadSound(l.c_str()));
printWithDots("Sound : ", name, "[ LOADED ]");
}
}
@@ -186,7 +187,7 @@ void Resource::loadMusics() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
musics_.emplace_back(Resource::ResourceMusic(name, JA_LoadMusic(l.c_str())));
musics_.emplace_back(name, JA_LoadMusic(l.c_str()));
printWithDots("Music : ", name, "[ LOADED ]");
}
}
@@ -200,7 +201,7 @@ void Resource::loadTextures() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
textures_.emplace_back(Resource::ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
textures_.emplace_back(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l));
}
}
@@ -213,7 +214,7 @@ void Resource::loadTextFiles() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
text_files_.emplace_back(Resource::ResourceTextFile(name, loadTextFile(l)));
text_files_.emplace_back(name, loadTextFile(l));
}
}
@@ -226,7 +227,7 @@ void Resource::loadAnimations() {
for (const auto &l : list) {
auto name = getFileName(l);
updateLoadingProgress(name);
animations_.emplace_back(Resource::ResourceAnimation(name, loadAnimationsFromFile(l)));
animations_.emplace_back(name, loadAnimationsFromFile(l));
}
}
@@ -260,11 +261,11 @@ void Resource::addPalettes() {
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes
void Resource::createTextures() {
struct NameAndText {
std::string name;
std::string text;
std::string name;
std::string text;
NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {}
NameAndText(std::string name_init, std::string text_init)
: name(std::move(name_init)), text(std::move(text_init)) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
@@ -281,7 +282,7 @@ void Resource::createTextures() {
auto text = getText("04b_25");
for (const auto &s : strings) {
textures_.emplace_back(Resource::ResourceTexture(s.name, text->writeToTexture(s.text, 1, -2)));
textures_.emplace_back(s.name, text->writeToTexture(s.text, 1, -2));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
@@ -295,7 +296,7 @@ void Resource::createTextures() {
auto text2 = getText("04b_25_2x");
for (const auto &s : strings2_x) {
textures_.emplace_back(Resource::ResourceTexture(s.name, text2->writeToTexture(s.text, 1, -4)));
textures_.emplace_back(s.name, text2->writeToTexture(s.text, 1, -4));
printWithDots("Texture : ", s.name, "[ DONE ]");
}
}
@@ -303,12 +304,12 @@ void Resource::createTextures() {
// Crea los objetos de texto a partir de los archivos de textura y texto
void Resource::createText() {
struct ResourceInfo {
std::string key;
std::string texture_file;
std::string text_file;
std::string key;
std::string texture_file;
std::string text_file;
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
: key(k), texture_file(t_file), text_file(txt_file) {}
ResourceInfo(std::string k, std::string t_file, std::string txt_file)
: key(std::move(k)), texture_file(std::move(t_file)), text_file(std::move(txt_file)) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");
@@ -328,7 +329,7 @@ void Resource::createText() {
{"smb2_grad", "smb2_grad.png", "smb2.txt"}};
for (const auto &resource : resources) {
texts_.emplace_back(Resource::ResourceText(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file))));
texts_.emplace_back(resource.key, std::make_shared<Text>(getTexture(resource.texture_file), getTextFile(resource.text_file)));
printWithDots("Text : ", resource.key, "[ DONE ]");
}
}

View File

@@ -1,10 +1,10 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para basic_string, string
#include <utility>
#include <vector> // Para vector
@@ -146,5 +146,5 @@ class Resource {
~Resource(); // Destructor privado
// --- Instancia singleton ---
static Resource *instance_; // Instancia única de Resource
static Resource *instance; // Instancia única de Resource
};

View File

@@ -1,8 +1,8 @@
#include "scoreboard.h"
#include <SDL3/SDL.h> // Para SDL_DestroyTexture, SDL_SetRenderDrawColor
#include <math.h> // Para roundf
#include <cmath> // Para roundf
#include <iomanip> // Para operator<<, setfill, setw
#include <sstream> // Para basic_ostringstream, basic_ostream, basic_os...
@@ -16,21 +16,21 @@
#include "texture.h" // Para Texture
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Scoreboard *Scoreboard::scoreboard_ = nullptr;
Scoreboard *Scoreboard::instance = nullptr;
// [SINGLETON] Crearemos el objeto score_board con esta función estática
void Scoreboard::init() {
Scoreboard::scoreboard_ = new Scoreboard();
Scoreboard::instance = new Scoreboard();
}
// [SINGLETON] Destruiremos el objeto score_board con esta función estática
void Scoreboard::destroy() {
delete Scoreboard::scoreboard_;
delete Scoreboard::instance;
}
// [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él
Scoreboard *Scoreboard::get() {
return Scoreboard::scoreboard_;
auto Scoreboard::get() -> Scoreboard * {
return Scoreboard::instance;
}
// Constructor
@@ -88,7 +88,7 @@ Scoreboard::~Scoreboard() {
}
// Transforma un valor numérico en una cadena de 7 cifras
std::string Scoreboard::updateScoreText(int num) {
auto Scoreboard::updateScoreText(int num) -> std::string {
std::ostringstream oss;
oss << std::setw(7) << std::setfill('0') << num;
return oss.str();
@@ -385,8 +385,8 @@ void Scoreboard::createPanelTextures() {
panel_texture_.clear();
// Crea las texturas para cada panel_
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, panel_[i].pos.w, panel_[i].pos.h);
for (auto &i : panel_) {
SDL_Texture *tex = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, i.pos.w, i.pos.h);
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
panel_texture_.push_back(tex);
}

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para basic_string, string
#include <vector> // Para vector
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para basic_string, string
#include <vector> // Para vector
#include "utils.h" // Para Color
@@ -45,7 +45,7 @@ class Scoreboard {
// --- Métodos de singleton ---
static void init(); // Crea el objeto Scoreboard
static void destroy(); // Libera el objeto Scoreboard
static Scoreboard *get(); // Obtiene el puntero al objeto Scoreboard
static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard
// --- Métodos principales ---
void update(); // Actualiza la lógica del marcador
@@ -67,55 +67,55 @@ class Scoreboard {
void setStage(int stage) { stage_ = stage; }
private:
// --- Singleton ---
static Scoreboard *scoreboard_;
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// --- Variables de estado ---
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Variables de estado ---
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
std::string updateScoreText(int num); // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Singleton ---
static Scoreboard *instance;
};

View File

@@ -19,16 +19,16 @@
#include "ui/service_menu.h" // Para ServiceMenu
// Singleton
Screen *Screen::instance_ = nullptr;
Screen *Screen::instance = nullptr;
// Inicializa la instancia única del singleton
void Screen::init() { Screen::instance_ = new Screen(); }
void Screen::init() { Screen::instance = new Screen(); }
// Libera la instancia
void Screen::destroy() { delete Screen::instance_; }
void Screen::destroy() { delete Screen::instance; }
// Obtiene la instancia
auto Screen::get() -> Screen * { return Screen::instance_; }
auto Screen::get() -> Screen * { return Screen::instance; }
// Constructor
Screen::Screen()
@@ -214,7 +214,7 @@ void Screen::renderInfo() {
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
// FPS
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS";
const std::string FPS_TEXT = std::to_string(fps_.last_value) + " FPS";
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
}
}
@@ -254,7 +254,7 @@ void Screen::adjustWindowSize() {
const int NEW_POS_X = old_pos_x + ((old_width - WIDTH) / 2);
const int NEW_POS_Y = old_pos_y + ((old_height - HEIGHT) / 2);
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS), std::max(NEW_POS_Y, 0));
SDL_SetWindowSize(window_, WIDTH, HEIGHT);
}
}
@@ -370,7 +370,7 @@ void Screen::getDisplayInfo() {
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS_) / param.game.height);
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS) / param.game.height);
// Normaliza los valores de zoom
Options::window.size = std::min(Options::window.size, MAX_ZOOM);

View File

@@ -18,7 +18,7 @@ class Screen {
// --- Métodos de singleton ---
static void init(); // Inicializa el objeto Screen
static void destroy(); // Libera el objeto Screen
static Screen *get(); // Obtiene el puntero al objeto Screen
static auto get() -> Screen *; // Obtiene el puntero al objeto Screen
// --- Métodos principales ---
void update(); // Actualiza la lógica de la clase
@@ -32,8 +32,8 @@ class Screen {
void setFullscreenMode(); // Establece el modo de pantalla completa
void toggleFullscreen(); // Cambia entre pantalla completa y ventana
void setWindowZoom(int size); // Cambia el tamaño de la ventana
bool decWindowSize(); // Reduce el tamaño de la ventana
bool incWindowSize(); // Aumenta el tamaño de la ventana
auto decWindowSize() -> bool; // Reduce el tamaño de la ventana
auto incWindowSize() -> bool; // Aumenta el tamaño de la ventana
void applySettings(); // Aplica los valores de las opciones
void initShaders(); // Inicializa los shaders
@@ -47,12 +47,12 @@ class Screen {
void attenuate(bool value) { attenuate_effect_ = value; } // Atenúa la pantalla
// --- Getters ---
SDL_Renderer *getRenderer() { return renderer_; } // Obtiene el renderizador
auto getRenderer() -> SDL_Renderer * { return renderer_; } // Obtiene el renderizador
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
void getSingletons(); // Obtiene los punteros a los singletones
bool getVSync() const { return Options::video.v_sync; } // Obtiene el valor de V-Sync
std::shared_ptr<Text> getText() const { return text_; } // Obtiene el puntero al texto de Screen
[[nodiscard]] auto getVSync() const -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
#ifdef DEBUG
// --- Debug ---
@@ -62,24 +62,24 @@ class Screen {
private:
// --- Constantes ---
static constexpr int WINDOWS_DECORATIONS_ = 35;
static constexpr int WINDOWS_DECORATIONS = 35;
// --- Estructuras internas ---
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frameCount; // Número acumulado de frames en el intervalo.
int lastValue; // Número de frames calculado en el último segundo.
// --- Estructuras internas ---
struct FPS {
Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count{0}; // Número acumulado de frames en el intervalo.
int last_value{0}; // Número de frames calculado en el último segundo.
FPS() : ticks(0), frameCount(0), lastValue(0) {}
void increment() { frameCount++; }
int calculate(Uint32 currentTicks) {
if (currentTicks - ticks >= 1000) {
lastValue = frameCount;
frameCount = 0;
ticks = currentTicks;
}
return lastValue;
}
FPS() {}
void increment() { frame_count++; }
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) {
last_value = frame_count;
frame_count = 0;
ticks = current_ticks;
}
return last_value;
}
};
// Efecto de flash en pantalla: pinta la pantalla de un color durante unos frames
@@ -94,7 +94,7 @@ class Screen {
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
bool isRendarable() { return enabled && counter < lenght - delay; }
auto isRendarable() -> bool { return enabled && counter < lenght - delay; }
};
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
@@ -108,8 +108,8 @@ class Screen {
int original_width; // Ancho original de la imagen
bool enabled; // Indica si el efecto está activo
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int origPos = 0, int origWidth = 800)
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(origPos), original_width(origWidth), enabled(en) {}
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
// Activa el efecto de sacudida y guarda la posición y tamaño originales
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
@@ -156,7 +156,7 @@ class Screen {
}
}
bool isEnabled() const { return enabled; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled; }
};
#ifdef DEBUG
@@ -168,7 +168,7 @@ class Screen {
#endif
// --- Singleton ---
static Screen *instance_;
static Screen *instance;
// --- Objetos y punteros ---
SDL_Window *window_; // Ventana de la aplicación
@@ -193,7 +193,7 @@ class Screen {
std::shared_ptr<Text> text_; // Objeto para escribir texto en pantalla
// --- Métodos internos ---
bool initSDLVideo(); // Arranca SDL VIDEO y crea la ventana
auto initSDLVideo() -> bool; // Arranca SDL VIDEO y crea la ventana
void renderFlash(); // Dibuja el efecto de flash en la pantalla
void renderShake(); // Aplica el efecto de agitar la pantalla
void renderInfo(); // Muestra información por pantalla

View File

@@ -170,9 +170,8 @@ void Credits::fillTextTexture() {
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT;
int y = (param.game.height - TEXTS_HEIGHT) / 2;
// PROGRAMMED_AND_DESIGNED_BY
y = 0;
int y = 0;
text_grad->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_POST_TITLE;
@@ -259,7 +258,7 @@ void Credits::fillCanvas() {
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0, 0, 0xFF);
const Color COLOR = color_.LIGHTEN();
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF);
SDL_RenderRect(Screen::get()->getRenderer(), &red_rect);
SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_);
// Si el mini_logo está en su destino, lo dibuja encima de lo anterior
if (mini_logo_on_position_) {
@@ -408,10 +407,10 @@ void Credits::updateBlackRects() {
// Actualiza el rectangulo rojo
void Credits::updateRedRect() {
red_rect.x = left_black_rect_.x + left_black_rect_.w;
red_rect.y = top_black_rect_.y + top_black_rect_.h - 1;
red_rect.w = right_black_rect_.x - red_rect.x;
red_rect.h = bottom_black_rect_.y - red_rect.y + 1;
border_rect_.x = left_black_rect_.x + left_black_rect_.w;
border_rect_.y = top_black_rect_.y + top_black_rect_.h - 1;
border_rect_.w = right_black_rect_.x - border_rect_.x;
border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1;
}
// Actualiza el estado de fade
@@ -452,9 +451,9 @@ void Credits::cycleColors() {
constexpr int UPPER_LIMIT = 140; // Límite superior
constexpr int LOWER_LIMIT = 30; // Límite inferior
static float r_ = static_cast<float>(UPPER_LIMIT);
static float g_ = static_cast<float>(LOWER_LIMIT);
static float b_ = static_cast<float>(LOWER_LIMIT);
static auto r_ = static_cast<float>(UPPER_LIMIT);
static auto g_ = static_cast<float>(LOWER_LIMIT);
static auto b_ = static_cast<float>(LOWER_LIMIT);
static float step_r_ = -0.5f; // Paso flotante para transiciones suaves
static float step_g_ = 0.3f;
static float step_b_ = 0.1f;

View File

@@ -16,114 +16,114 @@ class Player;
class TiledBG;
class Credits {
public:
// --- Constructores y destructor ---
Credits();
~Credits();
public:
// --- Constructores y destructor ---
Credits();
~Credits();
// --- Bucle principal ---
void run();
// --- Bucle principal ---
void run();
private:
// --- Constantes de clase ---
static constexpr int PLAY_AREA_HEIGHT = 200;
private:
// --- Constantes de clase ---
static constexpr int PLAY_AREA_HEIGHT = 200;
// --- Objetos principales ---
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
std::unique_ptr<Fade> fade_out_; // Fundido de salida
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
// --- Objetos principales ---
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
std::unique_ptr<Fade> fade_out_; // Fundido de salida
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
// --- Gestión de texturas ---
SDL_Texture *text_texture_; // Textura con el texto de créditos
SDL_Texture *canvas_; // Textura donde se dibuja todo
// --- Gestión de texturas ---
SDL_Texture *text_texture_; // Textura con el texto de créditos
SDL_Texture *canvas_; // Textura donde se dibuja todo
// --- Temporización y contadores ---
Uint64 ticks_ = 0; // Control de velocidad del programa
Uint32 counter_ = 0; // Contador principal de lógica
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
// --- Temporización y contadores ---
Uint64 ticks_ = 0; // Control de velocidad del programa
Uint32 counter_ = 0; // Contador principal de lógica
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
// --- Variables de estado ---
bool fading_ = false; // Estado del fade final
bool want_to_pass_ = false; // Jugador quiere saltarse créditos
bool mini_logo_on_position_ = false; // Minilogo en posición final
// --- Variables de estado ---
bool fading_ = false; // Estado del fade final
bool want_to_pass_ = false; // Jugador quiere saltarse créditos
bool mini_logo_on_position_ = false; // Minilogo en posición final
// --- Diseño y posicionamiento ---
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
int mini_logo_final_pos_ = 0; // Posición final del minilogo
Color color_; // Color usado para los efectos
// --- Diseño y posicionamiento ---
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
int mini_logo_final_pos_ = 0; // Posición final del minilogo
Color color_; // Color usado para los efectos
// --- Control de audio ---
int initial_volume_ = Options::audio.music.volume; // Volumen inicial
int steps_ = 0; // Pasos para reducir audio
// --- Control de audio ---
int initial_volume_ = Options::audio.music.volume; // Volumen inicial
int steps_ = 0; // Pasos para reducir audio
// --- Rectángulos de renderizado ---
// Texto de créditos
SDL_FRect credits_rect_src_ = param.game.game_area.rect;
SDL_FRect credits_rect_dst_ = param.game.game_area.rect;
// --- Rectángulos de renderizado ---
// Texto de créditos
SDL_FRect credits_rect_src_ = param.game.game_area.rect;
SDL_FRect credits_rect_dst_ = param.game.game_area.rect;
// Mini logo
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect;
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect;
// Mini logo
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect;
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect;
// Definición del área de juego
SDL_FRect play_area_ = {
param.game.game_area.rect.x,
param.game.game_area.rect.y + black_bars_size_,
param.game.game_area.rect.w,
PLAY_AREA_HEIGHT};
// Definición del área de juego
SDL_FRect play_area_ = {
param.game.game_area.rect.x,
param.game.game_area.rect.y + black_bars_size_,
param.game.game_area.rect.w,
PLAY_AREA_HEIGHT};
// Barras negras para efecto letterbox
SDL_FRect top_black_rect_ = {
play_area_.x,
param.game.game_area.rect.y,
play_area_.w,
black_bars_size_};
SDL_FRect bottom_black_rect_ = {
play_area_.x,
param.game.game_area.rect.h - black_bars_size_,
play_area_.w,
black_bars_size_};
SDL_FRect left_black_rect_ = {
play_area_.x,
param.game.game_area.center_y - 1,
0,
2};
SDL_FRect right_black_rect_ = {
play_area_.x + play_area_.w,
param.game.game_area.center_y - 1,
0,
2};
// Barras negras para efecto letterbox
SDL_FRect top_black_rect_ = {
play_area_.x,
param.game.game_area.rect.y,
play_area_.w,
black_bars_size_};
SDL_FRect bottom_black_rect_ = {
play_area_.x,
param.game.game_area.rect.h - black_bars_size_,
play_area_.w,
black_bars_size_};
SDL_FRect left_black_rect_ = {
play_area_.x,
param.game.game_area.center_y - 1,
0,
2};
SDL_FRect right_black_rect_ = {
play_area_.x + play_area_.w,
param.game.game_area.center_y - 1,
0,
2};
// Borde para la ventana
SDL_FRect red_rect = play_area_; // Delimitador de ventana
// Borde para la ventana
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
// --- Métodos del bucle principal ---
void update(); // Actualización principal de la lógica
void render(); // Renderizado de la escena
void checkEvents(); // Manejo de eventos
void checkInput(); // Procesamiento de entrada
// --- Métodos del bucle principal ---
void update(); // Actualización principal de la lógica
void render(); // Renderizado de la escena
void checkEvents(); // Manejo de eventos
void checkInput(); // Procesamiento de entrada
// --- Métodos de renderizado ---
void fillTextTexture(); // Crear textura de texto de créditos
void fillCanvas(); // Renderizar todos los sprites y fondos
void updateTextureDstRects(); // Actualizar destinos de texturas
void renderPlayers(); // Renderiza los jugadores
// --- Métodos de renderizado ---
void fillTextTexture(); // Crear textura de texto de créditos
void fillCanvas(); // Renderizar todos los sprites y fondos
void updateTextureDstRects(); // Actualizar destinos de texturas
void renderPlayers(); // Renderiza los jugadores
// --- Métodos de lógica del juego ---
void throwBalloons(); // Lanzar globos al escenario
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(); // Actualza los jugadores
// --- Métodos de lógica del juego ---
void throwBalloons(); // Lanzar globos al escenario
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(); // Actualza los jugadores
// --- Métodos de interfaz ---
void updateBlackRects(); // Actualizar rectángulos negros (letterbox)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
// --- Métodos de interfaz ---
void updateBlackRects(); // Actualizar rectángulos negros (letterbox)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
// --- Métodos de audio ---
void setVolume(int amount); // Establecer volumen
void resetVolume(); // Restablecer volumen
// --- Métodos de audio ---
void setVolume(int amount); // Establecer volumen
void resetVolume(); // Restablecer volumen
};

View File

@@ -1,9 +1,9 @@
#include "game.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para find_if, clamp, find, min
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
#include <iterator> // Para distance, size
@@ -283,7 +283,7 @@ void Game::updateGameStateGameOver() {
cleanVectors();
if (game_over_counter_ > 0) {
if (game_over_counter_ == GAME_OVER_COUNTER_) {
if (game_over_counter_ == GAME_OVER_COUNTER) {
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
Audio::get()->fadeOutMusic(1000);
balloon_manager_->setBouncingSounds(true);
@@ -367,7 +367,7 @@ void Game::updateGameStateCompleted() {
if (game_completed_counter_ == END_CELEBRATIONS) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->IsEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
player->setPlayingState(player->isEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
}
}
}
@@ -399,7 +399,7 @@ void Game::destroyAllItems() {
}
// Comprueba la colisión entre el jugador y los globos activos
std::shared_ptr<Balloon> Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) {
auto Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon> {
for (auto &balloon : balloon_manager_->getBalloons()) {
if (!balloon->isInvulnerable() && !balloon->isPowerBall()) {
if (checkCollision(player->getCollider(), balloon->getCollider())) {
@@ -594,7 +594,7 @@ void Game::renderItems() {
}
// Devuelve un item al azar y luego segun sus probabilidades
ItemType Game::dropItem() {
auto Game::dropItem() -> ItemType {
const auto LUCKY_NUMBER = rand() % 100;
const auto ITEM = rand() % 6;
@@ -621,7 +621,7 @@ ItemType Game::dropItem() {
break;
case 4:
if (LUCKY_NUMBER < helper_.item_coffee_odds) {
helper_.item_coffee_odds = ITEM_COFFEE_ODDS_;
helper_.item_coffee_odds = ITEM_COFFEE_ODDS;
return ItemType::COFFEE;
} else {
if (helper_.need_coffee) {
@@ -631,7 +631,7 @@ ItemType Game::dropItem() {
break;
case 5:
if (LUCKY_NUMBER < helper_.item_coffee_machine_odds) {
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS_;
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS;
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) {
return ItemType::COFFEE_MACHINE;
}
@@ -786,7 +786,7 @@ void Game::handlePlayerCollision(std::shared_ptr<Player> &player) {
screen_->shake();
playSound("voice_no.wav");
player->setPlayingState(PlayerState::ROLLING);
players_to_reorder.push_back(player);
players_to_reorder_.push_back(player);
if (allPlayersAreNotPlaying()) {
// No se puede subir poder de fase si no hay nadie jugando
Stage::power_can_be_added = false;
@@ -928,7 +928,7 @@ void Game::render() {
void Game::enableTimeStopItem() {
balloon_manager_->stopAllBalloons();
balloon_manager_->reverseColorsToAllBalloons();
time_stopped_counter_ = TIME_STOPPED_COUNTER_;
time_stopped_counter_ = TIME_STOPPED_COUNTER;
}
// Deshabilita el efecto del item de detener el tiempo
@@ -960,8 +960,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
// Recorrido para el texto de "Last Stage!" o de "X stages left" o "Game Over" (2,3)
@@ -972,8 +972,8 @@ void Game::initPaths() {
const int Y1 = param.game.play_area.center_y - H / 2;
const int Y2 = -H;
const int X = param.game.play_area.center_x;
paths_.emplace_back(Path(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20));
paths_.emplace_back(Path(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0));
paths_.emplace_back(createPath(Y0, Y1, PathType::VERTICAL, X, 80, easeOutQuint), 20);
paths_.emplace_back(createPath(Y1, Y2, PathType::VERTICAL, X, 80, easeInQuint), 0);
}
// Recorrido para el texto de "Congratulations!!" (3,4)
@@ -985,8 +985,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = param.game.play_area.rect.w;
const int Y = param.game.play_area.center_y - H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
// Recorrido para el texto de "1.000.000 points!" (5,6)
@@ -998,8 +998,8 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - W / 2;
const int X2 = -W;
const int Y = param.game.play_area.center_y + H / 2 - 20;
paths_.emplace_back(Path(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400));
paths_.emplace_back(Path(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0));
paths_.emplace_back(createPath(X0, X1, PathType::HORIZONTAL, Y, 80, easeOutQuint), 400);
paths_.emplace_back(createPath(X1, X2, PathType::HORIZONTAL, Y, 80, easeInQuint), 0);
}
}
@@ -1021,7 +1021,7 @@ void Game::updateHelper() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreWaitingOrGameOver() {
auto Game::allPlayersAreWaitingOrGameOver() -> bool {
auto success = true;
for (const auto &player : players_)
success &= player->isWaiting() || player->isGameOver();
@@ -1030,7 +1030,7 @@ bool Game::allPlayersAreWaitingOrGameOver() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreGameOver() {
auto Game::allPlayersAreGameOver() -> bool {
auto success = true;
for (const auto &player : players_)
success &= player->isGameOver();
@@ -1039,7 +1039,7 @@ bool Game::allPlayersAreGameOver() {
}
// Comprueba si todos los jugadores han terminado de jugar
bool Game::allPlayersAreNotPlaying() {
auto Game::allPlayersAreNotPlaying() -> bool {
auto success = true;
for (const auto &player : players_)
success &= !player->isPlaying();
@@ -1131,7 +1131,7 @@ void Game::checkPlayersStatusPlaying() {
}
// Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Game::getPlayer(int id) {
auto Game::getPlayer(int id) -> std::shared_ptr<Player> {
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
if (it != players_.end()) {
@@ -1141,7 +1141,7 @@ std::shared_ptr<Player> Game::getPlayer(int id) {
}
// Obtiene un controlador a partir del "id" del jugador
int Game::getController(int player_id) {
auto Game::getController(int player_id) -> int {
auto it = std::find_if(Options::controllers.begin(), Options::controllers.end(), [player_id](const auto &controller) { return controller.player_id == player_id; });
if (it != Options::controllers.end()) {
@@ -1158,12 +1158,12 @@ void Game::checkInput() {
// Comprueba las entradas si no está el menú de servicio activo
if (!ServiceMenu::get()->isEnabled()) {
checkPauseInput();
demo_.enabled ? DEMO_handlePassInput() : handlePlayersInput();
demo_.enabled ? demoHandlePassInput() : handlePlayersInput();
}
// Mueve los jugadores en el modo demo
if (demo_.enabled) {
DEMO_handleInput();
demoHandleInput();
}
// Verifica los inputs globales.
@@ -1188,7 +1188,7 @@ void Game::checkPauseInput() {
}
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void Game::DEMO_handlePassInput() {
void Game::demoHandlePassInput() {
if (input_->checkAnyButton()) {
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
@@ -1197,19 +1197,19 @@ void Game::DEMO_handlePassInput() {
}
// Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void Game::DEMO_handleInput() {
void Game::demoHandleInput() {
int index = 0;
for (const auto &player : players_) {
if (player->isPlaying()) {
// Maneja el input específico del jugador en modo demo.
DEMO_handlePlayerInput(player, index);
demoHandlePlayerInput(player, index);
}
++index;
}
}
// Procesa las entradas para un jugador específico durante el modo demo.
void Game::DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index) {
void Game::demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index) {
const auto &demo_data = demo_.data[index][demo_.counter];
if (demo_data.left == 1) {
@@ -1721,10 +1721,10 @@ void Game::playSound(const std::string &name) {
// Organiza los jugadores para que los vivos se pinten sobre los muertos
void Game::movePlayersToFront() {
if (players_to_reorder.empty())
if (players_to_reorder_.empty())
return;
for (auto &player : players_to_reorder) {
for (auto &player : players_to_reorder_) {
auto it = std::find(players_.begin(), players_.end(), player);
if (it != players_.end() && it != players_.begin()) {
std::shared_ptr<Player> dying_player = *it;
@@ -1732,7 +1732,7 @@ void Game::movePlayersToFront() {
players_.insert(players_.begin(), dying_player);
}
}
players_to_reorder.clear();
players_to_reorder_.clear();
}
// Comprueba si está activo el menu de servicio para poner el juego en pausa

View File

@@ -39,13 +39,13 @@ constexpr int TOTAL_SCORE_DATA = 3;
class Game {
public:
// Constructor
Game(int playerID, int current_stage, bool demo);
Game(int player_id, int current_stage, bool demo);
// Destructor
~Game();
// Destructor
~Game();
// Bucle principal del juego
void run();
// Bucle principal del juego
void run();
private:
// --- Tipos internos ---
@@ -59,43 +59,40 @@ class Game {
};
// --- Constantes internas ---
static constexpr int HELP_COUNTER_ = 1000;
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
static constexpr int GAME_COMPLETED_END_ = 700;
static constexpr int GAME_OVER_COUNTER_ = 350;
static constexpr int TIME_STOPPED_COUNTER_ = 360;
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
static constexpr int ITEM_CLOCK_ODDS_ = 5;
static constexpr int ITEM_COFFEE_ODDS_ = 5;
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
static constexpr int HELP_COUNTER = 1000;
static constexpr int GAME_COMPLETED_START_FADE = 500;
static constexpr int GAME_COMPLETED_END = 700;
static constexpr int GAME_OVER_COUNTER = 350;
static constexpr int TIME_STOPPED_COUNTER = 360;
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
static constexpr int ITEM_CLOCK_ODDS = 5;
static constexpr int ITEM_COFFEE_ODDS = 5;
static constexpr int ITEM_POWER_BALL_ODDS = 0;
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
// --- Estructuras ---
struct Helper {
bool need_coffee; // Indica si se necesitan cafes
bool need_coffee_machine; // Indica si se necesita PowerUp
bool need_power_ball; // Indica si se necesita una PowerBall
int counter; // Contador para no dar ayudas consecutivas
int item_disk_odds; // Probabilidad de aparición del objeto
int item_gavina_odds; // Probabilidad de aparición del objeto
int item_pacmar_odds; // Probabilidad de aparición del objeto
int item_clock_odds; // Probabilidad de aparición del objeto
int item_coffee_odds; // Probabilidad de aparición del objeto
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
bool need_coffee{false}; // Indica si se necesitan cafes
bool need_coffee_machine{false}; // Indica si se necesita PowerUp
bool need_power_ball{false}; // Indica si se necesita una PowerBall
int counter; // Contador para no dar ayudas consecutivas
int item_disk_odds; // Probabilidad de aparición del objeto
int item_gavina_odds; // Probabilidad de aparición del objeto
int item_pacmar_odds; // Probabilidad de aparición del objeto
int item_clock_odds; // Probabilidad de aparición del objeto
int item_coffee_odds; // Probabilidad de aparición del objeto
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
Helper()
: need_coffee(false),
need_coffee_machine(false),
need_power_ball(false),
counter(HELP_COUNTER_),
item_disk_odds(ITEM_POINTS_1_DISK_ODDS_),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS_),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS_),
item_clock_odds(ITEM_CLOCK_ODDS_),
item_coffee_odds(ITEM_COFFEE_ODDS_),
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
Helper()
: counter(HELP_COUNTER),
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
item_clock_odds(ITEM_CLOCK_ODDS),
item_coffee_odds(ITEM_COFFEE_ODDS),
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
};
// --- Objetos y punteros ---
@@ -144,13 +141,13 @@ class Game {
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
int counter_ = 0; // Contador para el juego
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
int game_over_counter_ = GAME_OVER_COUNTER_; // Contador para el estado de fin de partida
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
int menace_current_ = 0; // Nivel de amenaza actual
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
GameState state_ = GameState::FADE_IN; // Estado
std::vector<std::shared_ptr<Player>> players_to_reorder;
std::vector<std::shared_ptr<Player>> players_to_reorder_;
#ifdef DEBUG
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
@@ -170,7 +167,7 @@ class Game {
void updateStage(); // Comprueba si hay cambio de fase y actualiza las variables
void updateGameStateGameOver(); // Actualiza el estado de fin de la partida
void destroyAllItems(); // Destruye todos los items
std::shared_ptr<Balloon> checkPlayerBalloonCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los globos activos
auto checkPlayerBalloonCollision(std::shared_ptr<Player> &player) -> std::shared_ptr<Balloon>; // Comprueba la colisión entre el jugador y los globos activos
void checkPlayerItemCollision(std::shared_ptr<Player> &player); // Comprueba la colisión entre el jugador y los items
void checkBulletCollision(); // Comprueba y procesa la colisión de las balas
void updateBullets(); // Mueve las balas activas
@@ -179,7 +176,7 @@ class Game {
void freeBullets(); // Vacia el vector de balas
void updateItems(); // Actualiza los items
void renderItems(); // Pinta los items activos
ItemType dropItem(); // Devuelve un item en función del azar
auto dropItem() -> ItemType; // Devuelve un item en función del azar
void createItem(ItemType type, float x, float y); // Crea un objeto item
void freeItems(); // Vacia el vector de items
void createItemText(int x, std::shared_ptr<Texture> texture); // Crea un objeto PathSprite
@@ -198,26 +195,26 @@ class Game {
void enableTimeStopItem(); // Habilita el efecto del item de detener el tiempo
void disableTimeStopItem(); // Deshabilita el efecto del item de detener el tiempo
void updateHelper(); // Actualiza las variables de ayuda
bool allPlayersAreWaitingOrGameOver(); // Comprueba si todos los jugadores han terminado de jugar
bool allPlayersAreGameOver(); // Comprueba si todos los jugadores han terminado de jugar
bool allPlayersAreNotPlaying(); // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreWaitingOrGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreGameOver() -> bool; // Comprueba si todos los jugadores han terminado de jugar
auto allPlayersAreNotPlaying() -> bool; // Comprueba si todos los jugadores han terminado de jugar
void updateScoreboard(); // Actualiza el marcador
void fillCanvas(); // Dibuja los elementos de la zona de juego en su textura
void pause(bool value); // Pausa el juego
void addScoreToScoreBoard(const std::shared_ptr<Player> &player); // Añade una puntuación a la tabla de records
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
int getController(int playerId); // Obtiene un controlador a partir del "id" del jugador
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
auto getController(int player_id) -> int; // Obtiene un controlador a partir del "id" del jugador
void checkInput(); // Gestiona la entrada durante el juego
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
void DEMO_handleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void DEMO_handlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bulletType); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
void initDemo(int player_id); // Inicializa las variables para el modo DEMO

View File

@@ -1,9 +1,9 @@
#include "hiscore_table.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para max
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
#include <vector> // Para vector
@@ -32,7 +32,7 @@ HiScoreTable::HiScoreTable()
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
fade_(std::make_unique<Fade>()),
background_(std::make_unique<Background>()),
counter_(0),
ticks_(0),
view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
fade_mode_(FadeMode::IN),
@@ -168,7 +168,7 @@ void HiScoreTable::updateFade() {
}
// Convierte un entero a un string con separadores de miles
std::string HiScoreTable::format(int number) {
auto HiScoreTable::format(int number) -> std::string {
const std::string SEPARATOR = ".";
const std::string SCORE = std::to_string(number);
@@ -341,7 +341,7 @@ void HiScoreTable::initBackground() {
}
// Obtiene un color del vector de colores de entradas
Color HiScoreTable::getEntryColor(int counter) {
auto HiScoreTable::getEntryColor(int counter) -> Color {
int cycle_length = entry_colors_.size() * 2 - 2;
size_t n = counter % cycle_length;
@@ -383,7 +383,7 @@ void HiScoreTable::updateCounter() {
background_->setAlpha(96);
}
if (counter_ == COUNTER_END_) {
if (counter_ == COUNTER_END) {
fade_->activate();
}
}

View File

@@ -39,40 +39,40 @@ class HiScoreTable {
private:
// --- Constantes ---
static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
std::vector<Path> paths_; // Vector con los recorridos precalculados
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
std::vector<Path> paths_; // Vector con los recorridos precalculados
// --- Variables ---
Uint16 counter_ = 0; // Contador
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
// --- Variables ---
Uint16 counter_ = 0; // Contador
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
std::string format(int number); // Convierte un entero a un string con separadores de miles
void fillTexture(); // Dibuja los sprites en la textura
void updateFade(); // Gestiona el fade
void createSprites(); // Crea los sprites con los textos
void updateSprites(); // Actualiza las posiciones de los sprites de texto
void initFade(); // Inicializa el fade
void initBackground(); // Inicializa el fondo
Color getEntryColor(int counter_); // Obtiene un color del vector de colores de entradas
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
void fillTexture(); // Dibuja los sprites en la textura
void updateFade(); // Gestiona el fade
void createSprites(); // Crea los sprites con los textos
void updateSprites(); // Actualiza las posiciones de los sprites de texto
void initFade(); // Inicializa el fade
void initBackground(); // Inicializa el fondo
auto getEntryColor(int counter) -> Color; // Obtiene un color del vector de colores de entradas
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador
};

View File

@@ -279,7 +279,7 @@ void Instructions::run() {
}
// Método para inicializar las líneas
std::vector<Line> Instructions::initializeLines(int height) {
auto Instructions::initializeLines(int height) -> std::vector<Line> {
std::vector<Line> lines;
for (int y = 0; y < height; y++) {
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
@@ -289,17 +289,17 @@ std::vector<Line> Instructions::initializeLines(int height) {
}
// Método para mover las líneas con suavizado
bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) {
auto Instructions::moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool {
Uint32 current_time = SDL_GetTicks();
bool all_lines_off_screen = true;
for (auto &line : lines) {
// Establecer startTime en el primer cuadro de animación
if (line.startTime == 0) {
line.startTime = current_time + line.y * start_delay;
// Establecer start_time en el primer cuadro de animación
if (line.start_time == 0) {
line.start_time = current_time + line.y * start_delay;
}
float elapsed_time = (current_time - line.startTime) / 1000.0f; // Convertir a segundos
float elapsed_time = (current_time - line.start_time) / 1000.0f; // Convertir a segundos
if (elapsed_time < 0) {
all_lines_off_screen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
continue;

View File

@@ -29,11 +29,11 @@ struct Line {
int y; // Coordenada Y de la línea
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
Uint32 startTime; // Tiempo de inicio del movimiento
Uint32 start_time{0}; // Tiempo de inicio del movimiento
// Constructor de Line
Line(int y, float x, int direction)
: y(y), x(x), direction(direction), startTime(0) {}
: y(y), x(x), direction(direction) {}
};
// Clase Instructions
@@ -80,8 +80,8 @@ class Instructions {
void fillBackbuffer(); // Rellena el backbuffer
void iniSprites(); // Inicializa los sprites de los items
void updateSprites(); // Actualiza los sprites
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay); // Mueve las líneas
auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
void updateBackbuffer(); // Gestiona la textura con los gráficos
};

View File

@@ -46,14 +46,14 @@ Logo::Logo()
}
// Inicializa el vector de colores
color_.push_back(Color(0x00, 0x00, 0x00)); // Black
color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
color_.emplace_back(0x00, 0x00, 0x00); // Black
color_.emplace_back(0x00, 0x00, 0xd8); // Blue
color_.emplace_back(0xd8, 0x00, 0x00); // Red
color_.emplace_back(0xd8, 0x00, 0xd8); // Magenta
color_.emplace_back(0x00, 0xd8, 0x00); // Green
color_.emplace_back(0x00, 0xd8, 0xd8); // Cyan
color_.emplace_back(0xd8, 0xd8, 0x00); // Yellow
color_.emplace_back(0xFF, 0xFF, 0xFF); // Bright white
}
// Destructor

View File

@@ -1,9 +1,9 @@
#include "title.h"
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_EventType
#include <stddef.h> // Para size_t
#include <algorithm> // Para find_if
#include <cstddef> // Para size_t
#include <iostream> // Para basic_ostream, basic_ostream::operator<<
#include <string> // Para basic_string, char_traits, operator+
#include <vector> // Para vector
@@ -408,11 +408,11 @@ void Title::updateStartPrompt() {
}
}
should_render_start_prompt = condition_met;
should_render_start_prompt_ = condition_met;
}
void Title::renderStartPrompt() {
if (should_render_start_prompt) {
if (should_render_start_prompt_) {
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
param.game.game_area.center_x,
param.title.press_start_position,
@@ -513,7 +513,7 @@ void Title::renderPlayers() {
}
// Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Title::getPlayer(int id) {
auto Title::getPlayer(int id) -> std::shared_ptr<Player> {
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; });
if (it != players_.end()) {

View File

@@ -67,7 +67,7 @@ class Title {
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
int num_controllers_; // Número de mandos conectados
TitleState state_; // Estado actual de la sección
bool should_render_start_prompt = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
bool should_render_start_prompt_ = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2
@@ -92,5 +92,5 @@ class Title {
void initPlayers(); // Inicializa los jugadores
void renderPlayers(); // Renderiza los jugadores
void updatePlayers(); // Actualza los jugadores
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
auto getPlayer(int id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
};

View File

@@ -19,10 +19,10 @@ class SmartSprite : public AnimatedSprite {
void render() override; // Dibuja el sprite
// --- Getters ---
int getDestX() const { return dest_x_; } // Obtiene la posición de destino en X
int getDestY() const { return dest_y_; } // Obtiene la posición de destino en Y
bool isOnDestination() const { return on_destination_; } // Indica si está en el destino
bool hasFinished() const { return finished_; } // Indica si ya ha terminado
auto getDestX() const -> int { return dest_x_; } // Obtiene la posición de destino en X
auto getDestY() const -> int { return dest_y_; } // Obtiene la posición de destino en Y
auto isOnDestination() const -> bool { return on_destination_; } // Indica si está en el destino
auto hasFinished() const -> bool { return finished_; } // Indica si ya ha terminado
// --- Setters ---
void setFinishedCounter(int value) { finished_counter_ = value; } // Establece el contador para deshabilitarlo

View File

@@ -1,20 +1,22 @@
#include "sprite.h"
#include <utility>
#include "texture.h" // Para Texture
// Constructor
Sprite::Sprite(std::shared_ptr<Texture> texture, float pos_x, float pos_y, float width, float height)
: texture_(texture),
: texture_(std::move(texture)),
pos_((SDL_FRect){pos_x, pos_y, width, height}),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_FRect rect)
: texture_(texture),
: texture_(std::move(texture)),
pos_(rect),
sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture),
: texture_(std::move(texture)),
pos_(SDL_FRect{0, 0, static_cast<float>(texture_->getWidth()), static_cast<float>(texture_->getHeight())}),
sprite_clip_(pos_) {}

View File

@@ -12,21 +12,21 @@ int number = 0; // Fase actual
bool power_can_be_added = true; // Habilita la recolecta de poder
// Devuelve una fase
Stage get(int index) { return stages.at(std::min(9, index)); }
auto get(int index) -> Stage { return stages.at(std::min(9, index)); }
// Inicializa las variables del namespace Stage
void init() {
stages.clear();
stages.emplace_back(Stage(200, 7 + (4 * 1), 7 + (4 * 3)));
stages.emplace_back(Stage(300, 7 + (4 * 2), 7 + (4 * 4)));
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
stages.emplace_back(Stage(600, 7 + (4 * 3), 7 + (4 * 5)));
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
stages.emplace_back(Stage(600, 7 + (4 * 4), 7 + (4 * 6)));
stages.emplace_back(Stage(650, 7 + (4 * 5), 7 + (4 * 7)));
stages.emplace_back(Stage(750, 7 + (4 * 5), 7 + (4 * 7)));
stages.emplace_back(Stage(850, 7 + (4 * 6), 7 + (4 * 8)));
stages.emplace_back(Stage(950, 7 + (4 * 7), 7 + (4 * 10)));
stages.emplace_back(200, 7 + (4 * 1), 7 + (4 * 3));
stages.emplace_back(300, 7 + (4 * 2), 7 + (4 * 4));
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
stages.emplace_back(600, 7 + (4 * 3), 7 + (4 * 5));
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
stages.emplace_back(600, 7 + (4 * 4), 7 + (4 * 6));
stages.emplace_back(650, 7 + (4 * 5), 7 + (4 * 7));
stages.emplace_back(750, 7 + (4 * 5), 7 + (4 * 7));
stages.emplace_back(850, 7 + (4 * 6), 7 + (4 * 8));
stages.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10));
power = 0;
total_power = 0;

View File

@@ -27,7 +27,7 @@ extern int number; // Índice de la fase actual
extern bool power_can_be_added; // Indica si se puede añadir poder a la fase
// --- Funciones principales ---
Stage get(int index); // Devuelve una fase por índice
auto get(int index) -> Stage; // Devuelve una fase por índice
void init(); // Inicializa las variables del namespace Stage
void addPower(int amount); // Añade poder a la fase actual
} // namespace Stage

View File

@@ -1,8 +1,8 @@
#include "text.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_GetRenderTarget, Uint8
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <fstream> // Para basic_ifstream, basic_istream, basic_ostream
#include <iostream> // Para cerr
#include <stdexcept> // Para runtime_error
@@ -13,14 +13,14 @@
#include "utils.h" // Para Color, getFileName, printWithDots
// Llena una estructuta TextFile desde un fichero
std::shared_ptr<TextFile> loadTextFile(const std::string &file_path) {
auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile> {
auto tf = std::make_shared<TextFile>();
// Inicializa a cero el vector con las coordenadas
for (int i = 0; i < 128; ++i) {
tf->offset[i].x = 0;
tf->offset[i].y = 0;
tf->offset[i].w = 0;
for (auto &i : tf->offset) {
i.x = 0;
i.y = 0;
i.w = 0;
tf->box_width = 0;
tf->box_height = 0;
}
@@ -141,7 +141,7 @@ void Text::write2X(int x, int y, const std::string &text, int kerning) {
}
// Escribe el texto en una textura
std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom, int kerning) {
auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = lenght(text, kerning) * zoom;
@@ -159,7 +159,7 @@ std::shared_ptr<Texture> Text::writeToTexture(const std::string &text, int zoom,
}
// Escribe el texto con extras en una textura
std::shared_ptr<Texture> Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) {
auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = Text::lenght(text, kerning) + shadow_distance;
@@ -230,7 +230,7 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
}
// Obtiene la longitud en pixels de una cadena
int Text::lenght(const std::string &text, int kerning) const {
auto Text::lenght(const std::string &text, int kerning) const -> int {
int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
shift += (offset_[static_cast<int>(text[i])].w + kerning);
@@ -240,7 +240,7 @@ int Text::lenght(const std::string &text, int kerning) const {
}
// Devuelve el valor de la variable
int Text::getCharacterSize() const {
auto Text::getCharacterSize() const -> int {
return box_width_;
}

View File

@@ -2,23 +2,24 @@
#include "texture.h"
#include <SDL3/SDL.h> // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_...
#include <stdint.h> // Para uint32_t
#include <cstdint> // Para uint32_t
#include <cstring> // Para memcpy
#include <fstream> // Para basic_ifstream, basic_istream, basic_ios
#include <sstream> // Para basic_istringstream
#include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, char_traits, operator+, string
#include <vector> // Para vector
#include <utility>
#include <vector> // Para vector
#include "external/gif.h" // Para Gif
#include "stb_image.h" // Para stbi_image_free, stbi_load, STBI_rgb_alpha
#include "utils.h" // Para getFileName, Color, printWithDots
// Constructor
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
Texture::Texture(SDL_Renderer *renderer, std::string path)
: renderer_(renderer),
path_(path) {
path_(std::move(path)) {
// Carga el fichero en la textura
if (!path_.empty()) {
// Obtiene la extensión
@@ -53,7 +54,7 @@ Texture::~Texture() {
}
// Carga una imagen desde un fichero
bool Texture::loadFromFile(const std::string &file_path) {
auto Texture::loadFromFile(const std::string &file_path) -> bool {
if (file_path.empty())
return false;
@@ -106,7 +107,7 @@ bool Texture::loadFromFile(const std::string &file_path) {
}
// Crea una textura en blanco
bool Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) {
auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool {
// Crea una textura sin inicializar
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) {
@@ -179,22 +180,22 @@ void Texture::setAsRenderTarget(SDL_Renderer *renderer) {
}
// Obtiene el ancho de la imagen
int Texture::getWidth() {
auto Texture::getWidth() -> int {
return width_;
}
// Obtiene el alto de la imagen
int Texture::getHeight() {
auto Texture::getHeight() -> int {
return height_;
}
// Recarga la textura
bool Texture::reLoad() {
auto Texture::reLoad() -> bool {
return loadFromFile(path_);
}
// Obtiene la textura
SDL_Texture *Texture::getSDLTexture() {
auto Texture::getSDLTexture() -> SDL_Texture * {
return texture_;
}
@@ -206,7 +207,7 @@ void Texture::unloadSurface() {
}
// Crea una surface desde un fichero .gif
std::shared_ptr<Surface> Texture::loadSurface(const std::string &file_path) {
auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surface> {
// Libera la superficie actual
unloadSurface();
@@ -277,7 +278,7 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color) {
}
// Carga una paleta desde un fichero
Palette Texture::loadPaletteFromFile(const std::string &file_path) {
auto Texture::loadPaletteFromFile(const std::string &file_path) -> Palette {
Palette palette;
// Abrir el archivo GIF
@@ -337,10 +338,10 @@ void Texture::setPalette(size_t palette) {
}
// Obtiene el renderizador
SDL_Renderer *Texture::getRenderer() { return renderer_; }
auto Texture::getRenderer() -> SDL_Renderer * { return renderer_; }
// Carga una paleta desde un archivo .pal
Palette Texture::readPalFile(const std::string &file_path) {
auto Texture::readPalFile(const std::string &file_path) -> Palette {
Palette palette{};
palette.fill(0); // Inicializar todo con 0 (transparente por defecto)

View File

@@ -1,11 +1,11 @@
#pragma once
#include <SDL3/SDL.h> // Para Uint8, SDL_Renderer, Uint16, SDL_FlipMode, SDL_PixelFormat, SDL_TextureAccess, SDL_Texture, Uint32, SDL_BlendMode, SDL_FPoint, SDL_FRect
#include <stddef.h> // Para size_t
#include <array> // Para array
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <array> // Para array
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr
#include <string> // Para string, basic_string
#include <utility>
#include <vector> // Para vector
@@ -28,54 +28,54 @@ struct Surface {
class Texture {
public:
// --- Constructores y destructor ---
explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
~Texture();
explicit Texture(SDL_Renderer *renderer, std::string path = std::string());
~Texture();
// --- Carga y creación ---
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
auto reLoad() -> bool; // Recarga la textura
// --- Carga y creación ---
auto loadFromFile(const std::string &path) -> bool; // Carga una imagen desde un fichero
auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco
auto reLoad() -> bool; // Recarga la textura
// --- Renderizado ---
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
// --- Renderizado ---
void render(int x, int y, SDL_FRect *clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint *center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico
void setAsRenderTarget(SDL_Renderer *renderer); // Establece la textura como objetivo de renderizado
// --- Modificadores de color y blending ---
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
void setColor(Color color); // Establece el color para la modulación
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
// --- Modificadores de color y blending ---
void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulación
void setColor(Color color); // Establece el color para la modulación
void setBlendMode(SDL_BlendMode blending); // Establece el blending
void setAlpha(Uint8 alpha); // Establece el alpha para la modulación
// --- Paletas ---
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
void setPalette(size_t palette); // Cambia la paleta de la textura
// --- Paletas ---
void addPaletteFromGifFile(const std::string &path); // Añade una paleta a la lista
void addPaletteFromPalFile(const std::string &path); // Añade una paleta a la lista
void setPaletteColor(int palette, int index, Uint32 color); // Establece un color de la paleta
void setPalette(size_t palette); // Cambia la paleta de la textura
// --- Getters ---
auto getWidth() -> int; // Obtiene el ancho de la imagen
auto getHeight() -> int; // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
// --- Getters ---
auto getWidth() -> int; // Obtiene el ancho de la imagen
auto getHeight() -> int; // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
SDL_Texture *texture_ = nullptr; // La textura
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
SDL_Texture *texture_ = nullptr; // La textura
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imágenes en formato gif con paleta
// --- Variables ---
std::string path_; // Ruta de la imagen de la textura
int width_ = 0; // Ancho de la imagen
int height_ = 0; // Alto de la imagen
std::vector<Palette> palettes_; // Vector con las diferentes paletas
int current_palette_ = 0; // Índice de la paleta en uso
// --- Variables ---
std::string path_; // Ruta de la imagen de la textura
int width_ = 0; // Ancho de la imagen
int height_ = 0; // Alto de la imagen
std::vector<Palette> palettes_; // Vector con las diferentes paletas
int current_palette_ = 0; // Índice de la paleta en uso
// --- Métodos internos ---
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
void flipSurface(); // Vuelca la surface en la textura
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
void unloadTexture(); // Libera la memoria de la textura
void unloadSurface(); // Libera la surface actual
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
// --- Métodos internos ---
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
void flipSurface(); // Vuelca la surface en la textura
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
void unloadTexture(); // Libera la memoria de la textura
void unloadSurface(); // Libera la surface actual
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
};

View File

@@ -1,10 +1,11 @@
#include "tiled_bg.h"
#include <SDL3/SDL.h> // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_De...
#include <stdlib.h> // Para rand
#include <cmath> // Para sin
#include <memory> // Para unique_ptr, make_unique
#include <cmath> // Para sin
#include <cstdlib> // Para rand
#include <memory> // Para unique_ptr, make_unique
#include <numbers>
#include <string> // Para basic_string
#include "resource.h" // Para Resource
@@ -41,7 +42,7 @@ TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode)
// Inicializa los valores del vector con los valores del seno
for (int i = 0; i < 360; ++i) {
sin_[i] = std::sin(i * 3.14159 / 180.0); // Convierte grados a radianes y calcula el seno
sin_[i] = std::sin(i * std::numbers::pi / 180.0); // Convierte grados a radianes y calcula el seno
}
}
@@ -53,20 +54,20 @@ TiledBG::~TiledBG() {
// Rellena la textura con el contenido
void TiledBG::fillTexture() {
// Crea los objetos para pintar en la textura de fondo
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH_, TILE_HEIGHT_});
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH, TILE_HEIGHT});
// Prepara para dibujar sobre la textura
auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, canvas_);
// Rellena la textura con el tile
const auto I_MAX = pos_.w * 2 / TILE_WIDTH_;
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT_;
tile->setSpriteClip(0, 0, TILE_WIDTH_, TILE_HEIGHT_);
const auto I_MAX = pos_.w * 2 / TILE_WIDTH;
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT;
tile->setSpriteClip(0, 0, TILE_WIDTH, TILE_HEIGHT);
for (int i = 0; i < I_MAX; ++i) {
for (int j = 0; j < J_MAX; ++j) {
tile->setX(i * TILE_WIDTH_);
tile->setY(j * TILE_HEIGHT_);
tile->setX(i * TILE_WIDTH);
tile->setY(j * TILE_HEIGHT);
tile->render();
}
}
@@ -88,8 +89,8 @@ void TiledBG::update() {
switch (mode_) {
case TiledBGMode::DIAGONAL: {
// El tileado de fondo se desplaza en diagonal
window_.x = static_cast<int>(desp_) % TILE_WIDTH_;
window_.y = static_cast<int>(desp_) % TILE_HEIGHT_;
window_.x = static_cast<int>(desp_) % TILE_WIDTH;
window_.y = static_cast<int>(desp_) % TILE_HEIGHT;
break;
}
@@ -112,7 +113,7 @@ void TiledBG::updateStop() {
const int UMBRAL = 20 * speed_; // Ajusta este valor según la precisión deseada
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
if (window_.x >= TILE_WIDTH_ - UMBRAL) {
if (window_.x >= TILE_WIDTH - UMBRAL) {
speed_ /= 1.05f; // Reduce gradualmente la velocidad
// Asegura que no baje demasiado

View File

@@ -35,28 +35,28 @@ class TiledBG {
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
// --- Getters ---
bool isStopped() const { return speed_ == 0.0f; } // Indica si está parado
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0f; } // Indica si está parado
private:
private:
// --- Constantes ---
static constexpr int TILE_WIDTH_ = 64; // Ancho del tile
static constexpr int TILE_HEIGHT_ = 64; // Alto del tile
static constexpr int TILE_WIDTH = 64; // Ancho del tile
static constexpr int TILE_HEIGHT = 64; // Alto del tile
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
// --- Variables de estado ---
SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados
float desp_ = 0.0f; // Desplazamiento aplicado
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
bool stopping_ = false; // Indica si se está deteniendo
// --- Variables de estado ---
SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados
float desp_ = 0.0f; // Desplazamiento aplicado
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
bool stopping_ = false; // Indica si se está deteniendo
// --- Métodos internos ---
void fillTexture(); // Rellena la textura con el contenido
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
void updateStop(); // Detiene el desplazamiento de forma ordenada
// --- Métodos internos ---
void fillTexture(); // Rellena la textura con el contenido
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
void updateStop(); // Detiene el desplazamiento de forma ordenada
};

View File

@@ -26,21 +26,21 @@ class MenuOption {
virtual ~MenuOption() = default;
const std::string &getCaption() const { return caption_; }
ServiceMenu::SettingsGroup getGroup() const { return group_; }
bool isHidden() const { return hidden_; }
[[nodiscard]] auto getCaption() const -> const std::string & { return caption_; }
[[nodiscard]] auto getGroup() const -> ServiceMenu::SettingsGroup { return group_; }
[[nodiscard]] auto isHidden() const -> bool { return hidden_; }
void setHidden(bool hidden) { hidden_ = hidden; }
virtual Behavior getBehavior() const = 0;
virtual std::string getValueAsString() const { return ""; }
[[nodiscard]] virtual auto getBehavior() const -> Behavior = 0;
[[nodiscard]] virtual auto getValueAsString() const -> std::string { return ""; }
virtual void adjustValue(bool adjust_up) {}
virtual ServiceMenu::SettingsGroup getTargetGroup() const { return ServiceMenu::SettingsGroup::MAIN; }
[[nodiscard]] virtual auto getTargetGroup() const -> ServiceMenu::SettingsGroup { return ServiceMenu::SettingsGroup::MAIN; }
virtual void executeAction() {}
// Método virtual para que cada opción calcule el ancho de su valor más largo.
virtual int getMaxValueWidth(Text *text_renderer) const { return 0; }
virtual auto getMaxValueWidth(Text *text_renderer) const -> int { return 0; }
protected:
protected:
std::string caption_;
ServiceMenu::SettingsGroup group_;
bool hidden_;
@@ -53,14 +53,14 @@ class BoolOption : public MenuOption {
BoolOption(const std::string &cap, ServiceMenu::SettingsGroup grp, bool *var)
: MenuOption(cap, grp), linked_variable_(var) {}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override {
return *linked_variable_ ? Lang::getText("[SERVICE_MENU] ON") : Lang::getText("[SERVICE_MENU] OFF");
}
void adjustValue(bool /*adjust_up*/) override {
*linked_variable_ = !*linked_variable_;
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
return std::max(
text_renderer->lenght(Lang::getText("[SERVICE_MENU] ON"), -2),
text_renderer->lenght(Lang::getText("[SERVICE_MENU] OFF"), -2));
@@ -75,13 +75,13 @@ class IntOption : public MenuOption {
IntOption(const std::string &cap, ServiceMenu::SettingsGroup grp, int *var, int min, int max, int step)
: MenuOption(cap, grp), linked_variable_(var), min_value_(min), max_value_(max), step_value_(step) {}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override { return std::to_string(*linked_variable_); }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override { return std::to_string(*linked_variable_); }
void adjustValue(bool adjust_up) override {
int newValue = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(newValue, min_value_, max_value_);
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
int max_width = 0;
// Iterar por todos los valores posibles en el rango
@@ -100,14 +100,13 @@ class IntOption : public MenuOption {
class ListOption : public MenuOption {
public:
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
: MenuOption(cap, grp),
value_list_(std::move(values)),
getter_(std::move(current_value_getter)),
setter_(std::move(new_value_setter)),
list_index_(0) {
sync();
}
ListOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::vector<std::string> values, std::function<std::string()> current_value_getter, std::function<void(const std::string &)> new_value_setter)
: MenuOption(cap, grp),
value_list_(std::move(values)),
getter_(std::move(current_value_getter)),
setter_(std::move(new_value_setter)) {
sync();
}
void sync() {
std::string current_value = getter_();
@@ -119,8 +118,8 @@ class ListOption : public MenuOption {
}
}
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::ADJUST; }
[[nodiscard]] auto getValueAsString() const -> std::string override {
return value_list_.empty() ? "" : value_list_[list_index_];
}
void adjustValue(bool adjust_up) override {
@@ -131,7 +130,7 @@ class ListOption : public MenuOption {
: (list_index_ + size - 1) % size;
setter_(value_list_[list_index_]);
}
int getMaxValueWidth(Text *text_renderer) const override {
auto getMaxValueWidth(Text *text_renderer) const -> int override {
int max_w = 0;
for (const auto &val : value_list_) {
max_w = std::max(max_w, text_renderer->lenght(val, -2));
@@ -143,7 +142,7 @@ class ListOption : public MenuOption {
std::vector<std::string> value_list_;
std::function<std::string()> getter_;
std::function<void(const std::string &)> setter_;
size_t list_index_;
size_t list_index_{0};
};
class FolderOption : public MenuOption {
@@ -151,10 +150,10 @@ class FolderOption : public MenuOption {
FolderOption(const std::string &cap, ServiceMenu::SettingsGroup grp, ServiceMenu::SettingsGroup target)
: MenuOption(cap, grp), target_group_(target) {}
Behavior getBehavior() const override { return Behavior::SELECT; }
ServiceMenu::SettingsGroup getTargetGroup() const override { return target_group_; }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
[[nodiscard]] auto getTargetGroup() const -> ServiceMenu::SettingsGroup override { return target_group_; }
private:
private:
ServiceMenu::SettingsGroup target_group_;
};
@@ -163,7 +162,7 @@ class ActionOption : public MenuOption {
ActionOption(const std::string &cap, ServiceMenu::SettingsGroup grp, std::function<void()> action, bool hidden = false)
: MenuOption(cap, grp, hidden), action_(std::move(action)) {}
Behavior getBehavior() const override { return Behavior::SELECT; }
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
void executeAction() override {
if (action_)
action_();

View File

@@ -37,7 +37,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
// Dibuja la línea separadora
y = rect_.y + upper_height_;
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y);
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y);
// Dibuja las opciones
y = options_y_;
@@ -47,8 +47,8 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, option_pairs.at(i).first, current_color, -2);
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ - element_text_->lenght(option_pairs.at(i).second, -2);
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, option_pairs.at(i).first, current_color, -2);
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING - element_text_->lenght(option_pairs.at(i).second, -2);
element_text_->writeColored(X, y, option_pairs.at(i).second, current_color, -2);
} else {
element_text_->writeDX(TEXT_CENTER | TEXT_COLOR, rect_.x + rect_.w / 2, y, option_pairs.at(i).first, -2, current_color);
@@ -96,11 +96,11 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
lower_padding_ = (options_padding_ * 3);
lower_height_ = ((max_entries > 0 ? max_entries - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
width_ = ServiceMenu::MIN_WIDTH_;
width_ = ServiceMenu::MIN_WIDTH;
height_ = upper_height_ + lower_height_;
}
SDL_FRect MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) {
auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect {
width_ = getMenuWidthForGroup(menu_state->getCurrentGroup());
const auto &display_options = menu_state->getDisplayOptions();
lower_height_ = ((display_options.size() > 0 ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
@@ -151,7 +151,7 @@ void MenuRenderer::updateResizeAnimation() {
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
for (int &w : group_menu_widths_)
w = ServiceMenu::MIN_WIDTH_;
w = ServiceMenu::MIN_WIDTH;
for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0;
@@ -164,15 +164,15 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
max_value_width = std::max(max_value_width, option->getMaxValueWidth(element_text_.get()));
}
}
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ * 2);
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE_ + max_value_width;
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width;
}
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH_, (int)total_width);
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width);
}
}
int MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const {
auto MenuRenderer::getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int {
return group_menu_widths_[static_cast<int>(group)];
}
@@ -185,12 +185,12 @@ void MenuRenderer::updateColorCounter() {
}
}
Color MenuRenderer::getAnimatedSelectedColor() {
auto MenuRenderer::getAnimatedSelectedColor() -> Color {
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
return color_cycle_.at(color_counter_ % color_cycle_.size());
}
SDL_FRect MenuRenderer::setRect(SDL_FRect rect) {
auto MenuRenderer::setRect(SDL_FRect rect) -> SDL_FRect {
border_rect_ = {rect.x - 1, rect.y + 1, rect.w + 2, rect.h - 2};
return rect;
}

View File

@@ -1,10 +1,10 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect, Uint32
#include <stddef.h> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector
#include "ui/service_menu.h" // Para ServiceMenu
#include "utils.h" // Para Color
@@ -26,9 +26,9 @@ class MenuRenderer {
void setLayout(const ServiceMenu *menu_state);
// Getters
const SDL_FRect &getRect() const { return rect_; }
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
private:
private:
// --- Referencias a los renderizadores de texto ---
std::shared_ptr<Text> element_text_;
std::shared_ptr<Text> title_text_;
@@ -60,13 +60,13 @@ class MenuRenderer {
// --- Métodos privados de la vista ---
void setAnchors(const ServiceMenu *menu_state);
SDL_FRect calculateNewRect(const ServiceMenu *menu_state);
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void updateResizeAnimation();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
int getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const;
Color getAnimatedSelectedColor();
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
auto getAnimatedSelectedColor() -> Color;
void updateColorCounter();
SDL_FRect setRect(SDL_FRect rect);
auto setRect(SDL_FRect rect) -> SDL_FRect;
};

View File

@@ -13,10 +13,10 @@
#include "utils.h" // Para Zone
// Singleton
ServiceMenu *ServiceMenu::instance_ = nullptr;
void ServiceMenu::init() { ServiceMenu::instance_ = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance_; }
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance_; }
ServiceMenu *ServiceMenu::instance = nullptr;
void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance; }
auto ServiceMenu::get() -> ServiceMenu * { return ServiceMenu::instance; }
// Constructor
ServiceMenu::ServiceMenu()
@@ -106,7 +106,13 @@ void ServiceMenu::selectOption() {
return;
if (current_settings_group_ == SettingsGroup::MAIN)
main_menu_selected_ = selected_;
auto &selected_option = display_options_.at(selected_);
auto *selected_option = display_options_.at(selected_);
if (!selected_option) {
// This shouldn't happen in normal operation, but protects against null pointer
return;
}
if (auto folder = dynamic_cast<FolderOption *>(selected_option)) {
previous_settings_group_ = current_settings_group_;
current_settings_group_ = folder->getTargetGroup();
@@ -150,7 +156,7 @@ void ServiceMenu::updateOptionPairs() {
void ServiceMenu::updateMenu() {
title_ = settingsGroupToString(current_settings_group_);
AdjustListValues();
adjustListValues();
// Actualiza las opciones visibles
updateDisplayOptions();
@@ -184,7 +190,7 @@ void ServiceMenu::applySettingsSettings() {
setHiddenOptions();
}
MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
auto ServiceMenu::getOptionByCaption(const std::string &caption) const -> MenuOption * {
for (const auto &option : options_) {
if (option->getCaption() == caption) {
return option.get();
@@ -195,7 +201,7 @@ MenuOption *ServiceMenu::getOptionByCaption(const std::string &caption) const {
// --- Getters y otros ---
ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
auto ServiceMenu::getCurrentGroupAlignment() const -> ServiceMenu::GroupAlignment {
switch (current_settings_group_) {
case SettingsGroup::VIDEO:
case SettingsGroup::AUDIO:
@@ -206,7 +212,7 @@ ServiceMenu::GroupAlignment ServiceMenu::getCurrentGroupAlignment() const {
}
}
size_t ServiceMenu::countOptionsInGroup(SettingsGroup group) const {
auto ServiceMenu::countOptionsInGroup(SettingsGroup group) const -> size_t {
size_t count = 0;
for (const auto &option : options_) {
if (option->getGroup() == group && !option->isHidden()) {
@@ -254,7 +260,7 @@ void ServiceMenu::initializeOptions() {
}
// Sincroniza los valores de las opciones tipo lista
void ServiceMenu::AdjustListValues() {
void ServiceMenu::adjustListValues() {
for (auto &option : options_) {
if (auto list_option = dynamic_cast<ListOption *>(option.get())) {
list_option->sync();
@@ -269,7 +275,7 @@ void ServiceMenu::playSelectSound() { Audio::get()->playSound("service_menu_sele
void ServiceMenu::playBackSound() { Audio::get()->playSound("service_menu_select.wav", Audio::Group::INTERFACE); }
// Devuelve el nombre del grupo como string para el título
std::string ServiceMenu::settingsGroupToString(SettingsGroup group) const {
auto ServiceMenu::settingsGroupToString(SettingsGroup group) const -> std::string {
switch (group) {
case SettingsGroup::MAIN:
return Lang::getText("[SERVICE_MENU] TITLE");

View File

@@ -1,7 +1,6 @@
#pragma once
#include <stddef.h> // Para size_t
#include <cstddef> // Para size_t
#include <memory> // Para unique_ptr
#include <string> // Para basic_string, string
#include <utility> // Para pair
@@ -28,13 +27,13 @@ class ServiceMenu {
};
// --- Constantes públicas que el Renderer podría necesitar ---
static constexpr size_t OPTIONS_HORIZONTAL_PADDING_ = 20;
static constexpr size_t MIN_WIDTH_ = 240;
static constexpr size_t MIN_GAP_OPTION_VALUE_ = 30;
static constexpr size_t OPTIONS_HORIZONTAL_PADDING = 20;
static constexpr size_t MIN_WIDTH = 240;
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
static void init();
static void destroy();
static ServiceMenu *get();
static auto get() -> ServiceMenu *;
void toggle();
void render();
@@ -49,17 +48,17 @@ class ServiceMenu {
void moveBack();
// --- Getters para que el Renderer pueda leer el estado ---
bool isEnabled() const { return enabled_; }
const std::string &getTitle() const { return title_; }
SettingsGroup getCurrentGroup() const { return current_settings_group_; }
GroupAlignment getCurrentGroupAlignment() const;
const std::vector<MenuOption *> &getDisplayOptions() const { return display_options_; }
const std::vector<std::unique_ptr<MenuOption>> &getAllOptions() const { return options_; }
size_t getSelectedIndex() const { return selected_; }
const std::vector<std::pair<std::string, std::string>> &getOptionPairs() const { return option_pairs_; }
size_t countOptionsInGroup(SettingsGroup group) const;
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
[[nodiscard]] auto getTitle() const -> const std::string & { return title_; }
[[nodiscard]] auto getCurrentGroup() const -> SettingsGroup { return current_settings_group_; }
[[nodiscard]] auto getCurrentGroupAlignment() const -> GroupAlignment;
[[nodiscard]] auto getDisplayOptions() const -> const std::vector<MenuOption *> & { return display_options_; }
[[nodiscard]] auto getAllOptions() const -> const std::vector<std::unique_ptr<MenuOption>> & { return options_; }
[[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; }
[[nodiscard]] auto getOptionPairs() const -> const std::vector<std::pair<std::string, std::string>> & { return option_pairs_; }
[[nodiscard]] auto countOptionsInGroup(SettingsGroup group) const -> size_t;
private:
private:
// --- Lógica de estado del menú (Modelo) ---
bool enabled_ = false;
std::vector<std::unique_ptr<MenuOption>> options_;
@@ -88,19 +87,19 @@ class ServiceMenu {
void applyVideoSettings();
void applyAudioSettings();
void applySettingsSettings();
MenuOption *getOptionByCaption(const std::string &caption) const;
void AdjustListValues();
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
void adjustListValues();
void playMoveSound();
void playAdjustSound();
void playSelectSound();
void playBackSound();
std::string settingsGroupToString(SettingsGroup group) const;
[[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string;
void setHiddenOptions();
// --- Singleton ---
ServiceMenu();
~ServiceMenu() = default;
ServiceMenu(const ServiceMenu &) = delete;
ServiceMenu &operator=(const ServiceMenu &) = delete;
static ServiceMenu *instance_;
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
static ServiceMenu *instance;
};

View File

@@ -1,19 +1,20 @@
#include "ui_message.h"
#include <cmath> // Para pow
#include <utility>
#include "text.h" // Para TEXT_CENTER, TEXT_COLOR, Text
// Constructor: inicializa el renderizador, el texto y el color del mensaje
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color)
: text_renderer_(text_renderer), text_(message_text), color_(color) {}
UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color)
: text_renderer_(std::move(text_renderer)), text_(std::move(message_text)), color_(color) {}
// Muestra el mensaje en la posición base_x, base_y con animación de entrada desde arriba
void UIMessage::show() {
if (visible_ && target_y_ == 0.0f)
return; // Ya está visible y quieto
start_y_ = DESP_; // Empieza 8 píxeles arriba de la posición base
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
target_y_ = 0.0f; // La posición final es la base
y_offset_ = start_y_;
anim_step_ = 0;
@@ -27,7 +28,7 @@ void UIMessage::hide() {
return;
start_y_ = y_offset_; // Comienza desde la posición actual
target_y_ = DESP_; // Termina 8 píxeles arriba de la base
target_y_ = DESP; // Termina 8 píxeles arriba de la base
anim_step_ = 0;
animating_ = true;
}
@@ -76,7 +77,7 @@ void UIMessage::render() {
}
// Devuelve true si el mensaje está visible actualmente
bool UIMessage::isVisible() const {
auto UIMessage::isVisible() const -> bool {
return visible_;
}

View File

@@ -11,25 +11,25 @@ class Text;
class UIMessage {
public:
// Constructor: recibe el renderizador de texto, el mensaje y el color
UIMessage(std::shared_ptr<Text> text_renderer, const std::string &message_text, const Color &color);
UIMessage(std::shared_ptr<Text> text_renderer, std::string message_text, const Color &color);
// Muestra el mensaje con animación de entrada
void show();
// Muestra el mensaje con animación de entrada
void show();
// Oculta el mensaje con animación de salida
void hide();
// Oculta el mensaje con animación de salida
void hide();
// Actualiza el estado de la animación (debe llamarse cada frame)
void update();
// Actualiza el estado de la animación (debe llamarse cada frame)
void update();
// Dibuja el mensaje en pantalla si está visible
void render();
// Dibuja el mensaje en pantalla si está visible
void render();
// Indica si el mensaje está visible actualmente
bool isVisible() const;
// Indica si el mensaje está visible actualmente
[[nodiscard]] auto isVisible() const -> bool;
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
void setPosition(float new_base_x, float new_base_y);
// Permite actualizar la posición del mensaje (por ejemplo, si el menú se mueve)
void setPosition(float new_base_x, float new_base_y);
private:
// --- Configuración ---
@@ -49,7 +49,7 @@ class UIMessage {
float target_y_ = 0.0f; // Posición Y objetivo de la animación
int anim_step_ = 0; // Paso actual de la animación
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
static constexpr float DESP_ = -8.0f; // Distancia a desplazarse
static constexpr float DESP = -8.0f; // Distancia a desplazarse
// Actualiza la interpolación de la animación (ease out/in cubic)
void updateAnimation();

View File

@@ -67,7 +67,7 @@ void Writer::setEnabled(bool value) {
}
// Obtiene el valor de la variable
bool Writer::IsEnabled() const {
auto Writer::isEnabled() const -> bool {
return enabled_;
}
@@ -82,6 +82,6 @@ void Writer::center(int x) {
}
// Obtiene el valor de la variable
bool Writer::hasFinished() const {
auto Writer::hasFinished() const -> bool {
return finished_;
}

View File

@@ -2,6 +2,7 @@
#include <memory> // Para shared_ptr
#include <string> // Para string
#include <utility>
class Text;
@@ -9,33 +10,33 @@ class Text;
class Writer {
public:
// Constructor
explicit Writer(std::shared_ptr<Text> text)
: text_(text) {}
explicit Writer(std::shared_ptr<Text> text)
: text_(std::move(text)) {}
// Destructor
~Writer() = default;
// Destructor
~Writer() = default;
// Actualiza el objeto
void update();
// Actualiza el objeto
void update();
// Dibuja el objeto en pantalla
void render() const;
// Dibuja el objeto en pantalla
void render() const;
// Setters
void setPosX(int value); // Establece la posición X
void setPosY(int value); // Establece la posición Y
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
void setCaption(const std::string &text); // Establece el texto a escribir
void setSpeed(int value); // Establece la velocidad de escritura
void setEnabled(bool value); // Habilita o deshabilita el objeto
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
// Setters
void setPosX(int value); // Establece la posición X
void setPosY(int value); // Establece la posición Y
void setKerning(int value); // Establece el kerning (espaciado entre caracteres)
void setCaption(const std::string &text); // Establece el texto a escribir
void setSpeed(int value); // Establece la velocidad de escritura
void setEnabled(bool value); // Habilita o deshabilita el objeto
void setFinishedCounter(int time); // Establece el temporizador para deshabilitar el objeto
// Centra la cadena de texto a un punto X
void center(int x);
// Centra la cadena de texto a un punto X
void center(int x);
// Getters
bool IsEnabled() const; // Indica si el objeto está habilitado
bool hasFinished() const; // Indica si ya ha terminado
// Getters
[[nodiscard]] auto isEnabled() const -> bool; // Indica si el objeto está habilitado
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ya ha terminado
private:
// --- Objetos y punteros ---