diff --git a/.clang-tidy b/.clang-tidy index f07142a..8d4f776 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,6 @@ Checks: > - readability-identifier-naming + readability-identifier-naming, + modernize-* WarningsAsErrors: '*' # Solo incluir archivos de tu código fuente diff --git a/source/background.h b/source/background.h index ab66576..b89d36c 100644 --- a/source/background.h +++ b/source/background.h @@ -1,10 +1,10 @@ #pragma once #include // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer -#include // Para size_t -#include // Para unique_ptr, shared_ptr -#include // Para vector +#include // Para size_t +#include // Para unique_ptr, shared_ptr +#include // Para vector #include "utils.h" // Para Color diff --git a/source/balloon.h b/source/balloon.h index 5fed9e1..3294579 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -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; } diff --git a/source/balloon_formations.h b/source/balloon_formations.h index 8208fb3..7f03192 100644 --- a/source/balloon_formations.h +++ b/source/balloon_formations.h @@ -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 balloon_formation_; // Vector con todas las formaciones enemigas std::vector balloon_formation_pool_; // Conjuntos de formaciones enemigas diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 6d1c171..6211437 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -1,8 +1,7 @@ #include "balloon_manager.h" -#include // Para rand - #include // Para remove_if +#include // Para rand #include // 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 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 { if (can_deploy_balloons_) { const int INDEX = static_cast(size); balloons_.emplace_back(std::make_shared(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) { +auto BalloonManager::popBalloon(std::shared_ptr balloon) -> int { Stage::addPower(1); int score = 0; @@ -255,7 +254,7 @@ int BalloonManager::popBalloon(std::shared_ptr balloon) { } // Explosiona un globo. Lo destruye = no crea otros globos -int BalloonManager::destroyBalloon(std::shared_ptr &balloon) { +auto BalloonManager::destroyBalloon(std::shared_ptr &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) { } // 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(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(rand() % 4); + const auto SIZE = static_cast(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); }); } diff --git a/source/balloon_manager.h b/source/balloon_manager.h index 4ceab00..b50429f 100644 --- a/source/balloon_manager.h +++ b/source/balloon_manager.h @@ -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 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; // Crea un nuevo globo void createChildBalloon(const std::shared_ptr &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); // Explosiona un globo, creando otros si aplica - int destroyBalloon(std::shared_ptr &balloon); // Explosiona un globo sin crear otros - int destroyAllBalloons(); // Destruye todos los globos + auto popBalloon(std::shared_ptr balloon) -> int; // Explosiona un globo, creando otros si aplica + auto destroyBalloon(std::shared_ptr &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_; // Objeto para gestionar explosiones std::unique_ptr balloon_formations_; // Objeto para manejar formaciones enemigas diff --git a/source/bullet.cpp b/source/bullet.cpp index f169bd4..ed3931c 100644 --- a/source/bullet.cpp +++ b/source/bullet.cpp @@ -46,13 +46,13 @@ 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(); @@ -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_; } diff --git a/source/bullet.h b/source/bullet.h index 9280f77..1cce1df 100644 --- a/source/bullet.h +++ b/source/bullet.h @@ -34,17 +34,17 @@ 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; @@ -64,5 +64,5 @@ class Bullet { // 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 + auto move() -> BulletMoveStatus; // Mueve la bala y devuelve su estado }; diff --git a/source/define_buttons.cpp b/source/define_buttons.cpp index a62b815..dc949cc 100644 --- a/source/define_buttons.cpp +++ b/source/define_buttons.cpp @@ -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; diff --git a/source/define_buttons.h b/source/define_buttons.h index e7f7ce2..9ebd0f3 100644 --- a/source/define_buttons.h +++ b/source/define_buttons.h @@ -1,10 +1,11 @@ #pragma once #include // Para SDL_GamepadButton, SDL_Event, SDL_GamepadButtonEvent -#include // Para size_t -#include // Para shared_ptr -#include // Para basic_string, string +#include // Para size_t +#include // Para shared_ptr +#include // Para basic_string, string +#include #include // 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_; // 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 }; diff --git a/source/director.cpp b/source/director.cpp index 3e9db30..e5a9cb8 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -2,12 +2,12 @@ #include "director.h" #include // Para SDL_Scancode, SDL_GamepadButton -#include // Para errno, EEXIST, EACCES, ENAMETOOLONG -#include // Para printf, perror #include // Para mkdir, stat, S_IRWXU #include // Para getuid #include // Para min +#include // Para errno, EEXIST, EACCES, ENAMETOOLONG +#include // Para printf, perror #include // Para exit, EXIT_FAILURE, size_t, srand #include // Para time #include // 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) { diff --git a/source/director.h b/source/director.h index 725b00a..52e0821 100644 --- a/source/director.h +++ b/source/director.h @@ -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 diff --git a/source/enter_name.cpp b/source/enter_name.cpp index cc6e53f..f923b3d 100644 --- a/source/enter_name.cpp +++ b/source/enter_name.cpp @@ -1,8 +1,7 @@ #include "enter_name.h" -#include // Para size_t -#include // Para rand - +#include // Para size_t +#include // Para rand #include // 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 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(); diff --git a/source/enter_name.h b/source/enter_name.h index ab7da80..4a32ea3 100644 --- a/source/enter_name.h +++ b/source/enter_name.h @@ -1,9 +1,8 @@ #pragma once -#include // Para size_t - -#include // Para array -#include // Para string, basic_string +#include // Para array +#include // Para size_t +#include // 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 }; \ No newline at end of file diff --git a/source/explosions.cpp b/source/explosions.cpp index f9a67a6..fe93644 100644 --- a/source/explosions.cpp +++ b/source/explosions.cpp @@ -23,7 +23,7 @@ void Explosions::render() { // Añade texturas al objeto void Explosions::addTexture(int size, std::shared_ptr texture, const std::vector &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; diff --git a/source/explosions.h b/source/explosions.h index 45c5fa0..5a88de7 100644 --- a/source/explosions.h +++ b/source/explosions.h @@ -2,6 +2,7 @@ #include // Para unique_ptr, shared_ptr #include // Para string +#include #include // Para vector #include "animated_sprite.h" // Para AnimatedSprite @@ -15,7 +16,7 @@ struct ExplosionTexture { std::vector animation; // Animación para la textura ExplosionTexture(int sz, std::shared_ptr tex, const std::vector &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; }; \ No newline at end of file diff --git a/source/external/json.hpp b/source/external/json.hpp index d4a35b4..82d69f7 100644 --- a/source/external/json.hpp +++ b/source/external/json.hpp @@ -6059,7 +6059,7 @@ inline void to_json(BasicJsonType& j, const std::pair& p) j = { p.first, p.second }; } -// Para https://github.com/nlohmann/json/pull/1134 +// for https://github.com/nlohmann/json/pull/1134 template>::value, int> = 0> inline void to_json(BasicJsonType& j, const T& b) @@ -6624,7 +6624,7 @@ class iterator_input_adapter return char_traits::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 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::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 #include // input_iterator_tag, iterator_traits #include // allocator -#include // Para out_of_range +#include // for out_of_range #include // enable_if, is_convertible #include // pair #include // 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 +/// for use within nlohmann::basic_json template , class Allocator = std::allocator>> struct ordered_map : std::vector, Allocator> diff --git a/source/fade.cpp b/source/fade.cpp index 5dc90b4..0d7a68d 100644 --- a/source/fade.cpp +++ b/source/fade.cpp @@ -1,9 +1,9 @@ #include "fade.h" #include // Para SDL_SetRenderTarget, SDL_FRect, SDL_GetRenderT... -#include // Para rand, size_t #include // Para min, max +#include // 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; } diff --git a/source/fade.h b/source/fade.h index 4d4fad2..1327074 100644 --- a/source/fade.h +++ b/source/fade.h @@ -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 }; \ No newline at end of file diff --git a/source/game_logo.cpp b/source/game_logo.cpp index 684984d..a8ce57e 100644 --- a/source/game_logo.cpp +++ b/source/game_logo.cpp @@ -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_; diff --git a/source/game_logo.h b/source/game_logo.h index 8c0de32..e50be7c 100644 --- a/source/game_logo.h +++ b/source/game_logo.h @@ -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 }; \ No newline at end of file diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index 20a854e..ea66ba7 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -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()) diff --git a/source/global_inputs.h b/source/global_inputs.h index 2c08b7b..dcd7e6e 100644 --- a/source/global_inputs.h +++ b/source/global_inputs.h @@ -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 \ No newline at end of file diff --git a/source/input.cpp b/source/input.cpp index 3591192..860df5a 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -1,9 +1,9 @@ #include "input.h" #include // Para SDL_LogInfo, SDL_LogCategory, SDL_GetGamepa... -#include // Para size_t #include // Para find +#include // Para size_t #include // Para distance #include // Para unordered_map, _Node_const_iterator, operat... #include // Para pair @@ -18,11 +18,11 @@ void Input::init(const std::string &game_controller_db_path) { 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(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(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(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 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 --- diff --git a/source/input.h b/source/input.h index 821088a..5b3360f 100644 --- a/source/input.h +++ b/source/input.h @@ -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,10 +139,10 @@ 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 --- diff --git a/source/item.cpp b/source/item.cpp index 77b3b0f..0cb44d7 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -1,8 +1,7 @@ #include "item.h" -#include // Para rand - #include // Para clamp +#include // 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; diff --git a/source/item.h b/source/item.h index c8389e0..abc44e6 100644 --- a/source/item.h +++ b/source/item.h @@ -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 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; }; diff --git a/source/lang.cpp b/source/lang.cpp index 83a5845..b2fe9b5 100644 --- a/source/lang.cpp +++ b/source/lang.cpp @@ -1,7 +1,6 @@ #include "lang.h" -#include // Para size_t - +#include // Para size_t #include // Para exception #include // Para basic_ifstream, basic_istream, ifstream #include // Para unordered_map, _Node_iterator, operator== @@ -24,7 +23,7 @@ std::vector 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); diff --git a/source/main.cpp b/source/main.cpp index 7b51514..a64d0b0 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -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(argc, const_cast(argv)); diff --git a/source/manage_hiscore_table.cpp b/source/manage_hiscore_table.cpp index 0defb99..a7846ec 100644 --- a/source/manage_hiscore_table.cpp +++ b/source/manage_hiscore_table.cpp @@ -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"); diff --git a/source/manage_hiscore_table.h b/source/manage_hiscore_table.h index 7eff9a2..a938a21 100644 --- a/source/manage_hiscore_table.h +++ b/source/manage_hiscore_table.h @@ -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 &table_; diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp index 430fb20..0991e99 100644 --- a/source/moving_sprite.cpp +++ b/source/moving_sprite.cpp @@ -23,8 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos) MovingSprite::MovingSprite(std::shared_ptr texture) : Sprite(texture), - x_(0.0f), - y_(0.0f), + rotate_(Rotate()), zoom_w_(1.0f), zoom_h_(1.0f), diff --git a/source/notifier.cpp b/source/notifier.cpp index 8eaa238..b7eee1d 100644 --- a/source/notifier.cpp +++ b/source/notifier.cpp @@ -4,7 +4,8 @@ #include // Para remove_if #include // Para basic_string, string -#include // Para vector +#include +#include // Para vector #include "audio.h" // Para Audio #include "param.h" // Para Param, param, ParamNotification, ParamGame @@ -23,13 +24,13 @@ void Notifier::init(const std::string &icon_file, std::shared_ptr text) { 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) : renderer_(Screen::get()->getRenderer()), icon_texture_(!icon_file.empty() ? std::make_unique(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 Notifier::getCodes() { +auto Notifier::getCodes() -> std::vector { std::vector codes; for (const auto ¬ification : notifications_) { codes.emplace_back(notification.code); diff --git a/source/notifier.h b/source/notifier.h index cfcea70..403e659 100644 --- a/source/notifier.h +++ b/source/notifier.h @@ -18,7 +18,7 @@ class Notifier { // --- Métodos de singleton --- static void init(const std::string &icon_file, std::shared_ptr 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,11 +26,11 @@ class Notifier { // --- Gestión de notificaciones --- void show(std::vector 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 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; // 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; @@ -52,17 +52,17 @@ class Notifier { std::shared_ptr texture; // Textura de la notificación std::shared_ptr sprite; // Sprite asociado std::vector texts; // Textos a mostrar - int counter; // Contador de tiempo - NotificationStatus state; // Estado de la notificación - NotificationShape shape; // Forma de la notificación + 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; // Posición vertical - int travel_dist; // Distancia a recorrer + 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("") {} + : texture(nullptr), sprite(nullptr), texts(), rect{0, 0, 0, 0}, code("") {} }; // --- Objetos y punteros --- diff --git a/source/options.cpp b/source/options.cpp index 7ef88ce..5687b15 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -28,7 +28,7 @@ std::vector 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; diff --git a/source/options.h b/source/options.h index c6e3516..c207686 100644 --- a/source/options.h +++ b/source/options.h @@ -3,6 +3,7 @@ #include // Para SDL_GamepadButton, SDL_ScaleMode #include // Para string, basic_string +#include #include // 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 hi_score_table; // Tabla de mejores puntuaciones - std::vector 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 hi_score_table; // Tabla de mejores puntuaciones + std::vector 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 inputs; // Listado de acciones asignadas std::vector 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 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 \ No newline at end of file diff --git a/source/param.cpp b/source/param.cpp index 40a6e86..e200242 100644 --- a/source/param.cpp +++ b/source/param.cpp @@ -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; diff --git a/source/path_sprite.cpp b/source/path_sprite.cpp index 2a5cd7d..f1ce965 100644 --- a/source/path_sprite.cpp +++ b/source/path_sprite.cpp @@ -6,7 +6,7 @@ #include // Para move // Devuelve un vector con los puntos que conforman la ruta -std::vector createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function) { +auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function) -> std::vector { std::vector v; v.reserve(steps); @@ -141,4 +141,4 @@ void PathSprite::goToNextPathOrDie() { } // Indica si ha terminado todos los recorridos -bool PathSprite::hasFinished() { return has_finished_; } \ No newline at end of file +auto PathSprite::hasFinished() -> bool { return has_finished_; } \ No newline at end of file diff --git a/source/path_sprite.h b/source/path_sprite.h index 033f1f5..a797e2b 100644 --- a/source/path_sprite.h +++ b/source/path_sprite.h @@ -37,7 +37,7 @@ struct Path { }; // Devuelve un vector con los puntos que conforman la ruta -std::vector createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function); +auto createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function &easing_function) -> std::vector; // --- Clase PathSprite: Sprite que sigue uno o varios recorridos --- class PathSprite : public Sprite { @@ -58,12 +58,12 @@ class PathSprite : public Sprite { // --- 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 diff --git a/source/player.cpp b/source/player.cpp index 8b05b64..9cdeb6f 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -1,9 +1,9 @@ #include "player.h" #include // Para SDL_GetTicks, SDL_FlipMode, SDL_FRect -#include // Para rand #include // Para clamp, max, min +#include // Para rand #include "animated_sprite.h" // Para AnimatedSprite #include "asset.h" // Para Asset @@ -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(); } diff --git a/source/player.h b/source/player.h index b2653f0..d86c056 100644 --- a/source/player.h +++ b/source/player.h @@ -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(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(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; } @@ -226,6 +226,6 @@ class Player { 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(); } + [[nodiscard]] auto isRenderable() const -> bool { return !isWaiting() && !isGameOver() && !isTitleHidden(); } void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records }; \ No newline at end of file diff --git a/source/resource.cpp b/source/resource.cpp index 86929f1..aa7dc95 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,11 +1,12 @@ #include "resource.h" #include // Para SDL_LogInfo, SDL_LogCategory, SDL_L... -#include // Para exit #include // Para find_if #include // Para array +#include // Para exit #include // Para runtime_error +#include #include "asset.h" // Para Asset, AssetType #include "external/jail_audio.h" // Para JA_DeleteMusic, JA_DeleteSound, JA_... @@ -27,7 +28,7 @@ void Resource::init() { Resource::instance = new Resource(); } 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 Resource::getTexture(const std::string &name) { +auto Resource::getTexture(const std::string &name) -> std::shared_ptr { 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 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 Resource::getTextFile(const std::string &name) { +auto Resource::getTextFile(const std::string &name) -> std::shared_ptr { 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 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 Resource::getText(const std::string &name) { +auto Resource::getText(const std::string &name) -> std::shared_ptr { 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 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(Screen::get()->getRenderer(), l))); + textures_.emplace_back(name, std::make_shared(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)); } } @@ -263,8 +264,8 @@ void Resource::createTextures() { 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 ]"); } } @@ -307,8 +308,8 @@ void Resource::createText() { 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(getTexture(resource.texture_file), getTextFile(resource.text_file)))); + texts_.emplace_back(resource.key, std::make_shared(getTexture(resource.texture_file), getTextFile(resource.text_file))); printWithDots("Text : ", resource.key, "[ DONE ]"); } } diff --git a/source/resource.h b/source/resource.h index cd1019e..bbb6232 100644 --- a/source/resource.h +++ b/source/resource.h @@ -1,10 +1,10 @@ #pragma once #include // Para SDL_FRect -#include // Para size_t -#include // Para shared_ptr -#include // Para basic_string, string +#include // Para size_t +#include // Para shared_ptr +#include // Para basic_string, string #include #include // Para vector diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 3aacec4..67c2097 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -1,8 +1,8 @@ #include "scoreboard.h" #include // Para SDL_DestroyTexture, SDL_SetRenderDrawColor -#include // Para roundf +#include // Para roundf #include // Para operator<<, setfill, setw #include // Para basic_ostringstream, basic_ostream, basic_os... @@ -29,7 +29,7 @@ void Scoreboard::destroy() { } // [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él -Scoreboard *Scoreboard::get() { +auto Scoreboard::get() -> Scoreboard * { return Scoreboard::instance; } @@ -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); } diff --git a/source/scoreboard.h b/source/scoreboard.h index 3e0ceef..dce60b2 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -1,11 +1,11 @@ #pragma once #include // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64 -#include // Para size_t -#include // Para shared_ptr, unique_ptr -#include // Para basic_string, string -#include // Para vector +#include // Para size_t +#include // Para shared_ptr, unique_ptr +#include // Para basic_string, string +#include // 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 @@ -103,7 +103,7 @@ class Scoreboard { // --- 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 + 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 diff --git a/source/screen.h b/source/screen.h index d753cf9..ef2e6a5 100644 --- a/source/screen.h +++ b/source/screen.h @@ -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 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 { return text_; } // Obtiene el puntero al texto de Screen #ifdef DEBUG // --- Debug --- @@ -66,13 +66,13 @@ class Screen { // --- Estructuras internas --- struct FPS { - Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar. - int frame_count; // Número acumulado de frames en el intervalo. - int last_value; // Número de frames calculado en el último segundo. + 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), frame_count(0), last_value(0) {} + FPS() {} void increment() { frame_count++; } - int calculate(Uint32 current_ticks) { + auto calculate(Uint32 current_ticks) -> int { if (current_ticks - ticks >= 1000) { last_value = frame_count; frame_count = 0; @@ -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 @@ -156,7 +156,7 @@ class Screen { } } - bool isEnabled() const { return enabled; } + [[nodiscard]] auto isEnabled() const -> bool { return enabled; } }; #ifdef DEBUG @@ -193,7 +193,7 @@ class Screen { std::shared_ptr 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 diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index 11013ec..b68edf2 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -451,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(UPPER_LIMIT); - static float g_ = static_cast(LOWER_LIMIT); - static float b_ = static_cast(LOWER_LIMIT); + static auto r_ = static_cast(UPPER_LIMIT); + static auto g_ = static_cast(LOWER_LIMIT); + static auto b_ = static_cast(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; diff --git a/source/sections/game.cpp b/source/sections/game.cpp index dd95a2d..9cae56f 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -1,9 +1,9 @@ #include "game.h" #include // Para SDL_GetTicks, SDL_SetRenderTarget -#include // Para rand, size_t #include // Para find_if, clamp, find, min +#include // Para rand, size_t #include // Para function #include // Para distance, size @@ -399,7 +399,7 @@ void Game::destroyAllItems() { } // Comprueba la colisión entre el jugador y los globos activos -std::shared_ptr Game::checkPlayerBalloonCollision(std::shared_ptr &player) { +auto Game::checkPlayerBalloonCollision(std::shared_ptr &player) -> std::shared_ptr { 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; @@ -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 Game::getPlayer(int id) { +auto Game::getPlayer(int id) -> std::shared_ptr { 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 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()) { diff --git a/source/sections/game.h b/source/sections/game.h index 9a89230..2ac43b4 100644 --- a/source/sections/game.h +++ b/source/sections/game.h @@ -74,28 +74,25 @@ class Game { // --- 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 --- @@ -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 checkPlayerBalloonCollision(std::shared_ptr &player); // Comprueba la colisión entre el jugador y los globos activos + auto checkPlayerBalloonCollision(std::shared_ptr &player) -> std::shared_ptr; // Comprueba la colisión entre el jugador y los globos activos void checkPlayerItemCollision(std::shared_ptr &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); // Crea un objeto PathSprite @@ -198,17 +195,17 @@ 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); // 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 getPlayer(int id); // Obtiene un jugador a partir de su "id" - int getController(int player_id); // Obtiene un controlador a partir del "id" del jugador + auto getPlayer(int id) -> std::shared_ptr; // 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 demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos. diff --git a/source/sections/hiscore_table.cpp b/source/sections/hiscore_table.cpp index 11d662e..a5b026a 100644 --- a/source/sections/hiscore_table.cpp +++ b/source/sections/hiscore_table.cpp @@ -1,9 +1,9 @@ #include "hiscore_table.h" #include // Para SDL_GetTicks, SDL_SetRenderTarget -#include // Para rand, size_t #include // Para max +#include // Para rand, size_t #include // Para function #include // 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()), background_(std::make_unique()), - counter_(0), + ticks_(0), view_area_(SDL_FRect{0, 0, static_cast(param.game.width), static_cast(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; diff --git a/source/sections/hiscore_table.h b/source/sections/hiscore_table.h index 90a8b1c..74abc76 100644 --- a/source/sections/hiscore_table.h +++ b/source/sections/hiscore_table.h @@ -64,14 +64,14 @@ class HiScoreTable { 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 + 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 - Color getEntryColor(int counter); // Obtiene un color del vector de colores de entradas + 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 diff --git a/source/sections/instructions.cpp b/source/sections/instructions.cpp index 70e701b..489f826 100644 --- a/source/sections/instructions.cpp +++ b/source/sections/instructions.cpp @@ -279,7 +279,7 @@ void Instructions::run() { } // Método para inicializar las líneas -std::vector Instructions::initializeLines(int height) { +auto Instructions::initializeLines(int height) -> std::vector { std::vector lines; for (int y = 0; y < height; y++) { int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha @@ -289,7 +289,7 @@ std::vector Instructions::initializeLines(int height) { } // Método para mover las líneas con suavizado -bool Instructions::moveLines(std::vector &lines, int width, float duration, Uint32 start_delay) { +auto Instructions::moveLines(std::vector &lines, int width, float duration, Uint32 start_delay) -> bool { Uint32 current_time = SDL_GetTicks(); bool all_lines_off_screen = true; diff --git a/source/sections/instructions.h b/source/sections/instructions.h index a16021f..a1d55fc 100644 --- a/source/sections/instructions.h +++ b/source/sections/instructions.h @@ -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 start_time; // 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), start_time(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 initializeLines(int height); // Inicializa las líneas animadas - bool moveLines(std::vector &lines, int width, float duration, Uint32 start_delay); // Mueve las líneas + auto initializeLines(int height) -> std::vector; // Inicializa las líneas animadas + auto moveLines(std::vector &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector &lines); // Renderiza las líneas void updateBackbuffer(); // Gestiona la textura con los gráficos }; \ No newline at end of file diff --git a/source/sections/logo.cpp b/source/sections/logo.cpp index c74d89d..18f041c 100644 --- a/source/sections/logo.cpp +++ b/source/sections/logo.cpp @@ -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 diff --git a/source/sections/title.cpp b/source/sections/title.cpp index 1ac0a69..c99f346 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -1,9 +1,9 @@ #include "title.h" #include // Para SDL_GetTicks, Uint32, SDL_EventType -#include // Para size_t #include // Para find_if +#include // Para size_t #include // Para basic_ostream, basic_ostream::operator<< #include // Para basic_string, char_traits, operator+ #include // Para vector @@ -513,7 +513,7 @@ void Title::renderPlayers() { } // Obtiene un jugador a partir de su "id" -std::shared_ptr Title::getPlayer(int id) { +auto Title::getPlayer(int id) -> std::shared_ptr { auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) { return player->getId() == id; }); if (it != players_.end()) { diff --git a/source/sections/title.h b/source/sections/title.h index 822440e..6fabeed 100644 --- a/source/sections/title.h +++ b/source/sections/title.h @@ -92,5 +92,5 @@ class Title { void initPlayers(); // Inicializa los jugadores void renderPlayers(); // Renderiza los jugadores void updatePlayers(); // Actualza los jugadores - std::shared_ptr getPlayer(int id); // Obtiene un jugador a partir de su "id" + auto getPlayer(int id) -> std::shared_ptr; // Obtiene un jugador a partir de su "id" }; \ No newline at end of file diff --git a/source/smart_sprite.h b/source/smart_sprite.h index f3ea3b8..1ea40a2 100644 --- a/source/smart_sprite.h +++ b/source/smart_sprite.h @@ -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 diff --git a/source/sprite.cpp b/source/sprite.cpp index 290f539..6ca76ff 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -1,20 +1,22 @@ #include "sprite.h" +#include + #include "texture.h" // Para Texture // Constructor Sprite::Sprite(std::shared_ptr 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, 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_(std::move(texture)), pos_(SDL_FRect{0, 0, static_cast(texture_->getWidth()), static_cast(texture_->getHeight())}), sprite_clip_(pos_) {} diff --git a/source/stage.cpp b/source/stage.cpp index d61152a..64aa167 100644 --- a/source/stage.cpp +++ b/source/stage.cpp @@ -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; diff --git a/source/stage.h b/source/stage.h index 7cd6e29..5227c86 100644 --- a/source/stage.h +++ b/source/stage.h @@ -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 \ No newline at end of file diff --git a/source/text.cpp b/source/text.cpp index eae72a0..933b60f 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -1,8 +1,8 @@ #include "text.h" #include // Para SDL_SetRenderTarget, SDL_GetRenderTarget, Uint8 -#include // Para size_t +#include // Para size_t #include // Para basic_ifstream, basic_istream, basic_ostream #include // Para cerr #include // Para runtime_error @@ -13,14 +13,14 @@ #include "utils.h" // Para Color, getFileName, printWithDots // Llena una estructuta TextFile desde un fichero -std::shared_ptr loadTextFile(const std::string &file_path) { +auto loadTextFile(const std::string &file_path) -> std::shared_ptr { auto tf = std::make_shared(); // 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 Text::writeToTexture(const std::string &text, int zoom, int kerning) { +auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std::shared_ptr { auto renderer = Screen::get()->getRenderer(); auto texture = std::make_shared(renderer); auto width = lenght(text, kerning) * zoom; @@ -159,7 +159,7 @@ std::shared_ptr Text::writeToTexture(const std::string &text, int zoom, } // Escribe el texto con extras en una textura -std::shared_ptr 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 { auto renderer = Screen::get()->getRenderer(); auto texture = std::make_shared(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(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_; } diff --git a/source/texture.cpp b/source/texture.cpp index a52f9f3..21f7e8e 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -2,23 +2,24 @@ #include "texture.h" #include // Para SDL_LogError, SDL_LogCategory, Uint8, SDL_... -#include // Para uint32_t +#include // Para uint32_t #include // Para memcpy #include // Para basic_ifstream, basic_istream, basic_ios #include // Para basic_istringstream #include // Para runtime_error #include // Para basic_string, char_traits, operator+, string -#include // Para vector +#include +#include // 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 Texture::loadSurface(const std::string &file_path) { +auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr { // 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) diff --git a/source/texture.h b/source/texture.h index af6ecc8..b99d61d 100644 --- a/source/texture.h +++ b/source/texture.h @@ -1,11 +1,11 @@ #pragma once #include // Para Uint8, SDL_Renderer, Uint16, SDL_FlipMode, SDL_PixelFormat, SDL_TextureAccess, SDL_Texture, Uint32, SDL_BlendMode, SDL_FPoint, SDL_FRect -#include // Para size_t -#include // Para array -#include // Para shared_ptr -#include // Para string, basic_string +#include // Para array +#include // Para size_t +#include // Para shared_ptr +#include // Para string, basic_string #include #include // 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_ = 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_ = 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 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 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; // 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; // 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 }; \ No newline at end of file diff --git a/source/tiled_bg.cpp b/source/tiled_bg.cpp index 843fca5..3260de3 100644 --- a/source/tiled_bg.cpp +++ b/source/tiled_bg.cpp @@ -1,10 +1,11 @@ #include "tiled_bg.h" #include // Para SDL_SetRenderTarget, SDL_CreateTexture, SDL_De... -#include // Para rand -#include // Para sin -#include // Para unique_ptr, make_unique +#include // Para sin +#include // Para rand +#include // Para unique_ptr, make_unique +#include #include // 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 } } diff --git a/source/tiled_bg.h b/source/tiled_bg.h index 73d1d9c..f78dbc6 100644 --- a/source/tiled_bg.h +++ b/source/tiled_bg.h @@ -35,9 +35,9 @@ 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 diff --git a/source/ui/menu_option.h b/source/ui/menu_option.h index 9baec3c..2276e67 100644 --- a/source/ui/menu_option.h +++ b/source/ui/menu_option.h @@ -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 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 values, std::function current_value_getter, std::function 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 values, std::function current_value_getter, std::function 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 value_list_; std::function getter_; std::function 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 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_(); diff --git a/source/ui/menu_renderer.cpp b/source/ui/menu_renderer.cpp index 21bec71..a80ff10 100644 --- a/source/ui/menu_renderer.cpp +++ b/source/ui/menu_renderer.cpp @@ -100,7 +100,7 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) { 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); @@ -172,7 +172,7 @@ void MenuRenderer::precalculateMenuWidths(const std::vector int { return group_menu_widths_[static_cast(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; } \ No newline at end of file diff --git a/source/ui/menu_renderer.h b/source/ui/menu_renderer.h index 44e24f2..93f5b02 100644 --- a/source/ui/menu_renderer.h +++ b/source/ui/menu_renderer.h @@ -1,10 +1,10 @@ #pragma once #include // Para SDL_FRect, Uint32 -#include // Para size_t -#include // Para shared_ptr, unique_ptr -#include // Para vector +#include // Para size_t +#include // Para shared_ptr, unique_ptr +#include // 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 element_text_; std::shared_ptr 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> &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; }; diff --git a/source/ui/service_menu.cpp b/source/ui/service_menu.cpp index 5e825cc..c0a996c 100644 --- a/source/ui/service_menu.cpp +++ b/source/ui/service_menu.cpp @@ -16,7 +16,7 @@ ServiceMenu *ServiceMenu::instance = nullptr; void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); } void ServiceMenu::destroy() { delete ServiceMenu::instance; } -ServiceMenu *ServiceMenu::get() { return 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(selected_option)) { previous_settings_group_ = current_settings_group_; current_settings_group_ = folder->getTargetGroup(); @@ -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()) { @@ -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"); diff --git a/source/ui/service_menu.h b/source/ui/service_menu.h index 37f47f9..4cb3cc6 100644 --- a/source/ui/service_menu.h +++ b/source/ui/service_menu.h @@ -1,7 +1,6 @@ #pragma once -#include // Para size_t - +#include // Para size_t #include // Para unique_ptr #include // Para basic_string, string #include // Para pair @@ -34,7 +33,7 @@ class ServiceMenu { 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 &getDisplayOptions() const { return display_options_; } - const std::vector> &getAllOptions() const { return options_; } - size_t getSelectedIndex() const { return selected_; } - const std::vector> &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 & { return display_options_; } + [[nodiscard]] auto getAllOptions() const -> const std::vector> & { return options_; } + [[nodiscard]] auto getSelectedIndex() const -> size_t { return selected_; } + [[nodiscard]] auto getOptionPairs() const -> const std::vector> & { 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> options_; @@ -88,19 +87,19 @@ class ServiceMenu { void applyVideoSettings(); void applyAudioSettings(); void applySettingsSettings(); - MenuOption *getOptionByCaption(const std::string &caption) const; + [[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; + auto operator=(const ServiceMenu &) -> ServiceMenu & = delete; static ServiceMenu *instance; }; diff --git a/source/ui/ui_message.cpp b/source/ui/ui_message.cpp index 02e594e..ad54863 100644 --- a/source/ui/ui_message.cpp +++ b/source/ui/ui_message.cpp @@ -1,12 +1,13 @@ #include "ui_message.h" #include // Para pow +#include #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_renderer, const std::string &message_text, const Color &color) - : text_renderer_(text_renderer), text_(message_text), color_(color) {} +UIMessage::UIMessage(std::shared_ptr 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() { @@ -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_; } diff --git a/source/ui/ui_message.h b/source/ui/ui_message.h index 45ec32a..7508028 100644 --- a/source/ui/ui_message.h +++ b/source/ui/ui_message.h @@ -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_renderer, const std::string &message_text, const Color &color); + UIMessage(std::shared_ptr 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 --- diff --git a/source/writer.cpp b/source/writer.cpp index 293ad87..71d6482 100644 --- a/source/writer.cpp +++ b/source/writer.cpp @@ -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_; } \ No newline at end of file diff --git a/source/writer.h b/source/writer.h index bc09811..e2f0c8e 100644 --- a/source/writer.h +++ b/source/writer.h @@ -2,6 +2,7 @@ #include // Para shared_ptr #include // Para string +#include class Text; @@ -9,33 +10,33 @@ class Text; class Writer { public: // Constructor - explicit Writer(std::shared_ptr text) - : text_(text) {} + explicit Writer(std::shared_ptr 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 ---