From 327987447d282f6e5933d5497fe19be8f0c970bc Mon Sep 17 00:00:00 2001 From: Sergio Date: Sun, 17 Aug 2025 00:23:59 +0200 Subject: [PATCH] passant linters a vore si trobe variables sense inicialitzar --- .clang-tidy | 15 +- linux_utils/generate_compile_commands_json.sh | 15 ++ source/animated_sprite.cpp | 8 +- source/animated_sprite.h | 5 +- source/background.cpp | 49 +++--- source/background.h | 12 +- source/balloon.cpp | 4 +- source/balloon.h | 2 +- source/balloon_manager.cpp | 4 +- source/balloon_manager.h | 2 +- source/color.h | 2 +- source/defaults.h | 58 +++---- source/director.cpp | 4 +- source/explosions.cpp | 2 +- source/explosions.h | 2 +- source/fade.cpp | 56 +++--- source/fade.h | 86 ++++----- source/global_inputs.cpp | 2 +- source/hit.h | 2 +- source/input.cpp | 37 ++-- source/input.h | 16 +- source/item.cpp | 2 +- source/item.h | 2 +- source/moving_sprite.cpp | 8 +- source/options.cpp | 4 +- source/options.h | 15 +- source/param.h | 2 +- source/path_sprite.cpp | 2 +- source/path_sprite.h | 7 +- source/pause_manager.h | 2 +- source/player.h | 2 +- source/resource.cpp | 16 +- source/sections/credits.cpp | 50 +++--- source/sections/game.cpp | 40 ++--- source/sections/game.h | 14 +- source/sections/hiscore_table.cpp | 10 +- source/sections/hiscore_table.h | 5 +- source/sections/instructions.cpp | 4 +- source/sections/title.cpp | 6 +- source/shutdown.cpp | 101 ++++++----- source/shutdown.h | 30 ++-- source/smart_sprite.h | 3 +- source/sprite.cpp | 7 +- source/sprite.h | 7 +- source/stage.cpp | 47 ++--- source/stage.h | 2 +- source/stage_interface.h | 4 +- source/system_utils.cpp | 164 +++++++++--------- source/system_utils.h | 26 +-- source/text.cpp | 6 +- source/text.h | 4 +- source/texture.cpp | 2 +- source/ui/notifier.cpp | 5 +- source/ui/notifier.h | 2 +- source/ui/service_menu.cpp | 6 +- 55 files changed, 516 insertions(+), 474 deletions(-) create mode 100755 linux_utils/generate_compile_commands_json.sh diff --git a/.clang-tidy b/.clang-tidy index 15c1d23..7c29778 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,10 +1,21 @@ Checks: > readability-*, modernize-*, - bugprone-*, performance-*, + bugprone-unchecked-optional-access, + bugprone-sizeof-expression, + bugprone-suspicious-missing-comma, + bugprone-suspicious-index, + bugprone-undefined-memory-manipulation, + bugprone-use-after-move, + bugprone-out-of-bound-access, -readability-identifier-length, - -readability-magic-numbers + -readability-magic-numbers, + -bugprone-narrowing-conversions, + -performance-enum-size, + -performance-inefficient-string-concatenation, + -bugprone-integer-division, + -bugprone-easily-swappable-parameters WarningsAsErrors: '*' # Solo incluir archivos de tu c贸digo fuente diff --git a/linux_utils/generate_compile_commands_json.sh b/linux_utils/generate_compile_commands_json.sh new file mode 100755 index 0000000..0bc4903 --- /dev/null +++ b/linux_utils/generate_compile_commands_json.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# 馃弫 Ruta base del proyecto +BASE_DIR="/home/sergio/gitea/coffee_crisis_arcade_edition" + +# 馃搧 Ruta al build +BUILD_DIR="$BASE_DIR/build" + +# 馃搫 Archivo de mapping personalizado +MAPPING_FILE="$BASE_DIR/linux_utils/sdl3_mapping.imp" + +# 馃摝 Generar compile_commands.json +echo "馃敡 Generando compile_commands.json..." +cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -S "$BASE_DIR" -B "$BUILD_DIR" + diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 503163d..90e8f64 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -35,7 +35,7 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe // Constructor AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const std::string& file_path) - : MovingSprite(texture) { + : MovingSprite(std::move(texture)) { // Carga las animaciones if (!file_path.empty()) { auto buffer = loadAnimationsFromFile(file_path); @@ -45,7 +45,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const std::stri // Constructor AnimatedSprite::AnimatedSprite(std::shared_ptr texture, const AnimationsFileBuffer& animations) - : MovingSprite(texture) { + : MovingSprite(std::move(texture)) { if (!animations.empty()) { loadFromAnimationsFileBuffer(animations); } @@ -176,7 +176,7 @@ void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer& so // Procesa una l铆nea de configuraci贸n void AnimatedSprite::processConfigLine(const std::string& line, AnimationConfig& config) { - size_t pos = line.find("="); + size_t pos = line.find('='); if (pos == std::string::npos) { return; } @@ -230,7 +230,7 @@ auto AnimatedSprite::processAnimationBlock(const AnimationsFileBuffer& source, s // Procesa un par谩metro individual de animaci贸n void AnimatedSprite::processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config) { - size_t pos = line.find("="); + size_t pos = line.find('='); if (pos == std::string::npos) { return; } diff --git a/source/animated_sprite.h b/source/animated_sprite.h index ec6b587..238cf49 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.h @@ -7,7 +7,8 @@ #include // Para allocator, shared_ptr #include // Para string, hash #include // Para unordered_map -#include // Para vector +#include +#include // Para vector #include "moving_sprite.h" // Para MovingSprite @@ -49,7 +50,7 @@ class AnimatedSprite : public MovingSprite { // --- Constructores y destructor --- AnimatedSprite(std::shared_ptr texture, const std::string& file_path); AnimatedSprite(std::shared_ptr texture, const AnimationsFileBuffer& animations); - explicit AnimatedSprite(std::shared_ptr texture) : MovingSprite(texture) {} + explicit AnimatedSprite(std::shared_ptr texture) : MovingSprite(std::move(texture)) {} ~AnimatedSprite() override = default; // --- M茅todos principales --- diff --git a/source/background.cpp b/source/background.cpp index 608bea8..3d90073 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -5,6 +5,7 @@ #include // Para clamp, max #include // Para M_PI, cos, sin +#include #include "moving_sprite.h" // Para MovingSprite #include "param.h" // Para Param, ParamBackground, param @@ -171,7 +172,7 @@ void Background::incrementProgress(float amount) { // Establece la progresi贸n absoluta void Background::setProgress(float absolute_progress) { float old_progress = progress_; - progress_ = std::clamp(absolute_progress, 0.0f, total_progress_to_complete_); + progress_ = std::clamp(absolute_progress, 0.0F, total_progress_to_complete_); // Notifica el cambio si hay callback y el progreso cambi贸 if (progress_callback_ && progress_ != old_progress) { @@ -187,11 +188,11 @@ void Background::setState(State new_state) { // Reinicia la progresi贸n void Background::reset() { float old_progress = progress_; - progress_ = 0.0f; + progress_ = 0.0F; state_ = State::NORMAL; manual_mode_ = false; gradient_number_ = 0; - transition_ = 0.0f; + transition_ = 0.0F; sun_index_ = 0; moon_index_ = 0; @@ -208,7 +209,7 @@ void Background::setManualMode(bool manual) { // Establece callback para sincronizaci贸n autom谩tica void Background::setProgressCallback(ProgressCallback callback) { - progress_callback_ = callback; + progress_callback_ = std::move(callback); } // Elimina el callback @@ -224,8 +225,8 @@ void Background::setCloudsSpeed(float value) { // Las nubes inferiores van a la mitad de velocidad que las superiores top_clouds_sprite_a_->setVelX(value); top_clouds_sprite_b_->setVelX(value); - bottom_clouds_sprite_a_->setVelX(value / 2.0f); - bottom_clouds_sprite_b_->setVelX(value / 2.0f); + bottom_clouds_sprite_a_->setVelX(value / 2.0F); + bottom_clouds_sprite_b_->setVelX(value / 2.0F); } // Establece el degradado de fondo @@ -262,19 +263,19 @@ void Background::updateProgression() { } // Calcula la transici贸n de los diferentes fondos - const float gradient_number_float = std::min(progress_ / progress_per_stage_, 3.0F); - const float percent = gradient_number_float - static_cast(gradient_number_float); + const float GRADIENT_NUMBER_FLOAT = std::min(progress_ / progress_per_stage_, 3.0F); + const float PERCENT = GRADIENT_NUMBER_FLOAT - static_cast(GRADIENT_NUMBER_FLOAT); - gradient_number_ = static_cast(gradient_number_float); - transition_ = percent; + gradient_number_ = static_cast(GRADIENT_NUMBER_FLOAT); + transition_ = PERCENT; // Calcula la posici贸n del sol - const float sun_progression = std::min(progress_ / sun_completion_progress_, 1.0f); - sun_index_ = static_cast(sun_progression * (sun_path_.size() - 1)); + const float SUN_PROGRESSION = std::min(progress_ / sun_completion_progress_, 1.0F); + sun_index_ = static_cast(SUN_PROGRESSION * (sun_path_.size() - 1)); // Calcula la posici贸n de la luna - const float moon_progression = std::min(progress_ / total_progress_to_complete_, 1.0f); - moon_index_ = static_cast(moon_progression * (moon_path_.size() - 1)); + const float MOON_PROGRESSION = std::min(progress_ / total_progress_to_complete_, 1.0F); + moon_index_ = static_cast(MOON_PROGRESSION * (moon_path_.size() - 1)); // Actualiza la velocidad de las nubes updateCloudsSpeed(); @@ -294,22 +295,22 @@ void Background::updateCloudsSpeed() { if (state_ == State::COMPLETED) { float completion_factor = (progress_ - MINIMUM_COMPLETED_PROGRESS) / (total_progress_to_complete_ - MINIMUM_COMPLETED_PROGRESS); - completion_factor = std::max(0.1f, completion_factor); + completion_factor = std::max(0.1F, completion_factor); base_clouds_speed *= completion_factor; } // Aplicar velocidades diferentes para nubes superiores e inferiores - const float top_clouds_speed = base_clouds_speed; - const float bottom_clouds_speed = base_clouds_speed / 2.0f; + const float TOP_CLOUDS_SPEED = base_clouds_speed; + const float BOTTOM_CLOUDS_SPEED = base_clouds_speed / 2.0F; // Aplicar las velocidades a los sprites correspondientes - top_clouds_sprite_a_->setVelX(top_clouds_speed); - top_clouds_sprite_b_->setVelX(top_clouds_speed); - bottom_clouds_sprite_a_->setVelX(bottom_clouds_speed); - bottom_clouds_sprite_b_->setVelX(bottom_clouds_speed); + top_clouds_sprite_a_->setVelX(TOP_CLOUDS_SPEED); + top_clouds_sprite_b_->setVelX(TOP_CLOUDS_SPEED); + bottom_clouds_sprite_a_->setVelX(BOTTOM_CLOUDS_SPEED); + bottom_clouds_sprite_b_->setVelX(BOTTOM_CLOUDS_SPEED); // Guardar la velocidad principal - clouds_speed_ = top_clouds_speed; + clouds_speed_ = TOP_CLOUDS_SPEED; } // Actualiza las nubes @@ -501,9 +502,9 @@ void Background::createMoonPath() { constexpr double STEP = 0.01; const int NUM_STEPS = static_cast((M_PI / 2) / STEP) + 1; - constexpr float FREEZE_PERCENTAGE = 0.2f; // Porcentaje final del recorrido que se mantiene fijo + constexpr float FREEZE_PERCENTAGE = 0.2F; // Porcentaje final del recorrido que se mantiene fijo - const int FREEZE_START_INDEX = static_cast(NUM_STEPS * (1.0f - FREEZE_PERCENTAGE)); + const int FREEZE_START_INDEX = static_cast(NUM_STEPS * (1.0F - FREEZE_PERCENTAGE)); for (int i = 0; i < NUM_STEPS; ++i) { double theta = i * STEP; diff --git a/source/background.h b/source/background.h index 6ac7c99..56bb972 100644 --- a/source/background.h +++ b/source/background.h @@ -27,7 +27,7 @@ class Background { using ProgressCallback = std::function; // Callback para sincronizaci贸n // --- Constructor y destructor --- - Background(float total_progress_to_complete = 6100.0f); // Constructor principal + Background(float total_progress_to_complete = 6100.0F); // Constructor principal ~Background(); // Destructor // --- M茅todos principales --- @@ -50,7 +50,7 @@ class Background { void setAlpha(int alpha); // Ajusta la transparencia del fondo // --- Control de progresi贸n --- - void incrementProgress(float amount = 1.0f); // Incrementa la progresi贸n interna + void incrementProgress(float amount = 1.0F); // Incrementa la progresi贸n interna void setProgress(float absolute_progress); // Establece la progresi贸n absoluta // --- Getters --- @@ -61,9 +61,9 @@ class Background { private: // --- Constantes --- static constexpr size_t STAGES = 4; // N煤mero de etapas - static constexpr float COMPLETED_REDUCTION_RATE = 25.0f; // Tasa de reducci贸n completada - static constexpr float MINIMUM_COMPLETED_PROGRESS = 200.0f; // Progreso m铆nimo completado - static constexpr float SUN_COMPLETION_FACTOR = 0.5f; // Factor de completado del sol + static constexpr float COMPLETED_REDUCTION_RATE = 25.0F; // Tasa de reducci贸n completada + static constexpr float MINIMUM_COMPLETED_PROGRESS = 200.0F; // Progreso m铆nimo completado + static constexpr float SUN_COMPLETION_FACTOR = 0.5F; // Factor de completado del sol // --- Objetos y punteros --- SDL_Renderer *renderer_; // Renderizador de la ventana @@ -103,7 +103,7 @@ class Background { SDL_FRect dst_rect_; // Posici贸n en pantalla donde se copia el objeto Color attenuate_color_; // Color de atenuaci贸n State state_ = State::NORMAL; // Estado actual - float progress_ = 0.0f; // Progresi贸n interna + float progress_ = 0.0F; // Progresi贸n interna float clouds_speed_ = 0; // Velocidad de las nubes float transition_ = 0; // Porcentaje de transici贸n size_t gradient_number_ = 0; // 脥ndice de fondo degradado diff --git a/source/balloon.cpp b/source/balloon.cpp index 360f4dd..32c6c7e 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -11,7 +11,7 @@ #include "texture.h" // Para Texture // Constructor -Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, std::shared_ptr texture, const std::vector &animation) +Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float speed, Uint16 creation_timer, SDL_FRect play_area, const std::shared_ptr &texture, const std::vector &animation) : sprite_(std::make_unique(texture, animation)), x_(x), y_(y), @@ -44,7 +44,7 @@ Balloon::Balloon(float x, float y, Type type, Size size, float vel_x, float spee } case Type::FLOATER: { - default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0F); + default_vy_ = max_vy_ = vy_ = std::fabs(vx_ * 2.0F); gravity_ = 0.00F; const int INDEX = static_cast(size_); diff --git a/source/balloon.h b/source/balloon.h index f1400ea..ee63e29 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -62,7 +62,7 @@ class Balloon { float speed, Uint16 creation_timer, SDL_FRect play_area, - std::shared_ptr texture, + const std::shared_ptr& texture, const std::vector& animation); ~Balloon() = default; diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 25d41df..b0b779e 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -64,7 +64,7 @@ void BalloonManager::init() { // Actualiza void BalloonManager::update() { - for (auto balloon : balloons_) { + for (const auto &balloon : balloons_) { balloon->update(); } updateBalloonDeployCounter(); @@ -226,7 +226,7 @@ void BalloonManager::setBalloonSpeed(float speed) { } // Explosiona un globo. Lo destruye y crea otros dos si es el caso -auto BalloonManager::popBalloon(std::shared_ptr balloon) -> int { +auto BalloonManager::popBalloon(const std::shared_ptr &balloon) -> int { stage_info_->addPower(1); int score = 0; diff --git a/source/balloon_manager.h b/source/balloon_manager.h index e45c951..0a0b6d9 100644 --- a/source/balloon_manager.h +++ b/source/balloon_manager.h @@ -55,7 +55,7 @@ class BalloonManager { auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla // --- Manipulaci贸n de globos existentes --- - auto popBalloon(std::shared_ptr balloon) -> int; // Explosiona un globo, creando otros si aplica + auto popBalloon(const 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 diff --git a/source/color.h b/source/color.h index bee4ee5..13c733f 100644 --- a/source/color.h +++ b/source/color.h @@ -81,7 +81,7 @@ struct Color { } // Convierte el color a un entero de 32 bits en formato RGBA - [[nodiscard]] constexpr auto toUint32() const -> Uint32 { + [[nodiscard]] constexpr auto TO_UINT32() const -> Uint32 { return (static_cast(r) << 24) | (static_cast(g) << 16) | (static_cast(b) << 8) | diff --git a/source/defaults.h b/source/defaults.h index 5241160..861a429 100644 --- a/source/defaults.h +++ b/source/defaults.h @@ -10,38 +10,38 @@ namespace GameDefaults { // --- GAME --- namespace Game { -constexpr float WIDTH = 320.0f; -constexpr float HEIGHT = 256.0f; -constexpr float ITEM_SIZE = 20.0f; +constexpr float WIDTH = 320.0F; +constexpr float HEIGHT = 256.0F; +constexpr float ITEM_SIZE = 20.0F; constexpr int NAME_ENTRY_IDLE_TIME = 10; constexpr int NAME_ENTRY_TOTAL_TIME = 60; constexpr bool HIT_STOP = false; constexpr int HIT_STOP_MS = 500; // Play area por defecto -constexpr float PLAY_AREA_X = 0.0f; -constexpr float PLAY_AREA_Y = 0.0f; -constexpr float PLAY_AREA_W = 320.0f; -constexpr float PLAY_AREA_H = 216.0f; +constexpr float PLAY_AREA_X = 0.0F; +constexpr float PLAY_AREA_Y = 0.0F; +constexpr float PLAY_AREA_W = 320.0F; +constexpr float PLAY_AREA_H = 216.0F; } // namespace Game // --- FADE --- namespace Fade { constexpr const char* COLOR = "1F2B30"; -constexpr float NUM_SQUARES_WIDTH = 160.0f; -constexpr float NUM_SQUARES_HEIGHT = 128.0f; +constexpr float NUM_SQUARES_WIDTH = 160.0F; +constexpr float NUM_SQUARES_HEIGHT = 128.0F; constexpr int RANDOM_SQUARES_DELAY = 1; constexpr int RANDOM_SQUARES_MULT = 500; constexpr int POST_DURATION = 80; -constexpr float VENETIAN_SIZE = 12.0f; +constexpr float VENETIAN_SIZE = 12.0F; } // namespace Fade // --- SCOREBOARD --- namespace Scoreboard { -constexpr float RECT_X = 0.0f; -constexpr float RECT_Y = 216.0f; -constexpr float RECT_W = 320.0f; -constexpr float RECT_H = 40.0f; +constexpr float RECT_X = 0.0F; +constexpr float RECT_Y = 216.0F; +constexpr float RECT_W = 320.0F; +constexpr float RECT_H = 40.0F; constexpr bool SEPARATOR_AUTOCOLOR = true; constexpr const char* SEPARATOR_COLOR = "0D1A2B"; constexpr const char* EASY_COLOR = "4B692F"; @@ -77,10 +77,10 @@ struct BalloonSettings { }; constexpr std::array SETTINGS = {{ - BalloonSettings(2.75f, 0.09f), // Globo 0 - BalloonSettings(3.70f, 0.10f), // Globo 1 - BalloonSettings(4.70f, 0.10f), // Globo 2 - BalloonSettings(5.45f, 0.10f) // Globo 3 + BalloonSettings(2.75F, 0.09F), // Globo 0 + BalloonSettings(3.70F, 0.10F), // Globo 1 + BalloonSettings(4.70F, 0.10F), // Globo 2 + BalloonSettings(5.45F, 0.10F) // Globo 3 }}; constexpr std::array COLORS = { @@ -111,15 +111,15 @@ constexpr const char* BG_COLOR = "141E32F0"; // Color(20, 30, 50, 240) constexpr const char* BORDER_COLOR = "6496C8FF"; // Color(100, 150, 200, 255) constexpr const char* TITLE_COLOR = "6496C8FF"; // Color(100, 150, 200, 255) constexpr const char* TEXT_COLOR = "DCDCDCFF"; // Color(220, 220, 220, 255) -constexpr float PADDING = 15.0f; -constexpr float LINE_SPACING = 5.0f; -constexpr float TITLE_SEPARATOR_SPACING = 10.0f; // Cambiado a float -constexpr float MIN_WIDTH = 250.0f; -constexpr float MIN_HEIGHT = 32.0f; // Cambiado a float -constexpr float MAX_WIDTH_RATIO = 0.8f; // Nuevo -constexpr float MAX_HEIGHT_RATIO = 0.8f; // Nuevo -constexpr float TEXT_SAFETY_MARGIN = 15.0f; -constexpr float ANIMATION_DURATION = 0.3f; +constexpr float PADDING = 15.0F; +constexpr float LINE_SPACING = 5.0F; +constexpr float TITLE_SEPARATOR_SPACING = 10.0F; // Cambiado a float +constexpr float MIN_WIDTH = 250.0F; +constexpr float MIN_HEIGHT = 32.0F; // Cambiado a float +constexpr float MAX_WIDTH_RATIO = 0.8F; // Nuevo +constexpr float MAX_HEIGHT_RATIO = 0.8F; // Nuevo +constexpr float TEXT_SAFETY_MARGIN = 15.0F; +constexpr float ANIMATION_DURATION = 0.3F; } // namespace WindowMessage } // namespace ServiceMenu @@ -143,8 +143,8 @@ constexpr const char* COLOR = "FFFFFF"; // --- TABE --- namespace Tabe { -constexpr float MIN_SPAWN_TIME = 2.0f; -constexpr float MAX_SPAWN_TIME = 3.0f; +constexpr float MIN_SPAWN_TIME = 2.0F; +constexpr float MAX_SPAWN_TIME = 3.0F; } // namespace Tabe // --- PLAYER --- diff --git a/source/director.cpp b/source/director.cpp index e28bfb2..ebd1142 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -188,7 +188,7 @@ void Director::createSystemFolder(const std::string &folder) { if (result != SystemUtils::Result::SUCCESS) { std::cerr << "Error creando carpeta del sistema: " - << SystemUtils::resultToString(result) << std::endl; + << SystemUtils::resultToString(result) << '\n'; exit(EXIT_FAILURE); } } @@ -321,7 +321,7 @@ void Director::shutdownSystem(bool should_shutdown) { auto result = SystemShutdown::shutdownSystem(5, true); // 5 segundos, forzar apps if (result != SystemShutdown::ShutdownResult::SUCCESS) { - std::cerr << SystemShutdown::resultToString(result) << std::endl; + std::cerr << SystemShutdown::resultToString(result) << '\n'; } } } \ No newline at end of file diff --git a/source/explosions.cpp b/source/explosions.cpp index 9c96a93..b0697ef 100644 --- a/source/explosions.cpp +++ b/source/explosions.cpp @@ -24,7 +24,7 @@ void Explosions::render() { } // A帽ade texturas al objeto -void Explosions::addTexture(int size, std::shared_ptr texture, const std::vector &animation) { +void Explosions::addTexture(int size, const std::shared_ptr &texture, const std::vector &animation) { textures_.emplace_back(size, texture, animation); } diff --git a/source/explosions.h b/source/explosions.h index 1f0adc9..c2178da 100644 --- a/source/explosions.h +++ b/source/explosions.h @@ -31,7 +31,7 @@ class Explosions { void render(); // Dibuja el objeto en pantalla // --- Configuraci贸n --- - void addTexture(int size, std::shared_ptr texture, const std::vector &animation); // A帽ade texturas al objeto + void addTexture(int size, const std::shared_ptr &texture, const std::vector &animation); // A帽ade texturas al objeto void add(int x, int y, int size); // A帽ade una explosi贸n private: diff --git a/source/fade.cpp b/source/fade.cpp index 6c4b248..0ae2511 100644 --- a/source/fade.cpp +++ b/source/fade.cpp @@ -27,8 +27,8 @@ Fade::~Fade() { // Inicializa las variables void Fade::init() { - type_ = FadeType::CENTER; - mode_ = FadeMode::OUT; + type_ = Type::CENTER; + mode_ = Mode::OUT; counter_ = 0; r_ = 0; g_ = 0; @@ -46,13 +46,13 @@ void Fade::init() { // Resetea algunas variables para volver a hacer el fade sin perder ciertos parametros void Fade::reset() { - state_ = FadeState::NOT_ENABLED; + state_ = State::NOT_ENABLED; counter_ = 0; } // Pinta una transici贸n en pantalla void Fade::render() { - if (state_ != FadeState::NOT_ENABLED) { + if (state_ != State::NOT_ENABLED) { SDL_RenderTexture(renderer_, backbuffer_, nullptr, nullptr); } } @@ -60,13 +60,13 @@ void Fade::render() { // Actualiza las variables internas void Fade::update() { switch (state_) { - case FadeState::PRE: + case State::PRE: updatePreState(); break; - case FadeState::FADING: + case State::FADING: updateFadingState(); break; - case FadeState::POST: + case State::POST: updatePostState(); break; default: @@ -76,7 +76,7 @@ void Fade::update() { void Fade::updatePreState() { if (pre_counter_ == pre_duration_) { - state_ = FadeState::FADING; + state_ = State::FADING; } else { pre_counter_++; } @@ -84,16 +84,16 @@ void Fade::updatePreState() { void Fade::updateFadingState() { switch (type_) { - case FadeType::FULLSCREEN: + case Type::FULLSCREEN: updateFullscreenFade(); break; - case FadeType::CENTER: + case Type::CENTER: updateCenterFade(); break; - case FadeType::RANDOM_SQUARE: + case Type::RANDOM_SQUARE: updateRandomSquareFade(); break; - case FadeType::VENETIAN: + case Type::VENETIAN: updateVenetianFade(); break; default: @@ -104,7 +104,7 @@ void Fade::updateFadingState() { void Fade::updatePostState() { if (post_counter_ == post_duration_) { - state_ = FadeState::FINISHED; + state_ = State::FINISHED; } else { post_counter_++; } @@ -113,12 +113,12 @@ void Fade::updatePostState() { void Fade::updateFullscreenFade() { // Modifica la transparencia - a_ = mode_ == FadeMode::OUT ? std::min(counter_ * 4, 255) : 255 - std::min(counter_ * 4, 255); + a_ = mode_ == Mode::OUT ? std::min(counter_ * 4, 255) : 255 - std::min(counter_ * 4, 255); SDL_SetTextureAlphaMod(backbuffer_, a_); // Comprueba si ha terminado if (counter_ >= 255 / 4) { - state_ = FadeState::POST; + state_ = State::POST; } } @@ -127,7 +127,7 @@ void Fade::updateCenterFade() { // Comprueba si ha terminado if ((counter_ * 4) > param.game.height) { - state_ = FadeState::POST; + state_ = State::POST; a_ = 255; } } @@ -160,7 +160,7 @@ void Fade::updateRandomSquareFade() { // Comprueba si ha terminado if (counter_ * fade_random_squares_mult_ / fade_random_squares_delay_ >= num_squares_width_ * num_squares_height_) { - state_ = FadeState::POST; + state_ = State::POST; } } @@ -192,7 +192,7 @@ void Fade::updateVenetianFade() { updateVenetianRectangles(); calculateVenetianProgress(); } else { - state_ = FadeState::POST; + state_ = State::POST; } } @@ -233,30 +233,30 @@ void Fade::calculateVenetianProgress() { // Activa el fade void Fade::activate() { // Si ya est谩 habilitado, no hay que volverlo a activar - if (state_ != FadeState::NOT_ENABLED) { + if (state_ != State::NOT_ENABLED) { return; } - state_ = FadeState::PRE; + state_ = State::PRE; counter_ = 0; post_counter_ = 0; pre_counter_ = 0; switch (type_) { - case FadeType::FULLSCREEN: { + case Type::FULLSCREEN: { // Pinta el backbuffer_ de color s贸lido cleanBackbuffer(r_, g_, b_, 255); break; } - case FadeType::CENTER: { + case Type::CENTER: { rect1_ = {0, 0, param.game.width, 0}; rect2_ = {0, 0, param.game.width, 0}; a_ = 64; break; } - case FadeType::RANDOM_SQUARE: { + case Type::RANDOM_SQUARE: { rect1_ = {0, 0, static_cast(param.game.width / num_squares_width_), static_cast(param.game.height / num_squares_height_)}; square_.clear(); @@ -278,22 +278,22 @@ void Fade::activate() { } // Limpia la textura - a_ = mode_ == FadeMode::OUT ? 0 : 255; + a_ = mode_ == Mode::OUT ? 0 : 255; cleanBackbuffer(r_, g_, b_, a_); // Deja el color listo para usar - a_ = mode_ == FadeMode::OUT ? 255 : 0; + a_ = mode_ == Mode::OUT ? 255 : 0; break; } - case FadeType::VENETIAN: { + case Type::VENETIAN: { // Limpia la textura - a_ = mode_ == FadeMode::OUT ? 0 : 255; + a_ = mode_ == Mode::OUT ? 0 : 255; cleanBackbuffer(r_, g_, b_, a_); // Deja el color listo para usar - a_ = mode_ == FadeMode::OUT ? 255 : 0; + a_ = mode_ == Mode::OUT ? 255 : 0; // A帽ade los cuadrados al vector square_.clear(); diff --git a/source/fade.h b/source/fade.h index 06f7557..760f0cc 100644 --- a/source/fade.h +++ b/source/fade.h @@ -6,30 +6,30 @@ struct Color; -// --- Enums --- -enum class FadeType : Uint8 { - FULLSCREEN = 0, // Fundido de pantalla completa - CENTER = 1, // Fundido desde el centro - RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios - VENETIAN = 3, // Fundido tipo persiana veneciana -}; - -enum class FadeMode : Uint8 { - IN = 0, // Fundido de entrada - OUT = 1, // Fundido de salida -}; - -enum class FadeState : Uint8 { - NOT_ENABLED = 0, // No activado - PRE = 1, // Estado previo - FADING = 2, // Fundiendo - POST = 3, // Estado posterior - FINISHED = 4, // Finalizado -}; - // --- Clase Fade: gestor de transiciones de fundido --- class Fade { public: + // --- Enums --- + enum class Type : Uint8 { + FULLSCREEN = 0, // Fundido de pantalla completa + CENTER = 1, // Fundido desde el centro + RANDOM_SQUARE = 2, // Fundido con cuadrados aleatorios + VENETIAN = 3, // Fundido tipo persiana veneciana + }; + + enum class Mode : Uint8 { + IN = 0, // Fundido de entrada + OUT = 1, // Fundido de salida + }; + + enum class State : Uint8 { + NOT_ENABLED = 0, // No activado + PRE = 1, // Estado previo + FADING = 2, // Fundiendo + POST = 3, // Estado posterior + FINISHED = 4, // Finalizado + }; + // --- Constructores y destructor --- Fade(); ~Fade(); @@ -41,17 +41,17 @@ class Fade { void activate(); // Activa el fade // --- Configuraci贸n --- - void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade - void setColor(Color color); // Establece el color del fade - void setType(FadeType type) { type_ = type; } // Establece el tipo de fade - void setMode(FadeMode mode) { mode_ = mode; } // Establece el modo de fade + void setColor(Uint8 r, Uint8 g, Uint8 b); // Establece el color RGB del fade + void setColor(Color color); // Establece el color del fade + void setType(Type type) { type_ = type; } // Establece el tipo de fade + void setMode(Mode mode) { mode_ = mode; } // Establece el modo de fade void setPostDuration(int value) { post_duration_ = value; } // Duraci贸n posterior al fade void setPreDuration(int value) { pre_duration_ = value; } // Duraci贸n previa al fade // --- Getters --- [[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; } + [[nodiscard]] auto isEnabled() const -> bool { return state_ != State::NOT_ENABLED; } + [[nodiscard]] auto hasEnded() const -> bool { return state_ == State::FINISHED; } private: // --- Objetos y punteros --- @@ -59,22 +59,22 @@ class Fade { SDL_Texture *backbuffer_; // Backbuffer para efectos // --- Variables de estado --- - std::vector square_; // Vector de cuadrados - SDL_FRect rect1_, rect2_; // Rect谩ngulos para efectos - FadeType type_; // Tipo de fade - FadeMode mode_; // Modo de fade - FadeState state_ = FadeState::NOT_ENABLED; // Estado actual - Uint16 counter_; // Contador interno - Uint8 r_, g_, b_, a_; // Color del fade (RGBA) - int num_squares_width_; // Cuadrados en horizontal - int num_squares_height_; // Cuadrados en vertical - int fade_random_squares_delay_; // Delay entre cuadrados - int fade_random_squares_mult_; // Cuadrados por paso - int post_duration_ = 0; // Duraci贸n posterior - int post_counter_ = 0; // Contador posterior - int pre_duration_ = 0; // Duraci贸n previa - int pre_counter_ = 0; // Contador previo - int value_ = 0; // Estado del fade (0-100) + std::vector square_; // Vector de cuadrados + SDL_FRect rect1_, rect2_; // Rect谩ngulos para efectos + Type type_; // Tipo de fade + Mode mode_; // Modo de fade + State state_ = State::NOT_ENABLED; // Estado actual + Uint16 counter_; // Contador interno + Uint8 r_, g_, b_, a_; // Color del fade (RGBA) + int num_squares_width_; // Cuadrados en horizontal + int num_squares_height_; // Cuadrados en vertical + int fade_random_squares_delay_; // Delay entre cuadrados + int fade_random_squares_mult_; // Cuadrados por paso + int post_duration_ = 0; // Duraci贸n posterior + int post_counter_ = 0; // Contador posterior + int pre_duration_ = 0; // Duraci贸n previa + int pre_counter_ = 0; // Contador previo + int value_ = 0; // Estado del fade (0-100) // --- Inicializaci贸n y limpieza --- void init(); // Inicializa variables diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index ca6b073..e714905 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -145,7 +145,7 @@ auto checkServiceButton() -> bool { } // Mandos - for (auto gamepad : Input::get()->getGamepads()) { + for (const auto& gamepad : Input::get()->getGamepads()) { if (Input::get()->checkAction(Input::Action::SERVICE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { toggleServiceMenu(); return true; diff --git a/source/hit.h b/source/hit.h index cc71f05..0d5f6cc 100644 --- a/source/hit.h +++ b/source/hit.h @@ -12,7 +12,7 @@ struct Hit { public: // --- Constructor --- Hit() = delete; // Elimina el constructor por defecto para obligar a pasar una textura - explicit Hit(std::shared_ptr texture) // Constructor con textura obligatoria + explicit Hit(const std::shared_ptr& texture) // Constructor con textura obligatoria : sprite_(std::make_unique(texture)) {} // --- M茅todos principales --- diff --git a/source/input.cpp b/source/input.cpp index 03a6fd1..eada5ff 100644 --- a/source/input.cpp +++ b/source/input.cpp @@ -36,21 +36,21 @@ void Input::bindKey(Action action, SDL_Scancode code) { } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(std::shared_ptr gamepad, Action action, SDL_GamepadButton button) { +void Input::bindGameControllerButton(const std::shared_ptr &gamepad, Action action, SDL_GamepadButton button) { if (gamepad != nullptr) { gamepad->bindings[action].button = button; } } // Asigna inputs a botones del mando -void Input::bindGameControllerButton(std::shared_ptr gamepad, Action action_target, Action action_source) { +void Input::bindGameControllerButton(const std::shared_ptr &gamepad, Action action_target, Action action_source) { if (gamepad != nullptr) { gamepad->bindings[action_target].button = gamepad->bindings[action_source].button; } } // Comprueba si alguna acci贸n est谩 activa -auto Input::checkAction(Action action, bool repeat, bool check_keyboard, std::shared_ptr gamepad) -> bool { +auto Input::checkAction(Action action, bool repeat, bool check_keyboard, const std::shared_ptr &gamepad) -> bool { bool success_keyboard = false; bool success_controller = false; @@ -82,7 +82,7 @@ auto Input::checkAction(Action action, bool repeat, bool check_keyboard, std::sh } // Comprueba si hay almenos una acci贸n activa -auto Input::checkAnyInput(bool check_keyboard, std::shared_ptr gamepad) -> bool { +auto Input::checkAnyInput(bool check_keyboard, const std::shared_ptr &gamepad) -> bool { // Obtenemos el n煤mero total de acciones posibles para iterar sobre ellas. // --- Comprobaci贸n del Teclado --- @@ -122,7 +122,7 @@ auto Input::checkAnyButton(bool repeat) -> bool { } // Comprueba los mandos - for (auto gamepad : gamepads_) { + for (const auto &gamepad : gamepads_) { if (checkAction(bi, repeat, DO_NOT_CHECK_KEYBOARD, gamepad)) { return true; } @@ -136,7 +136,8 @@ auto Input::checkAnyButton(bool repeat) -> bool { auto Input::gameControllerFound() const -> bool { return !gamepads_.empty(); } // Obten el nombre de un mando de juego -auto Input::getControllerName(std::shared_ptr gamepad) -> std::string { return gamepad == nullptr ? std::string() : gamepad->name; } +auto Input::getControllerName(const std::shared_ptr &gamepad) -> std::string { + return gamepad == nullptr ? std::string() : gamepad->name; } // Obtiene la lista de nombres de mandos auto Input::getControllerNames() const -> std::vector { @@ -170,7 +171,7 @@ auto Input::getGamepadByName(const std::string &name) const -> std::shared_ptr gamepad, Action action) -> SDL_GamepadButton { +auto Input::getControllerBinding(const std::shared_ptr &gamepad, Action action) -> SDL_GamepadButton { return gamepad->bindings[action].button; } @@ -206,7 +207,7 @@ auto Input::stringToInput(const std::string &name) -> Action { } // Comprueba el eje del mando -auto Input::checkAxisInput(Action action, std::shared_ptr gamepad, bool repeat) -> bool { +auto Input::checkAxisInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool { // Umbral para considerar el eje como activo bool axis_active_now = false; @@ -248,7 +249,7 @@ auto Input::checkAxisInput(Action action, std::shared_ptr gamepad, bool } // Comprueba los triggers del mando como botones digitales -auto Input::checkTriggerInput(Action action, std::shared_ptr gamepad, bool repeat) -> bool { +auto Input::checkTriggerInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool { // Solo manejamos botones espec铆ficos que pueden ser triggers if (gamepad->bindings[action].button != SDL_GAMEPAD_BUTTON_INVALID) { // Solo procesamos L2 y R2 como triggers @@ -297,7 +298,7 @@ auto Input::checkTriggerInput(Action action, std::shared_ptr gamepad, b void Input::addGamepadMappingsFromFile() { if (SDL_AddGamepadMappingsFromFile(gamepad_mappings_file_.c_str()) < 0) { - std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << std::endl; + std::cout << "Error, could not load " << gamepad_mappings_file_.c_str() << " file: " << SDL_GetError() << '\n'; } } @@ -350,7 +351,7 @@ void Input::update() { } // --- MANDOS --- - for (auto gamepad : gamepads_) { + for (const auto &gamepad : gamepads_) { for (auto &binding : gamepad->bindings) { bool button_is_down_now = static_cast(SDL_GetGamepadButton(gamepad->pad, binding.second.button)) != 0; @@ -374,13 +375,13 @@ auto Input::handleEvent(const SDL_Event &event) -> std::string { auto Input::addGamepad(int device_index) -> std::string { SDL_Gamepad *pad = SDL_OpenGamepad(device_index); if (pad == nullptr) { - std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << std::endl; + std::cerr << "Error al abrir el gamepad: " << SDL_GetError() << '\n'; return {}; } auto gamepad = std::make_shared(pad); auto name = gamepad->name; - std::cout << "Gamepad connected (" << name << ")" << std::endl; + std::cout << "Gamepad connected (" << name << ")" << '\n'; applyGamepadConfig(gamepad); saveGamepadConfigFromGamepad(gamepad); gamepads_.push_back(std::move(gamepad)); @@ -394,17 +395,17 @@ auto Input::removeGamepad(SDL_JoystickID id) -> std::string { if (it != gamepads_.end()) { std::string name = (*it)->name; - std::cout << "Gamepad disconnected (" << name << ")" << std::endl; + std::cout << "Gamepad disconnected (" << name << ")" << '\n'; gamepads_.erase(it); return name + " DISCONNECTED"; } - std::cerr << "No se encontr贸 el gamepad con ID " << id << std::endl; + std::cerr << "No se encontr贸 el gamepad con ID " << id << '\n'; return {}; } void Input::printConnectedGamepads() const { if (gamepads_.empty()) { - std::cout << "No hay gamepads conectados." << std::endl; + std::cout << "No hay gamepads conectados." << '\n'; return; } @@ -412,7 +413,7 @@ void Input::printConnectedGamepads() const { for (const auto &gamepad : gamepads_) { std::string name = gamepad->name.empty() ? "Desconocido" : gamepad->name; std::cout << " - ID: " << gamepad->instance_id - << ", Nombre: " << name << ")" << std::endl; + << ", Nombre: " << name << ")" << '\n'; } } @@ -438,7 +439,7 @@ void Input::applyGamepadConfig(std::shared_ptr gamepad) { if (config_it != gamepad_configs_.end()) { // Se encontr贸 una configuraci贸n espec铆fica para este puerto/dispositivo. La aplicamos. - std::cout << "Applying custom config for gamepad at path: " << gamepad->path << std::endl; + std::cout << "Applying custom config for gamepad at path: " << gamepad->path << '\n'; for (const auto &[action, button] : config_it->bindings) { if (gamepad->bindings.find(action) != gamepad->bindings.end()) { gamepad->bindings[action].button = button; diff --git a/source/input.h b/source/input.h index 6089ab3..fdc25ef 100644 --- a/source/input.h +++ b/source/input.h @@ -144,18 +144,18 @@ class Input { // --- M茅todos de configuraci贸n de controles --- void bindKey(Action action, SDL_Scancode code); - static void bindGameControllerButton(std::shared_ptr gamepad, Action action, SDL_GamepadButton button); - static void bindGameControllerButton(std::shared_ptr gamepad, Action action_target, Action action_source); + static void bindGameControllerButton(const std::shared_ptr &gamepad, Action action, SDL_GamepadButton button); + static void bindGameControllerButton(const std::shared_ptr &gamepad, Action action_target, Action action_source); // --- M茅todos de consulta de entrada --- void update(); - auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, std::shared_ptr gamepad = nullptr) -> bool; - auto checkAnyInput(bool check_keyboard = true, std::shared_ptr gamepad = nullptr) -> bool; + auto checkAction(Action action, bool repeat = true, bool check_keyboard = true, const std::shared_ptr &gamepad = nullptr) -> bool; + auto checkAnyInput(bool check_keyboard = true, const std::shared_ptr &gamepad = nullptr) -> bool; auto checkAnyButton(bool repeat = DO_NOT_ALLOW_REPEAT) -> bool; // --- M茅todos de gesti贸n de mandos --- [[nodiscard]] auto gameControllerFound() const -> bool; - static auto getControllerName(std::shared_ptr gamepad) -> std::string; + static auto getControllerName(const std::shared_ptr &gamepad) -> std::string; auto getControllerNames() const -> std::vector; [[nodiscard]] auto getNumGamepads() const -> int; auto getGamepad(SDL_JoystickID id) const -> std::shared_ptr; @@ -163,7 +163,7 @@ class Input { auto getGamepads() const -> const Gamepads & { return gamepads_; } // --- M茅todos de consulta y utilidades --- - [[nodiscard]] static auto getControllerBinding(std::shared_ptr gamepad, Action action) -> SDL_GamepadButton; + [[nodiscard]] static auto getControllerBinding(const std::shared_ptr &gamepad, Action action) -> SDL_GamepadButton; [[nodiscard]] static auto inputToString(Action action) -> std::string; [[nodiscard]] static auto stringToInput(const std::string &name) -> Action; @@ -193,8 +193,8 @@ class Input { // --- M茅todos internos --- void initSDLGamePad(); - static auto checkAxisInput(Action action, std::shared_ptr gamepad, bool repeat) -> bool; - static auto checkTriggerInput(Action action, std::shared_ptr gamepad, bool repeat) -> bool; + static auto checkAxisInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool; + static auto checkTriggerInput(Action action, const std::shared_ptr &gamepad, bool repeat) -> bool; auto addGamepad(int device_index) -> std::string; auto removeGamepad(SDL_JoystickID id) -> std::string; void addGamepadMappingsFromFile(); diff --git a/source/item.cpp b/source/item.cpp index 185fa07..49cf697 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -8,7 +8,7 @@ class Texture; // lines 6-6 -Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr texture, const std::vector &animation) +Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr &texture, const std::vector &animation) : sprite_(std::make_unique(texture, animation)), play_area_(play_area), type_(type) { diff --git a/source/item.h b/source/item.h index d4b417c..2930844 100644 --- a/source/item.h +++ b/source/item.h @@ -31,7 +31,7 @@ class Item { static constexpr int COFFEE_MACHINE_HEIGHT = 39; // Altura de la m谩quina de caf茅 // --- Constructor y destructor --- - Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_ptr texture, const std::vector &animation); // Constructor principal + Item(ItemType type, float x, float y, SDL_FRect &play_area, const std::shared_ptr &texture, const std::vector &animation); // Constructor principal ~Item() = default; // Destructor // --- M茅todos principales --- diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp index 3388b89..bcca476 100644 --- a/source/moving_sprite.cpp +++ b/source/moving_sprite.cpp @@ -1,10 +1,12 @@ #include "moving_sprite.h" +#include + #include "texture.h" // Para Texture // Constructor MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos, Rotate rotate, float horizontal_zoom, float vertical_zoom, SDL_FlipMode flip) - : Sprite(texture, pos), + : Sprite(std::move(texture), pos), rotate_(rotate), flip_(flip), x_(pos.x), @@ -13,7 +15,7 @@ MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos, Rota vertical_zoom_(vertical_zoom) {} MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos) - : Sprite(texture, pos), + : Sprite(std::move(texture), pos), flip_(SDL_FLIP_NONE), x_(pos.x), y_(pos.y), @@ -21,7 +23,7 @@ MovingSprite::MovingSprite(std::shared_ptr texture, SDL_FRect pos) vertical_zoom_(1.0F) {} MovingSprite::MovingSprite(std::shared_ptr texture) - : Sprite(texture), + : Sprite(std::move(texture)), flip_(SDL_FLIP_NONE), horizontal_zoom_(1.0F), vertical_zoom_(1.0F) { Sprite::clear(); } diff --git a/source/options.cpp b/source/options.cpp index cd2999d..c2b9db5 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -65,7 +65,7 @@ auto loadFromFile() -> bool { std::string line; while (std::getline(file, line)) { if (line.substr(0, 1) != "#") { - int pos = line.find("="); + int pos = line.find('='); if (!set(line.substr(0, pos), line.substr(pos + 1, line.length()))) { SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "Unknown parameter: %s", line.substr(0, pos).c_str()); } @@ -413,7 +413,7 @@ auto playerIdToString(Player::Id player_id) -> std::string { } // Convierte un texto a player id segun Lang -auto stringToPlayerId(std::string name) -> Player::Id { +auto stringToPlayerId(const std::string& name) -> Player::Id { if (name == Lang::getText("[SERVICE_MENU] PLAYER1")) { return Player::Id::PLAYER1; } diff --git a/source/options.h b/source/options.h index 91b441e..7f8f897 100644 --- a/source/options.h +++ b/source/options.h @@ -11,7 +11,8 @@ #include // Para out_of_range, invalid_argument #include // Para char_traits, string, allocator, operator==, swap, operator<<, basic_string, stoi #include // Para string_view -#include // Para vector +#include +#include // Para vector #include "difficulty.h" // Para Code #include "input.h" // Para Input @@ -139,7 +140,7 @@ class GamepadManager { const std::string& name) -> bool { try { auto& gamepad = getGamepad(player_id); - gamepad.instance = instance; + gamepad.instance = std::move(instance); gamepad.name = name; return true; } catch (const std::exception&) { @@ -156,7 +157,7 @@ class GamepadManager { } void resyncGamepadsWithPlayers() { - for (auto player : players_) { + for (const auto& player : players_) { switch (player->getId()) { case Player::Id::PLAYER1: player->setGamepad(gamepads_[0].instance); @@ -221,11 +222,11 @@ class GamepadManager { return false; } - void addPlayer(std::shared_ptr player) { players_.push_back(player); } // A帽ade un jugador a la lista + void addPlayer(const std::shared_ptr& player) { players_.push_back(player); } // A帽ade un jugador a la lista void clearPlayers() { players_.clear(); } // Limpia la lista de jugadores // Asigna el mando a un jugador - void assignTo(Input::Gamepad gamepad, Player::Id player_id) { + void assignTo(const Input::Gamepad& gamepad, Player::Id player_id) { } // Asigna los mandos f铆sicos bas谩ndose en la configuraci贸n actual de nombres. @@ -274,7 +275,7 @@ struct Keyboard { Player::Id player_id = Player::Id::PLAYER1; // Jugador asociado al teclado std::vector> players; // Punteros a los jugadores - void addPlayer(std::shared_ptr player) { players.push_back(player); } // A帽ade un jugador a la lista + void addPlayer(const std::shared_ptr& player) { players.push_back(player); } // A帽ade un jugador a la lista void clearPlayers() { players.clear(); } // Limpia la lista de jugadores // Asigna el teclado a un jugador @@ -315,7 +316,7 @@ void swapKeyboard(); void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos auto getPlayerWhoUsesKeyboard() -> Player::Id; // Averigua qui茅n est谩 usando el teclado auto playerIdToString(Player::Id player_id) -> std::string; // Convierte un player id a texto segun Lang -auto stringToPlayerId(std::string name) -> Player::Id; // Convierte un texto a player id segun Lang +auto stringToPlayerId(const std::string& name) -> Player::Id; // Convierte un texto a player id segun Lang void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables void checkPendingChanges(); // Verifica si hay cambios pendientes auto assignGamepadByName(const std::string& gamepad_name, Player::Id player_id) -> bool; // Buscar y asignar un mando disponible por nombre diff --git a/source/param.h b/source/param.h index 99de247..5bb50d7 100644 --- a/source/param.h +++ b/source/param.h @@ -56,7 +56,7 @@ struct ParamBalloon { float vel; // Constructor por defecto - constexpr Settings(float grav_val = 0.0f, float vel_val = 0.0f) + constexpr Settings(float grav_val = 0.0F, float vel_val = 0.0F) : grav(grav_val), vel(vel_val) {} }; diff --git a/source/path_sprite.cpp b/source/path_sprite.cpp index 7ae6fbe..82ff9ff 100644 --- a/source/path_sprite.cpp +++ b/source/path_sprite.cpp @@ -83,7 +83,7 @@ void PathSprite::addPath(int start, int end, PathType type, int fixed_pos, int s } // A帽ade un recorrido -void PathSprite::addPath(std::vector spots, int waiting_counter) { +void PathSprite::addPath(const std::vector &spots, int waiting_counter) { paths_.emplace_back(std::move(spots), waiting_counter); } diff --git a/source/path_sprite.h b/source/path_sprite.h index 9fd76e8..9d7b9c9 100644 --- a/source/path_sprite.h +++ b/source/path_sprite.h @@ -4,7 +4,8 @@ #include // Para std::function #include // Para shared_ptr -#include // Para vector +#include +#include // Para vector #include "sprite.h" // Para Sprite @@ -43,7 +44,7 @@ class PathSprite : public Sprite { public: // --- Constructor y destructor --- explicit PathSprite(std::shared_ptr texture) - : Sprite(texture) {} + : Sprite(std::move(texture)) {} ~PathSprite() override = default; // --- M茅todos principales --- @@ -52,7 +53,7 @@ class PathSprite : public Sprite { // --- Gesti贸n de recorridos --- void addPath(Path path, bool centered = false); // A帽ade un recorrido (Path) - void addPath(std::vector spots, int waiting_counter = 0); // A帽ade un recorrido a partir de puntos + void addPath(const std::vector &spots, int waiting_counter = 0); // A帽ade un recorrido a partir de puntos void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function &easing_function, int waiting_counter = 0); // A帽ade un recorrido generado // --- Estado y control --- diff --git a/source/pause_manager.h b/source/pause_manager.h index 4be1544..0110463 100644 --- a/source/pause_manager.h +++ b/source/pause_manager.h @@ -115,7 +115,7 @@ class PauseManager { return result; } void setCallback(std::function callback) { // Permite cambiar el callback en runtime - on_pause_changed_callback_ = callback; + on_pause_changed_callback_ = std::move(callback); } private: diff --git a/source/player.h b/source/player.h index ae73557..33af336 100644 --- a/source/player.h +++ b/source/player.h @@ -186,7 +186,7 @@ class Player { void setWalkingState(State state) { walking_state_ = state; } void addCredit(); - void setGamepad(std::shared_ptr gamepad) { gamepad_ = gamepad; } + void setGamepad(std::shared_ptr gamepad) { gamepad_ = std::move(gamepad); } [[nodiscard]] auto getGamepad() const -> std::shared_ptr { return gamepad_; } void setUsesKeyboard(bool value) { uses_keyboard_ = value; } [[nodiscard]] auto getUsesKeyboard() const -> bool { return uses_keyboard_; } diff --git a/source/resource.cpp b/source/resource.cpp index 3e1e3b1..6a62847 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -571,15 +571,15 @@ void Resource::createPlayerTextures() { texture_copy->addPaletteFromPalFile(Asset::get()->get(player.palette_files[2])); // A帽ade los colores establecidos en param.player usando el 铆ndice del jugador (player_idx) - texture_copy->setPaletteColor(1, 16, param.player.one_coffee_shirt[player_idx].darkest.toUint32()); - texture_copy->setPaletteColor(1, 17, param.player.one_coffee_shirt[player_idx].dark.toUint32()); - texture_copy->setPaletteColor(1, 18, param.player.one_coffee_shirt[player_idx].base.toUint32()); - texture_copy->setPaletteColor(1, 19, param.player.one_coffee_shirt[player_idx].light.toUint32()); + texture_copy->setPaletteColor(1, 16, param.player.one_coffee_shirt[player_idx].darkest.TO_UINT32()); + texture_copy->setPaletteColor(1, 17, param.player.one_coffee_shirt[player_idx].dark.TO_UINT32()); + texture_copy->setPaletteColor(1, 18, param.player.one_coffee_shirt[player_idx].base.TO_UINT32()); + texture_copy->setPaletteColor(1, 19, param.player.one_coffee_shirt[player_idx].light.TO_UINT32()); - texture_copy->setPaletteColor(2, 16, param.player.two_coffee_shirt[player_idx].darkest.toUint32()); - texture_copy->setPaletteColor(2, 17, param.player.two_coffee_shirt[player_idx].dark.toUint32()); - texture_copy->setPaletteColor(2, 18, param.player.two_coffee_shirt[player_idx].base.toUint32()); - texture_copy->setPaletteColor(2, 19, param.player.two_coffee_shirt[player_idx].light.toUint32()); + texture_copy->setPaletteColor(2, 16, param.player.two_coffee_shirt[player_idx].darkest.TO_UINT32()); + texture_copy->setPaletteColor(2, 17, param.player.two_coffee_shirt[player_idx].dark.TO_UINT32()); + texture_copy->setPaletteColor(2, 18, param.player.two_coffee_shirt[player_idx].base.TO_UINT32()); + texture_copy->setPaletteColor(2, 19, param.player.two_coffee_shirt[player_idx].light.TO_UINT32()); // Cambiar a la paleta espec铆fica (铆ndice i+1 porque 0 es la original) texture_copy->setPalette(i + 1); diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index 80e8df7..809018c 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -39,8 +39,8 @@ Credits::Credits() tiled_bg_(std::make_unique(param.game.game_area.rect, TiledBGMode::DIAGONAL)), fade_in_(std::make_unique()), fade_out_(std::make_unique()), - text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), - canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)) { + text_texture_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast(param.game.width), static_cast(param.game.height))), + canvas_(SDL_CreateTexture(Screen::get()->getRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, static_cast(param.game.width), static_cast(param.game.height))) { if (text_texture_ == nullptr) { throw std::runtime_error("Failed to create SDL texture for text."); } @@ -48,13 +48,13 @@ Credits::Credits() balloon_manager_->setPlayArea(play_area_); fade_in_->setColor(param.fade.color); - fade_in_->setType(FadeType::FULLSCREEN); + fade_in_->setType(Fade::Type::FULLSCREEN); fade_in_->setPostDuration(50); - fade_in_->setMode(FadeMode::IN); + fade_in_->setMode(Fade::Mode::IN); fade_in_->activate(); fade_out_->setColor(0, 0, 0); - fade_out_->setType(FadeType::FULLSCREEN); + fade_out_->setType(Fade::Type::FULLSCREEN); fade_out_->setPostDuration(400); updateRedRect(); @@ -63,7 +63,7 @@ Credits::Credits() initPlayers(); SDL_SetTextureBlendMode(text_texture_, SDL_BLENDMODE_BLEND); fillTextTexture(); - steps_ = std::abs((top_black_rect_.h - param.game.game_area.center_y - 1) + ((left_black_rect_.w - param.game.game_area.center_x) / 4)); + steps_ = static_cast(std::abs((top_black_rect_.h - param.game.game_area.center_y - 1) + ((left_black_rect_.w - param.game.game_area.center_x) / 4))); } // Destructor @@ -171,57 +171,59 @@ void Credits::fillTextTexture() { const int SPACE_POST_TITLE = 3 + text->getCharacterSize(); const int SPACE_PRE_TITLE = text->getCharacterSize() * 4; const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE; - credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT; + const int POS_X = static_cast(param.game.game_area.center_x); + credits_rect_dst_.h = credits_rect_src_.h = static_cast(TEXTS_HEIGHT); + auto text_style = Text::Style(Text::CENTER | Text::SHADOW, NO_TEXT_COLOR, SHADOW_TEXT_COLOR); // PROGRAMMED_AND_DESIGNED_BY int y = 0; - text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text_grad->writeStyle(POS_X, y, TEXTS.at(0), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(4), text_style); // PIXELART_DRAWN_BY y += SPACE_PRE_TITLE; - text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(1), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text_grad->writeStyle(POS_X, y, TEXTS.at(1), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(4), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(4), text_style); // MUSIC_COMPOSED_BY y += SPACE_PRE_TITLE; - text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(2), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text_grad->writeStyle(POS_X, y, TEXTS.at(2), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(5), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(5), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(6), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(6), text_style); // SOUND_EFFECTS y += SPACE_PRE_TITLE; - text_grad->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(3), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text_grad->writeStyle(POS_X, y, TEXTS.at(3), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(7), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(7), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(8), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(8), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(9), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(9), text_style); y += SPACE_POST_TITLE; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, TEXTS.at(10), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeStyle(POS_X, y, TEXTS.at(10), text_style); // Mini logo y += SPACE_PRE_TITLE; - mini_logo_rect_src_.y = y; + mini_logo_rect_src_.y = static_cast(y); auto mini_logo_sprite = std::make_unique(Resource::get()->getTexture("logo_jailgames_mini.png")); - mini_logo_sprite->setPosition(1 + param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, 1 + y); + mini_logo_sprite->setPosition(1 + POS_X - mini_logo_sprite->getWidth() / 2, 1 + y); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(SHADOW_TEXT_COLOR.r, SHADOW_TEXT_COLOR.g, SHADOW_TEXT_COLOR.b); mini_logo_sprite->render(); - mini_logo_sprite->setPosition(param.game.game_area.center_x - mini_logo_sprite->getWidth() / 2, y); + mini_logo_sprite->setPosition(POS_X - mini_logo_sprite->getWidth() / 2, y); Resource::get()->getTexture("logo_jailgames_mini.png")->setColor(255, 255, 255); mini_logo_sprite->render(); // Texto con el copyright y += mini_logo_sprite->getHeight() + 3; - text->writeDX(Text::CENTER | Text::SHADOW, param.game.game_area.center_x, y, std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + text->writeDX(Text::CENTER | Text::SHADOW, POS_X, y, std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); // Resetea el renderizador SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); @@ -384,7 +386,7 @@ void Credits::initPlayers() { players_.back()->setPlayingState(Player::State::CREDITS); // Registra los jugadores en Options - for (auto player : players_) { + for (const auto &player : players_) { Options::keyboard.addPlayer(player); Options::gamepad_manager.addPlayer(player); } diff --git a/source/sections/game.cpp b/source/sections/game.cpp index ad1b8a2..9268b10 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -81,13 +81,13 @@ Game::Game(Player::Id player_id, int current_stage, bool demo) fade_in_->setColor(param.fade.color); fade_in_->setPreDuration(demo_.enabled ? 80 : 0); fade_in_->setPostDuration(0); - fade_in_->setType(FadeType::RANDOM_SQUARE); - fade_in_->setMode(FadeMode::IN); + fade_in_->setType(Fade::Type::RANDOM_SQUARE); + fade_in_->setMode(Fade::Mode::IN); fade_in_->activate(); fade_out_->setColor(param.fade.color); fade_out_->setPostDuration(param.fade.post_duration); - fade_out_->setType(FadeType::VENETIAN); + fade_out_->setType(Fade::Type::VENETIAN); background_->setPos(param.game.play_area.rect); @@ -230,7 +230,7 @@ void Game::updatePlayers() { handlePlayerCollision(player, balloon); if (demo_.enabled && allPlayersAreNotPlaying()) { - fade_out_->setType(FadeType::RANDOM_SQUARE); + fade_out_->setType(Fade::Type::RANDOM_SQUARE); fade_out_->activate(); } } @@ -549,7 +549,7 @@ void Game::checkBulletCollision() { } // Maneja la colisi贸n entre bala y Tabe -auto Game::checkBulletTabeCollision(std::shared_ptr bullet) -> bool { +auto Game::checkBulletTabeCollision(const std::shared_ptr &bullet) -> bool { if (!tabe_->isEnabled()) { return false; } @@ -581,7 +581,7 @@ void Game::handleTabeHitEffects() { } // Maneja la colisi贸n entre bala y globos -auto Game::checkBulletBalloonCollision(std::shared_ptr bullet) -> bool { +auto Game::checkBulletBalloonCollision(const std::shared_ptr &bullet) -> bool { for (auto &balloon : balloon_manager_->getBalloons()) { if (!balloon->isEnabled() || balloon->isInvulnerable()) { continue; @@ -598,7 +598,7 @@ auto Game::checkBulletBalloonCollision(std::shared_ptr bullet) -> bool { } // Procesa el impacto en un globo -void Game::processBalloonHit(std::shared_ptr bullet, std::shared_ptr balloon) { +void Game::processBalloonHit(const std::shared_ptr &bullet, const std::shared_ptr &balloon) { auto player = getPlayer(bullet->getOwner()); handleItemDrop(balloon, player); @@ -608,7 +608,7 @@ void Game::processBalloonHit(std::shared_ptr bullet, std::shared_ptr balloon, std::shared_ptr player) { +void Game::handleItemDrop(const std::shared_ptr &balloon, const std::shared_ptr &player) { const auto DROPPED_ITEM = dropItem(); if (DROPPED_ITEM == ItemType::NONE || demo_.recording) { return; @@ -623,9 +623,9 @@ void Game::handleItemDrop(std::shared_ptr balloon, std::shared_ptr balloon, std::shared_ptr player) { +void Game::handleBalloonDestruction(std::shared_ptr balloon, const std::shared_ptr &player) { if (player->isPlaying()) { - auto const SCORE = balloon_manager_->popBalloon(balloon) * player->getScoreMultiplier() * difficulty_score_multiplier_; + auto const SCORE = balloon_manager_->popBalloon(std::move(balloon)) * player->getScoreMultiplier() * difficulty_score_multiplier_; player->addScore(SCORE, Options::settings.hi_score_table.back().score); player->incScoreMultiplier(); } @@ -758,7 +758,7 @@ void Game::freeItems() { } // Crea un objeto PathSprite -void Game::createItemText(int x, std::shared_ptr texture) { +void Game::createItemText(int x, const std::shared_ptr &texture) { path_sprites_.emplace_back(std::make_unique(texture)); const auto W = texture->getWidth(); @@ -781,7 +781,7 @@ void Game::createItemText(int x, std::shared_ptr texture) { } // Crea un objeto PathSprite -void Game::createMessage(const std::vector &paths, std::shared_ptr texture) { +void Game::createMessage(const std::vector &paths, const std::shared_ptr &texture) { path_sprites_.emplace_back(std::make_unique(texture)); // Inicializa @@ -1239,7 +1239,7 @@ void Game::checkInput() { // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego. void Game::checkPauseInput() { // Comprueba los mandos - for (auto gamepad : input_->getGamepads()) { + for (const auto &gamepad : input_->getGamepads()) { if (input_->checkAction(Input::Action::PAUSE, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { pause_manager_->togglePlayerPause(); return; @@ -1616,7 +1616,7 @@ void Game::initPlayers(Player::Id player_id) { } // Registra los jugadores en Options - for (auto player : players_) { + for (const auto &player : players_) { Options::keyboard.addPlayer(player); Options::gamepad_manager.addPlayer(player); } @@ -1660,7 +1660,7 @@ void Game::updateDemo() { // Activa el fundido antes de acabar con los datos de la demo if (demo_.counter == TOTAL_DEMO_DATA - 200) { - fade_out_->setType(FadeType::RANDOM_SQUARE); + fade_out_->setType(Fade::Type::RANDOM_SQUARE); fade_out_->activate(); } @@ -1777,11 +1777,11 @@ void Game::updateMenace() { } const auto &stage = current_stage.value(); - const double fraction = stage_manager_->getCurrentStageProgressFraction(); - const int difference = stage.getMaxMenace() - stage.getMinMenace(); + const double FRACTION = stage_manager_->getCurrentStageProgressFraction(); + const int DIFFERENCE = stage.getMaxMenace() - stage.getMinMenace(); // Aumenta el nivel de amenaza en funci贸n del progreso de la fase - menace_threshold_ = stage.getMinMenace() + (difference * fraction); + menace_threshold_ = stage.getMinMenace() + (DIFFERENCE * FRACTION); if (menace_ < menace_threshold_) { balloon_manager_->deployRandomFormation(stage_manager_->getCurrentStageIndex()); @@ -1940,14 +1940,14 @@ void Game::handleDebugEvents(const SDL_Event &event) { ++formation_id_; balloon_manager_->destroyAllBalloons(); balloon_manager_->deployFormation(formation_id_); - std::cout << formation_id_ << std::endl; + std::cout << formation_id_ << '\n'; break; } case SDLK_KP_MINUS: { --formation_id_; balloon_manager_->destroyAllBalloons(); balloon_manager_->deployFormation(formation_id_); - std::cout << formation_id_ << std::endl; + std::cout << formation_id_ << '\n'; break; } default: diff --git a/source/sections/game.h b/source/sections/game.h index d336f0f..77e62cf 100644 --- a/source/sections/game.h +++ b/source/sections/game.h @@ -216,9 +216,9 @@ class Game { void freeBullets(); // Libera memoria del vector de balas // --- Colisiones espec铆ficas de balas --- - auto checkBulletTabeCollision(std::shared_ptr bullet) -> bool; // Detecta colisi贸n bala-Tabe - auto checkBulletBalloonCollision(std::shared_ptr bullet) -> bool; // Detecta colisi贸n bala-globo - void processBalloonHit(std::shared_ptr bullet, std::shared_ptr balloon); // Procesa impacto en globo + auto checkBulletTabeCollision(const std::shared_ptr &bullet) -> bool; // Detecta colisi贸n bala-Tabe + auto checkBulletBalloonCollision(const std::shared_ptr &bullet) -> bool; // Detecta colisi贸n bala-globo + void processBalloonHit(const std::shared_ptr &bullet, const std::shared_ptr &balloon); // Procesa impacto en globo // --- Sistema de 铆tems y power-ups --- void updateItems(); // Actualiza posici贸n y estado de todos los 铆tems @@ -235,7 +235,7 @@ class Game { void throwCoffee(int x, int y); // Crea efecto de caf茅 arrojado al ser golpeado // --- Gesti贸n de ca铆da de 铆tems --- - void handleItemDrop(std::shared_ptr balloon, std::shared_ptr player); // Gestiona ca铆da de 铆tem desde globo + void handleItemDrop(const std::shared_ptr &balloon, const std::shared_ptr &player); // Gestiona ca铆da de 铆tem desde globo // --- Sprites inteligentes (smartsprites) --- void updateSmartSprites(); // Actualiza todos los sprites con l贸gica propia @@ -249,11 +249,11 @@ class Game { void initPaths(); // Inicializa rutas predefinidas para animaciones // --- Creaci贸n de sprites especiales --- - void createItemText(int x, std::shared_ptr texture); // Crea texto animado para 铆tems - void createMessage(const std::vector &paths, std::shared_ptr texture); // Crea mensaje con animaci贸n por ruta + void createItemText(int x, const std::shared_ptr &texture); // Crea texto animado para 铆tems + void createMessage(const std::vector &paths, const std::shared_ptr &texture); // Crea mensaje con animaci贸n por ruta // --- Sistema de globos y enemigos --- - void handleBalloonDestruction(std::shared_ptr balloon, std::shared_ptr player); // Procesa destrucci贸n de globo + void handleBalloonDestruction(std::shared_ptr balloon, const std::shared_ptr &player); // Procesa destrucci贸n de globo void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos seg煤n progreso diff --git a/source/sections/hiscore_table.cpp b/source/sections/hiscore_table.cpp index b94728f..eb9660b 100644 --- a/source/sections/hiscore_table.cpp +++ b/source/sections/hiscore_table.cpp @@ -36,7 +36,7 @@ HiScoreTable::HiScoreTable() ticks_(0), view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}), - fade_mode_(FadeMode::IN), + fade_mode_(Fade::Mode::IN), background_fade_color_(Color(0, 0, 0)) { // Inicializa el resto Section::name = Section::Name::HI_SCORE_TABLE; @@ -133,13 +133,13 @@ void HiScoreTable::run() { void HiScoreTable::updateFade() { fade_->update(); - if (fade_->hasEnded() && fade_mode_ == FadeMode::IN) { + if (fade_->hasEnded() && fade_mode_ == Fade::Mode::IN) { fade_->reset(); - fade_mode_ = FadeMode::OUT; + fade_mode_ = Fade::Mode::OUT; fade_->setMode(fade_mode_); } - if (fade_->hasEnded() && fade_mode_ == FadeMode::OUT) { + if (fade_->hasEnded() && fade_mode_ == Fade::Mode::OUT) { Section::name = (Section::options == Section::Options::HI_SCORE_AFTER_PLAYING) ? Section::Name::TITLE : Section::Name::INSTRUCTIONS; @@ -272,7 +272,7 @@ void HiScoreTable::updateSprites() { // Inicializa el fade void HiScoreTable::initFade() { fade_->setColor(param.fade.color); - fade_->setType(FadeType::RANDOM_SQUARE); + fade_->setType(Fade::Type::RANDOM_SQUARE); fade_->setPostDuration(param.fade.post_duration); fade_->setMode(fade_mode_); fade_->activate(); diff --git a/source/sections/hiscore_table.h b/source/sections/hiscore_table.h index 475df81..606c93c 100644 --- a/source/sections/hiscore_table.h +++ b/source/sections/hiscore_table.h @@ -7,12 +7,11 @@ #include // Para vector #include "color.h" // Para Color +#include "fade.h" // Para Fade #include "path_sprite.h" // Para Path, PathSprite (ptr only) class Background; -class Fade; class Sprite; -enum class FadeMode : Uint8; // --- Clase HiScoreTable: muestra la tabla de puntuaciones m谩s altas --- // Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones @@ -48,7 +47,7 @@ class HiScoreTable { Uint16 counter_ = 0; // Contador Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla - FadeMode fade_mode_; // Modo de fade a utilizar + Fade::Mode fade_mode_; // Modo de fade a utilizar Color background_fade_color_; // Color de atenuaci贸n del fondo std::vector entry_colors_; // Colores para destacar las entradas en la tabla diff --git a/source/sections/instructions.cpp b/source/sections/instructions.cpp index acc6c65..37be929 100644 --- a/source/sections/instructions.cpp +++ b/source/sections/instructions.cpp @@ -43,9 +43,9 @@ Instructions::Instructions() // Inicializa objetos tiled_bg_->setColor(param.title.bg_color); fade_->setColor(param.fade.color); - fade_->setType(FadeType::FULLSCREEN); + fade_->setType(Fade::Type::FULLSCREEN); fade_->setPostDuration(param.fade.post_duration); - fade_->setMode(FadeMode::IN); + fade_->setMode(Fade::Mode::IN); fade_->activate(); // Inicializa las l铆neas con un retraso progresivo de 50 ms diff --git a/source/sections/title.cpp b/source/sections/title.cpp index a8cf149..9016c7e 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -49,7 +49,7 @@ Title::Title() game_logo_->enable(); mini_logo_sprite_->setX(param.game.game_area.center_x - mini_logo_sprite_->getWidth() / 2); fade_->setColor(param.fade.color); - fade_->setType(FadeType::RANDOM_SQUARE); + fade_->setType(Fade::Type::RANDOM_SQUARE); fade_->setPostDuration(param.fade.post_duration); initPlayers(); @@ -201,7 +201,7 @@ void Title::printColorValue(const Color& color) { << std::hex << std::setw(2) << std::setfill('0') << (int)color.r << std::setw(2) << std::setfill('0') << (int)color.g << std::setw(2) << std::setfill('0') << (int)color.b - << std::endl; + << '\n'; } #endif @@ -538,7 +538,7 @@ void Title::initPlayers() { players_.back()->setPlayingState(Player::State::TITLE_HIDDEN); // Registra los jugadores en Options - for (auto player : players_) { + for (const auto& player : players_) { Options::keyboard.addPlayer(player); Options::gamepad_manager.addPlayer(player); } diff --git a/source/shutdown.cpp b/source/shutdown.cpp index c7804c0..36304f0 100644 --- a/source/shutdown.cpp +++ b/source/shutdown.cpp @@ -13,40 +13,40 @@ namespace SystemShutdown { #ifndef _WIN32 // Funci贸n auxiliar para sistemas Unix-like - ShutdownResult executeUnixShutdown(const char* command, char* const args[]) { - pid_t pid = fork(); - - if (pid == 0) { - // Proceso hijo - execvp(command, args); - // Si llegamos aqu铆, execvp fall贸 - std::cerr << "Error: No se pudo ejecutar " << command << std::endl; - _exit(1); - } else if (pid > 0) { - // Proceso padre - int status; - waitpid(pid, &status, 0); - return (WEXITSTATUS(status) == 0) ? ShutdownResult::SUCCESS : ShutdownResult::ERROR_SYSTEM_CALL; - } else { - return ShutdownResult::ERROR_FORK_FAILED; - } +auto executeUnixShutdown(const char* command, char* const args[]) -> ShutdownResult { + pid_t pid = fork(); + + if (pid == 0) { + // Proceso hijo + execvp(command, args); + // Si llegamos aqu铆, execvp fall贸 + std::cerr << "Error: No se pudo ejecutar " << command << '\n'; + _exit(1); + } else if (pid > 0) { + // Proceso padre + int status; + waitpid(pid, &status, 0); + return (WEXITSTATUS(status) == 0) ? ShutdownResult::SUCCESS : ShutdownResult::ERROR_SYSTEM_CALL; + } else { + return ShutdownResult::ERROR_FORK_FAILED; } +} #endif // Implementaci贸n de las funciones p煤blicas - ShutdownResult shutdownSystem() { - ShutdownConfig config; - return shutdownSystem(config); - } +auto shutdownSystem() -> ShutdownResult { + ShutdownConfig config; + return shutdownSystem(config); +} - ShutdownResult shutdownSystem(int delay_seconds, bool force_apps) { - ShutdownConfig config; - config.delay_seconds = delay_seconds; - config.force_close_apps = force_apps; - return shutdownSystem(config); - } +auto shutdownSystem(int delay_seconds, bool force_apps) -> ShutdownResult { + ShutdownConfig config; + config.delay_seconds = delay_seconds; + config.force_close_apps = force_apps; + return shutdownSystem(config); +} - ShutdownResult shutdownSystem(const ShutdownConfig& config) { +auto shutdownSystem(const ShutdownConfig& config) -> ShutdownResult { #ifdef _WIN32 // Windows: Usar CreateProcess STARTUPINFOA si = {0}; @@ -107,42 +107,41 @@ namespace SystemShutdown { const_cast("shutdown"), const_cast("-h"), const_cast("now"), - NULL - }; - + nullptr}; + return executeUnixShutdown("shutdown", args); #else return ShutdownResult::ERROR_UNSUPPORTED; #endif - } +} - const char* resultToString(ShutdownResult result) { - switch (result) { - case ShutdownResult::SUCCESS: - return "Apagado iniciado exitosamente"; - case ShutdownResult::ERROR_PERMISSION: - return "Error: Permisos insuficientes"; - case ShutdownResult::ERROR_SYSTEM_CALL: - return "Error: Fallo en la llamada al sistema"; - case ShutdownResult::ERROR_FORK_FAILED: - return "Error: No se pudo crear proceso hijo"; - case ShutdownResult::ERROR_UNSUPPORTED: - return "Error: Sistema operativo no soportado"; - default: - return "Error desconocido"; - } +auto resultToString(ShutdownResult result) -> const char* { + switch (result) { + case ShutdownResult::SUCCESS: + return "Apagado iniciado exitosamente"; + case ShutdownResult::ERROR_PERMISSION: + return "Error: Permisos insuficientes"; + case ShutdownResult::ERROR_SYSTEM_CALL: + return "Error: Fallo en la llamada al sistema"; + case ShutdownResult::ERROR_FORK_FAILED: + return "Error: No se pudo crear proceso hijo"; + case ShutdownResult::ERROR_UNSUPPORTED: + return "Error: Sistema operativo no soportado"; + default: + return "Error desconocido"; } +} - bool isShutdownSupported() { +auto isShutdownSupported() -> bool { #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) return true; #else return false; #endif - } +} - const char* getRequiredPermissions() { +auto getRequiredPermissions() -> const char* { #ifdef _WIN32 return "Requiere permisos de Administrador en Windows"; #elif defined(__APPLE__) || defined(__linux__) @@ -150,6 +149,6 @@ namespace SystemShutdown { #else return "Sistema no soportado"; #endif - } +} } // namespace SystemShutdown \ No newline at end of file diff --git a/source/shutdown.h b/source/shutdown.h index d473010..52b1d7d 100644 --- a/source/shutdown.h +++ b/source/shutdown.h @@ -14,24 +14,22 @@ enum class ShutdownResult { // --- Estructuras --- struct ShutdownConfig { - int delay_seconds; // Segundos de retraso antes del apagado - bool force_close_apps; // Forzar cierre de aplicaciones - const char* shutdown_message; // Mensaje mostrado durante el apagado - - // Constructor con valores por defecto - ShutdownConfig() - : delay_seconds(5) - , force_close_apps(true) - , shutdown_message("El sistema se apagar谩...") - {} + int delay_seconds{5}; // Segundos de retraso antes del apagado + bool force_close_apps{true}; // Forzar cierre de aplicaciones + const char* shutdown_message{"El sistema se apagar谩..."}; // Mensaje mostrado durante el apagado + + // Constructor con valores por defecto + ShutdownConfig() + + {} }; // --- Funciones --- -ShutdownResult shutdownSystem(); // Apaga el sistema con configuraci贸n por defecto -ShutdownResult shutdownSystem(const ShutdownConfig& config); // Apaga el sistema con configuraci贸n personalizada -ShutdownResult shutdownSystem(int delay_seconds, bool force_apps = true); // Apaga el sistema con par谩metros simples -const char* resultToString(ShutdownResult result); // Convierte un c贸digo de resultado a string descriptivo -bool isShutdownSupported(); // Verifica si el sistema actual soporta apagado program谩tico -const char* getRequiredPermissions(); // Obtiene informaci贸n sobre los permisos necesarios +auto shutdownSystem() -> ShutdownResult; // Apaga el sistema con configuraci贸n por defecto +auto shutdownSystem(const ShutdownConfig& config) -> ShutdownResult; // Apaga el sistema con configuraci贸n personalizada +auto shutdownSystem(int delay_seconds, bool force_apps = true) -> ShutdownResult; // Apaga el sistema con par谩metros simples +auto resultToString(ShutdownResult result) -> const char*; // Convierte un c贸digo de resultado a string descriptivo +auto isShutdownSupported() -> bool; // Verifica si el sistema actual soporta apagado program谩tico +auto getRequiredPermissions() -> const char*; // Obtiene informaci贸n sobre los permisos necesarios } // namespace SystemShutdown diff --git a/source/smart_sprite.h b/source/smart_sprite.h index fbb63d6..347b6ee 100644 --- a/source/smart_sprite.h +++ b/source/smart_sprite.h @@ -1,6 +1,7 @@ #pragma once #include // Para shared_ptr +#include #include "animated_sprite.h" // Para AnimatedSprite @@ -11,7 +12,7 @@ class SmartSprite : public AnimatedSprite { public: // --- Constructor y destructor --- explicit SmartSprite(std::shared_ptr texture) - : AnimatedSprite(texture) {} + : AnimatedSprite(std::move(texture)) {} ~SmartSprite() override = default; // --- M茅todos principales --- diff --git a/source/sprite.cpp b/source/sprite.cpp index 1cbd077..7ef2430 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -1,22 +1,23 @@ #include "sprite.h" +#include #include // Para vector #include "texture.h" // Para Texture // Constructor Sprite::Sprite(std::shared_ptr texture, float pos_x, float pos_y, float width, float height) - : textures_{texture}, + : textures_{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) - : textures_{texture}, + : textures_{std::move(texture)}, pos_(rect), sprite_clip_((SDL_FRect){0, 0, pos_.w, pos_.h}) {} Sprite::Sprite(std::shared_ptr texture) - : textures_{texture}, + : textures_{std::move(texture)}, pos_(SDL_FRect{0, 0, static_cast(textures_.at(texture_index_)->getWidth()), static_cast(textures_.at(texture_index_)->getHeight())}), sprite_clip_(pos_) {} diff --git a/source/sprite.h b/source/sprite.h index a40a700..bcd755f 100644 --- a/source/sprite.h +++ b/source/sprite.h @@ -4,7 +4,8 @@ #include // Para size_t #include // Para shared_ptr -#include // Para vector +#include +#include // Para vector class Texture; @@ -52,8 +53,8 @@ class Sprite { // --- Textura --- [[nodiscard]] auto getTexture() const -> std::shared_ptr { return textures_.at(texture_index_); } - void setTexture(std::shared_ptr texture) { textures_.at(texture_index_) = texture; } - void addTexture(std::shared_ptr texture) { textures_.push_back(texture); } + void setTexture(std::shared_ptr texture) { textures_.at(texture_index_) = std::move(texture); } + void addTexture(const std::shared_ptr& texture) { textures_.push_back(texture); } auto setActiveTexture(size_t index) -> bool; // Cambia la textura activa por 铆ndice [[nodiscard]] auto getActiveTextureIndex() const -> size_t { return texture_index_; } // Obtiene el 铆ndice de la textura activa [[nodiscard]] auto getTextureCount() const -> size_t { return textures_.size(); } // Obtiene el n煤mero total de texturas diff --git a/source/stage.cpp b/source/stage.cpp index a0724cd..8416bf7 100644 --- a/source/stage.cpp +++ b/source/stage.cpp @@ -3,11 +3,12 @@ #include #include #include +#include // Implementaci贸n de StageData -StageData::StageData(int power_to_complete, int min_menace, int max_menace, const std::string& name) +StageData::StageData(int power_to_complete, int min_menace, int max_menace, std::string name) : status_(StageStatus::LOCKED), - name_(name), + name_(std::move(name)), power_to_complete_(power_to_complete), min_menace_(min_menace), max_menace_(max_menace) {} @@ -59,7 +60,7 @@ void StageManager::createDefaultStages() { stages_.emplace_back(950, 7 + (4 * 7), 7 + (4 * 10), "Maestr铆a"); } -bool StageManager::loadStagesFromFile(const std::string& filename) { +auto StageManager::loadStagesFromFile(const std::string& filename) -> bool { std::ifstream file(filename); if (!file.is_open()) { return false; // No se pudo abrir el archivo @@ -119,7 +120,7 @@ bool StageManager::loadStagesFromFile(const std::string& filename) { return !stages_.empty(); } -bool StageManager::advanceToNextStage() { +auto StageManager::advanceToNextStage() -> bool { if (!isCurrentStageCompleted() || current_stage_index_ >= stages_.size() - 1) { return false; } @@ -130,7 +131,7 @@ bool StageManager::advanceToNextStage() { return true; } -bool StageManager::jumpToStage(size_t target_stage_index) { +auto StageManager::jumpToStage(size_t target_stage_index) -> bool { if (!validateStageIndex(target_stage_index)) { return false; } @@ -150,7 +151,7 @@ bool StageManager::jumpToStage(size_t target_stage_index) { return true; } -bool StageManager::subtractPower(int amount) { +auto StageManager::subtractPower(int amount) -> bool { if (amount <= 0 || current_power_ < amount) { return false; } @@ -168,18 +169,18 @@ void StageManager::disablePowerCollection() { power_collection_state_ = PowerCollectionState::DISABLED; } -std::optional StageManager::getCurrentStage() const { +auto StageManager::getCurrentStage() const -> std::optional { return getStage(current_stage_index_); } -std::optional StageManager::getStage(size_t index) const { +auto StageManager::getStage(size_t index) const -> std::optional { if (!validateStageIndex(index)) { return std::nullopt; } return stages_[index]; } -bool StageManager::isCurrentStageCompleted() const { +auto StageManager::isCurrentStageCompleted() const -> bool { auto current_stage = getCurrentStage(); if (!current_stage.has_value()) { return false; @@ -188,24 +189,28 @@ bool StageManager::isCurrentStageCompleted() const { return current_power_ >= current_stage->getPowerToComplete(); } -bool StageManager::isGameCompleted() const { +auto StageManager::isGameCompleted() const -> bool { return current_stage_index_ >= stages_.size() - 1 && isCurrentStageCompleted(); } -double StageManager::getProgressPercentage() const { - if (stages_.empty()) return 0.0; +auto StageManager::getProgressPercentage() const -> double { + if (stages_.empty()) { + return 0.0; + } int total_power_needed = getTotalPowerNeededToCompleteGame(); - if (total_power_needed == 0) return 100.0; + if (total_power_needed == 0) { + return 100.0; + } return (static_cast(total_power_) / total_power_needed) * 100.0; } -double StageManager::getCurrentStageProgressPercentage() const { +auto StageManager::getCurrentStageProgressPercentage() const -> double { return getCurrentStageProgressFraction() * 100.0; } -double StageManager::getCurrentStageProgressFraction() const { +auto StageManager::getCurrentStageProgressFraction() const -> double { auto current_stage = getCurrentStage(); if (!current_stage.has_value()) { return 0.0; @@ -221,7 +226,7 @@ double StageManager::getCurrentStageProgressFraction() const { return std::min(fraction, 1.0); } -int StageManager::getPowerNeededForCurrentStage() const { +auto StageManager::getPowerNeededForCurrentStage() const -> int { auto current_stage = getCurrentStage(); if (!current_stage.has_value()) { return 0; @@ -230,7 +235,7 @@ int StageManager::getPowerNeededForCurrentStage() const { return std::max(0, current_stage->getPowerToComplete() - current_power_); } -int StageManager::getTotalPowerNeededToCompleteGame() const { +auto StageManager::getTotalPowerNeededToCompleteGame() const -> int { int total_power_needed = 0; for (const auto& stage : stages_) { total_power_needed += stage.getPowerToComplete(); @@ -239,7 +244,7 @@ int StageManager::getTotalPowerNeededToCompleteGame() const { } // Implementaci贸n de la interfaz IStageInfo -bool StageManager::canCollectPower() const { +auto StageManager::canCollectPower() const -> bool { return power_collection_state_ == PowerCollectionState::ENABLED; } @@ -267,7 +272,7 @@ void StageManager::addPower(int amount) { updateStageStatuses(); } -int StageManager::getCurrentMenaceLevel() const { +auto StageManager::getCurrentMenaceLevel() const -> int { auto current_stage = getCurrentStage(); if (!current_stage.has_value()) { return 0; @@ -278,7 +283,7 @@ int StageManager::getCurrentMenaceLevel() const { // Gesti贸n de callbacks void StageManager::setPowerChangeCallback(PowerChangeCallback callback) { - power_change_callback_ = callback; + power_change_callback_ = std::move(callback); } void StageManager::removePowerChangeCallback() { @@ -286,7 +291,7 @@ void StageManager::removePowerChangeCallback() { } // M茅todos privados -bool StageManager::validateStageIndex(size_t index) const { +auto StageManager::validateStageIndex(size_t index) const -> bool { return index < stages_.size(); } diff --git a/source/stage.h b/source/stage.h index 1595984..1ae8009 100644 --- a/source/stage.h +++ b/source/stage.h @@ -23,7 +23,7 @@ enum class StageStatus { class StageData { public: // --- Constructor --- - StageData(int power_to_complete, int min_menace, int max_menace, const std::string& name = ""); // Constructor de una fase + StageData(int power_to_complete, int min_menace, int max_menace, std::string name = ""); // Constructor de una fase // --- Getters --- [[nodiscard]] auto getPowerToComplete() const -> int { return power_to_complete_; } // Obtiene el poder necesario para completar diff --git a/source/stage_interface.h b/source/stage_interface.h index dc6c308..aafd8b0 100644 --- a/source/stage_interface.h +++ b/source/stage_interface.h @@ -10,9 +10,9 @@ public: virtual ~IStageInfo() = default; // Interfaz de recolecci贸n de poder - virtual bool canCollectPower() const = 0; + [[nodiscard]] virtual auto canCollectPower() const -> bool = 0; virtual void addPower(int amount) = 0; // Ajuste de comportamiento del gameplay - virtual int getCurrentMenaceLevel() const = 0; + [[nodiscard]] virtual auto getCurrentMenaceLevel() const -> int = 0; }; \ No newline at end of file diff --git a/source/system_utils.cpp b/source/system_utils.cpp index 51d0338..b50e6d9 100644 --- a/source/system_utils.cpp +++ b/source/system_utils.cpp @@ -20,16 +20,16 @@ namespace SystemUtils { // Funci贸n auxiliar para crear una carpeta individual - Result createSingleFolder(const std::string& path, int permissions) { - struct stat st = {0}; - - // Verificar si ya existe - if (stat(path.c_str(), &st) == 0) { - return Result::SUCCESS; // Ya existe, no es error por defecto - } +auto createSingleFolder(const std::string& path, int permissions) -> Result { + struct stat st = {0}; - // Intentar crear la carpeta - int result; + // Verificar si ya existe + if (stat(path.c_str(), &st) == 0) { + return Result::SUCCESS; // Ya existe, no es error por defecto + } + + // Intentar crear la carpeta + int result; #ifdef _WIN32 result = _mkdir(path.c_str()); #else @@ -50,63 +50,63 @@ namespace SystemUtils { } return Result::SUCCESS; - } +} // Funci贸n auxiliar para crear carpetas padre recursivamente - Result createParentFolders(const std::string& path, int permissions) { - size_t pos = 0; - - while ((pos = path.find('/', pos + 1)) != std::string::npos) { - std::string parent = path.substr(0, pos); - if (!parent.empty() && !folderExists(parent)) { - Result result = createSingleFolder(parent, permissions); - if (result != Result::SUCCESS && result != Result::ALREADY_EXISTS) { - return result; - } +auto createParentFolders(const std::string& path, int permissions) -> Result { + size_t pos = 0; + + while ((pos = path.find('/', pos + 1)) != std::string::npos) { + std::string parent = path.substr(0, pos); + if (!parent.empty() && !folderExists(parent)) { + Result result = createSingleFolder(parent, permissions); + if (result != Result::SUCCESS && result != Result::ALREADY_EXISTS) { + return result; } } - - return Result::SUCCESS; } - Result createApplicationFolder(const std::string& app_name, std::string& out_path) { - FolderConfig config; - return createApplicationFolder(app_name, out_path, config); + return Result::SUCCESS; +} + +auto createApplicationFolder(const std::string& app_name, std::string& out_path) -> Result { + FolderConfig config; + return createApplicationFolder(app_name, out_path, config); +} + +auto createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) -> Result { + out_path = getApplicationDataPath(app_name); + return createFolder(out_path, config); +} + +auto createFolder(const std::string& path) -> Result { + FolderConfig config; + return createFolder(path, config); +} + +auto createFolder(const std::string& path, const FolderConfig& config) -> Result { + if (path.empty()) { + return Result::INVALID_PATH; } - Result createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) { - out_path = getApplicationDataPath(app_name); - return createFolder(out_path, config); + // Verificar si ya existe y si eso es un error + if (folderExists(path) && config.fail_if_exists) { + return Result::ALREADY_EXISTS; } - Result createFolder(const std::string& path) { - FolderConfig config; - return createFolder(path, config); - } - - Result createFolder(const std::string& path, const FolderConfig& config) { - if (path.empty()) { - return Result::INVALID_PATH; + // Crear carpetas padre si es necesario + if (config.create_parents) { + Result parent_result = createParentFolders(path, config.permissions); + if (parent_result != Result::SUCCESS) { + return parent_result; } - - // Verificar si ya existe y si eso es un error - if (folderExists(path) && config.fail_if_exists) { - return Result::ALREADY_EXISTS; - } - - // Crear carpetas padre si es necesario - if (config.create_parents) { - Result parent_result = createParentFolders(path, config.permissions); - if (parent_result != Result::SUCCESS) { - return parent_result; - } - } - - // Crear la carpeta final - return createSingleFolder(path, config.permissions); } - std::string getApplicationDataPath(const std::string& app_name) { + // Crear la carpeta final + return createSingleFolder(path, config.permissions); +} + +auto getApplicationDataPath(const std::string& app_name) -> std::string { #ifdef _WIN32 char* appdata = getenv("APPDATA"); if (appdata) { @@ -127,33 +127,33 @@ namespace SystemUtils { std::string home = getHomeDirectory(); return home + "/." + app_name; #endif - } +} - bool folderExists(const std::string& path) { - struct stat st = {0}; - return (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)); - } +auto folderExists(const std::string& path) -> bool { + struct stat st = {0}; + return (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)); +} - const char* resultToString(Result result) { - switch (result) { - case Result::SUCCESS: - return "Operaci贸n exitosa"; - case Result::PERMISSION_DENIED: - return "Error: Permisos insuficientes"; - case Result::PATH_TOO_LONG: - return "Error: Ruta demasiado larga"; - case Result::ALREADY_EXISTS: - return "Error: La carpeta ya existe"; - case Result::INVALID_PATH: - return "Error: Ruta inv谩lida"; - case Result::UNKNOWN_ERROR: - return "Error desconocido"; - default: - return "Error no identificado"; - } +auto resultToString(Result result) -> const char* { + switch (result) { + case Result::SUCCESS: + return "Operaci贸n exitosa"; + case Result::PERMISSION_DENIED: + return "Error: Permisos insuficientes"; + case Result::PATH_TOO_LONG: + return "Error: Ruta demasiado larga"; + case Result::ALREADY_EXISTS: + return "Error: La carpeta ya existe"; + case Result::INVALID_PATH: + return "Error: Ruta inv谩lida"; + case Result::UNKNOWN_ERROR: + return "Error desconocido"; + default: + return "Error no identificado"; } +} - std::string getHomeDirectory() { +auto getHomeDirectory() -> std::string { #ifdef _WIN32 char* userprofile = getenv("USERPROFILE"); if (userprofile) { @@ -162,20 +162,20 @@ namespace SystemUtils { return "C:/Users/Default"; #else struct passwd *pw = getpwuid(getuid()); - if (pw && pw->pw_dir) { + if ((pw != nullptr) && (pw->pw_dir != nullptr)) { return std::string(pw->pw_dir); } - + // Fallback char* home = getenv("HOME"); - if (home) { + if (home != nullptr) { return std::string(home); } return "/tmp"; #endif - } +} - std::string getTempDirectory() { +auto getTempDirectory() -> std::string { #ifdef _WIN32 char* temp = getenv("TEMP"); if (temp) { @@ -185,6 +185,6 @@ namespace SystemUtils { #else return "/tmp"; #endif - } +} } // namespace SystemUtils \ No newline at end of file diff --git a/source/system_utils.h b/source/system_utils.h index 41db9d7..de281d0 100644 --- a/source/system_utils.h +++ b/source/system_utils.h @@ -16,25 +16,25 @@ enum class Result { // C贸digos de resultado para operaciones del sistema // --- Estructuras --- struct FolderConfig { // Configuraci贸n para creaci贸n de carpetas - bool create_parents; // Crear carpetas padre si no existen - bool fail_if_exists; // Fallar si la carpeta ya existe - int permissions; // Permisos Unix (ignorado en Windows) + bool create_parents{true}; // Crear carpetas padre si no existen + bool fail_if_exists{false}; // Fallar si la carpeta ya existe + int permissions{0755}; // Permisos Unix (ignorado en Windows) // Constructor con valores por defecto FolderConfig() - : create_parents(true), fail_if_exists(false), permissions(0755) // rwxr-xr-x + {} }; // --- Funciones --- -Result createApplicationFolder(const std::string& app_name, std::string& out_path); // Crea la carpeta del sistema donde guardar datos de la aplicaci贸n -Result createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config); // Crea la carpeta del sistema con configuraci贸n personalizada -Result createFolder(const std::string& path); // Crea una carpeta en la ruta especificada -Result createFolder(const std::string& path, const FolderConfig& config); // Crea una carpeta con configuraci贸n personalizada -std::string getApplicationDataPath(const std::string& app_name); // Obtiene la ruta de datos de la aplicaci贸n (sin crearla) -bool folderExists(const std::string& path); // Verifica si una carpeta existe -const char* resultToString(Result result); // Convierte un c贸digo de resultado a string descriptivo -std::string getHomeDirectory(); // Obtiene el directorio home del usuario -std::string getTempDirectory(); // Obtiene el directorio temporal del sistema +auto createApplicationFolder(const std::string& app_name, std::string& out_path) -> Result; // Crea la carpeta del sistema donde guardar datos de la aplicaci贸n +auto createApplicationFolder(const std::string& app_name, std::string& out_path, const FolderConfig& config) -> Result; // Crea la carpeta del sistema con configuraci贸n personalizada +auto createFolder(const std::string& path) -> Result; // Crea una carpeta en la ruta especificada +auto createFolder(const std::string& path, const FolderConfig& config) -> Result; // Crea una carpeta con configuraci贸n personalizada +auto getApplicationDataPath(const std::string& app_name) -> std::string; // Obtiene la ruta de datos de la aplicaci贸n (sin crearla) +auto folderExists(const std::string& path) -> bool; // Verifica si una carpeta existe +auto resultToString(Result result) -> const char*; // Convierte un c贸digo de resultado a string descriptivo +auto getHomeDirectory() -> std::string; // Obtiene el directorio home del usuario +auto getTempDirectory() -> std::string; // Obtiene el directorio temporal del sistema } // namespace SystemUtils diff --git a/source/text.cpp b/source/text.cpp index 15fe0bb..3714937 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -14,7 +14,7 @@ #include "utils.h" // Para getFileName, printWithDots // Constructor -Text::Text(std::shared_ptr texture, const std::string &text_file) { +Text::Text(const std::shared_ptr &texture, const std::string &text_file) { // Carga los offsets desde el fichero auto tf = loadFile(text_file); @@ -35,7 +35,7 @@ Text::Text(std::shared_ptr texture, const std::string &text_file) { } // Constructor -Text::Text(std::shared_ptr texture, std::shared_ptr text_file) { +Text::Text(const std::shared_ptr &texture, const std::shared_ptr &text_file) { // Inicializa variables desde la estructura box_height_ = text_file->box_height; box_width_ = text_file->box_width; @@ -261,7 +261,7 @@ auto Text::loadFile(const std::string &file_path) -> std::shared_ptr // El fichero no se puede abrir else { - std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << '\n'; throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } diff --git a/source/text.h b/source/text.h index b3febdd..1cd4438 100644 --- a/source/text.h +++ b/source/text.h @@ -52,8 +52,8 @@ class Text { }; // --- Constructores y destructor --- - Text(std::shared_ptr texture, const std::string &text_file); - Text(std::shared_ptr texture, std::shared_ptr text_file); + Text(const std::shared_ptr &texture, const std::string &text_file); + Text(const std::shared_ptr &texture, const std::shared_ptr &text_file); ~Text() = default; // --- M茅todos de escritura en pantalla --- diff --git a/source/texture.cpp b/source/texture.cpp index 08fc065..78aed7f 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -24,7 +24,7 @@ Texture::Texture(SDL_Renderer *renderer, std::string path) // Carga el fichero en la textura if (!path_.empty()) { // Obtiene la extensi贸n - const std::string EXTENSION = path_.substr(path_.find_last_of(".") + 1); + const std::string EXTENSION = path_.substr(path_.find_last_of('.') + 1); // .png if (EXTENSION == "png") { diff --git a/source/ui/notifier.cpp b/source/ui/notifier.cpp index 536f9cf..9648a05 100644 --- a/source/ui/notifier.cpp +++ b/source/ui/notifier.cpp @@ -18,7 +18,7 @@ Notifier* Notifier::instance = nullptr; // Inicializa la instancia 煤nica del singleton -void Notifier::init(const std::string& icon_file, std::shared_ptr text) { Notifier::instance = new Notifier(icon_file, text); } +void Notifier::init(const std::string& icon_file, std::shared_ptr text) { Notifier::instance = new Notifier(icon_file, std::move(text)); } // Libera la instancia void Notifier::destroy() { delete Notifier::instance; } @@ -27,7 +27,7 @@ void Notifier::destroy() { delete Notifier::instance; } auto Notifier::get() -> Notifier* { return Notifier::instance; } // Constructor -Notifier::Notifier(std::string icon_file, std::shared_ptr text) +Notifier::Notifier(const 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_(std::move(text)), @@ -300,6 +300,7 @@ void Notifier::clearAllNotifications() { // Obtiene los c贸digos de las notificaciones auto Notifier::getCodes() -> std::vector { std::vector codes; + codes.reserve(notifications_.size()); for (const auto& notification : notifications_) { codes.emplace_back(notification.code); } diff --git a/source/ui/notifier.h b/source/ui/notifier.h index 7d18318..b8a5bda 100644 --- a/source/ui/notifier.h +++ b/source/ui/notifier.h @@ -98,7 +98,7 @@ class Notifier { void transitionToStayState(int index); // Cambia el estado de una notificaci贸n de RISING a STAY cuando ha alcanzado su posici贸n final // --- Constructores y destructor privados (singleton) --- - Notifier(std::string icon_file, std::shared_ptr text); // Constructor privado + Notifier(const std::string &icon_file, std::shared_ptr text); // Constructor privado ~Notifier() = default; // Destructor privado // --- Instancia singleton --- diff --git a/source/ui/service_menu.cpp b/source/ui/service_menu.cpp index 153ac02..9415999 100644 --- a/source/ui/service_menu.cpp +++ b/source/ui/service_menu.cpp @@ -1,5 +1,7 @@ #include "ui/service_menu.h" +#include + #include "audio.h" // Para Audio #include "define_buttons.h" // Para DefineButtons #include "difficulty.h" // Para getCodeFromName, getNameFromCode @@ -596,7 +598,7 @@ auto ServiceMenu::checkInput() -> bool { } // Mandos - for (auto gamepad : input_->getGamepads()) { + for (const auto &gamepad : input_->getGamepads()) { for (const auto &[action, func] : ACTIONS) { if (input_->checkAction(action, Input::DO_NOT_ALLOW_REPEAT, Input::DO_NOT_CHECK_KEYBOARD, gamepad)) { func(); @@ -629,7 +631,7 @@ void ServiceMenu::refresh() { // M茅todo para registrar callback void ServiceMenu::setStateChangeCallback(StateChangeCallback callback) { - state_change_callback_ = callback; + state_change_callback_ = std::move(callback); } // M茅todo interno que cambia estado y notifica