diff --git a/source/background.h b/source/background.h index b89d36c..24d1720 100644 --- a/source/background.h +++ b/source/background.h @@ -2,6 +2,7 @@ #include // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer +#include #include // Para size_t #include // Para unique_ptr, shared_ptr #include // Para vector @@ -27,87 +28,87 @@ class Texture; */ class Background { - public: - // Constructor y Destructor - Background(); - ~Background(); + public: + // Constructor y Destructor + Background(); + ~Background(); - // Actualización y renderizado - void update(); // Actualiza la lógica del objeto - void render(); // Dibuja el objeto + // Actualización y renderizado + void update(); // Actualiza la lógica del objeto + void render(); // Dibuja el objeto - // Configuración de posición - void setPos(SDL_FRect pos); // Establece la posición del objeto + // Configuración de posición + void setPos(SDL_FRect pos); // Establece la posición del objeto - // Configuración de animaciones y efectos - void setCloudsSpeed(float value); // Ajusta la velocidad de desplazamiento de las nubes - void setGradientNumber(int value); // Establece el degradado de fondo a usar - void setTransition(float value); // Ajusta la transición entre texturas de fondo + // Configuración de animaciones y efectos + void setCloudsSpeed(float value); // Ajusta la velocidad de desplazamiento de las nubes + void setGradientNumber(int value); // Establece el degradado de fondo a usar + void setTransition(float value); // Ajusta la transición entre texturas de fondo - // Configuración de efectos visuales - void setColor(Color color); // Establece el color de atenuación - void setAlpha(int alpha); // Ajusta la transparencia del fondo + // Configuración de efectos visuales + void setColor(Color color); // Establece el color de atenuación + void setAlpha(int alpha); // Ajusta la transparencia del fondo - // Configuración del sol y la luna - void setSunProgression(float progress); // Establece la posición del sol - void setMoonProgression(float progress); // Establece la posición de la luna + // Configuración del sol y la luna + void setSunProgression(float progress); // Establece la posición del sol + void setMoonProgression(float progress); // Establece la posición de la luna - private: - // Objetos y punteros - SDL_Renderer *renderer_; // Renderizador de la ventana + private: + // Objetos y punteros + SDL_Renderer *renderer_; // Renderizador de la ventana - // Texturas - std::shared_ptr buildings_texture_; - std::shared_ptr top_clouds_texture_; - std::shared_ptr bottom_clouds_texture_; - std::shared_ptr grass_texture_; - std::shared_ptr gradients_texture_; - std::shared_ptr sun_texture_; - std::shared_ptr moon_texture_; + // Texturas + std::shared_ptr buildings_texture_; + std::shared_ptr top_clouds_texture_; + std::shared_ptr bottom_clouds_texture_; + std::shared_ptr grass_texture_; + std::shared_ptr gradients_texture_; + std::shared_ptr sun_texture_; + std::shared_ptr moon_texture_; - // Sprites - std::unique_ptr top_clouds_sprite_a_; - std::unique_ptr top_clouds_sprite_b_; - std::unique_ptr bottom_clouds_sprite_a_; - std::unique_ptr bottom_clouds_sprite_b_; - std::unique_ptr buildings_sprite_; - std::unique_ptr gradient_sprite_; - std::unique_ptr grass_sprite_; - std::unique_ptr sun_sprite_; - std::unique_ptr moon_sprite_; + // Sprites + std::unique_ptr top_clouds_sprite_a_; + std::unique_ptr top_clouds_sprite_b_; + std::unique_ptr bottom_clouds_sprite_a_; + std::unique_ptr bottom_clouds_sprite_b_; + std::unique_ptr buildings_sprite_; + std::unique_ptr gradient_sprite_; + std::unique_ptr grass_sprite_; + std::unique_ptr sun_sprite_; + std::unique_ptr moon_sprite_; - // Buffers de renderizado - SDL_Texture *canvas_; // Textura para componer el fondo - SDL_Texture *color_texture_; // Textura para atenuar el fondo + // Buffers de renderizado + SDL_Texture *canvas_; // Textura para componer el fondo + SDL_Texture *color_texture_; // Textura para atenuar el fondo - // Variables de control - SDL_FRect gradient_rect_[4]; - SDL_FRect top_clouds_rect_[4]; - SDL_FRect bottom_clouds_rect_[4]; - int gradient_number_ = 0; - int alpha_ = 0; - float clouds_speed_ = 0; - float transition_ = 0; - int counter_ = 0; - SDL_FRect rect_; - SDL_FRect src_rect_; - SDL_FRect dst_rect_; - int base_; - Color attenuate_color_; - int alpha_color_text_; - int alpha_color_text_temp_; - std::vector sun_path_; - std::vector moon_path_; - size_t sun_index_ = 0; - size_t moon_index_ = 0; + // Variables de control + std::array gradient_rect_; + std::array top_clouds_rect_; + std::array bottom_clouds_rect_; + int gradient_number_ = 0; + int alpha_ = 0; + float clouds_speed_ = 0; + float transition_ = 0; + int counter_ = 0; + SDL_FRect rect_; + SDL_FRect src_rect_; + SDL_FRect dst_rect_; + int base_; + Color attenuate_color_; + int alpha_color_text_; + int alpha_color_text_temp_; + std::vector sun_path_; + std::vector moon_path_; + size_t sun_index_ = 0; + size_t moon_index_ = 0; - // Métodos internos - void renderGradient(); // Dibuja el gradiente de fondo - void renderTopClouds(); // Dibuja las nubes superiores - void renderBottomClouds(); // Dibuja las nubes inferiores - void fillCanvas(); // Compone todos los elementos en la textura - void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación - void updateClouds(); // Actualiza el movimiento de las nubes - void createSunPath(); // Precalcula el recorrido del sol - void createMoonPath(); // Precalcula el recorrido de la luna + // Métodos internos + void renderGradient(); // Dibuja el gradiente de fondo + void renderTopClouds(); // Dibuja las nubes superiores + void renderBottomClouds(); // Dibuja las nubes inferiores + void fillCanvas(); // Compone todos los elementos en la textura + void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación + void updateClouds(); // Actualiza el movimiento de las nubes + void createSunPath(); // Precalcula el recorrido del sol + void createMoonPath(); // Precalcula el recorrido de la luna }; diff --git a/source/balloon.cpp b/source/balloon.cpp index 013be01..eaf9f3b 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -319,8 +319,8 @@ void Balloon::shiftSprite() { // Establece el nivel de zoom del sprite void Balloon::zoomSprite() { - sprite_->setZoomW(bouncing_.zoom_w); - sprite_->setZoomH(bouncing_.zoom_h); + sprite_->setZoomW(bouncing_.horizontal_zoom); + sprite_->setZoomH(bouncing_.verical_zoom); } // Activa el efecto @@ -341,8 +341,8 @@ void Balloon::disableBounce() { void Balloon::updateBounce() { if (bouncing_.enabled) { const int INDEX = bouncing_.counter / bouncing_.speed; - bouncing_.zoom_w = bouncing_.w[INDEX]; - bouncing_.zoom_h = bouncing_.h[INDEX]; + bouncing_.horizontal_zoom = bouncing_.horizontal_zoom_values[INDEX]; + bouncing_.verical_zoom = bouncing_.vertical_zoom_values[INDEX]; zoomSprite(); diff --git a/source/balloon.h b/source/balloon.h index 3294579..0798991 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -2,6 +2,7 @@ #include // Para Uint8, Uint16, SDL_FRect, Uint32 +#include #include // Para shared_ptr, unique_ptr #include // Para basic_string, string #include // Para vector @@ -14,12 +15,16 @@ class Texture; // --- Constantes relacionadas con globos --- constexpr int MAX_BOUNCE = 10; // Cantidad de elementos del vector de deformación -constexpr int BALLOON_SCORE[] = {50, 100, 200, 400}; -constexpr int BALLOON_POWER[] = {1, 3, 7, 15}; -constexpr int BALLOON_MENACE[] = {1, 2, 4, 8}; -constexpr int BALLOON_SIZE[] = {10, 16, 26, 48, 49}; -const std::string BALLOON_BOUNCING_SOUND[] = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"}; -const std::string BALLOON_POPPING_SOUND[] = {"balloon1.wav", "balloon2.wav", "balloon3.wav", "balloon4.wav"}; +constexpr std::array BALLOON_SCORE = {50, 100, 200, 400}; +constexpr std::array BALLOON_POWER = {1, 3, 7, 15}; +constexpr std::array BALLOON_MENACE = {1, 2, 4, 8}; +constexpr std::array BALLOON_SIZE = {10, 16, 26, 48, 49}; + +const std::array BALLOON_BOUNCING_SOUND = { + "bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"}; + +const std::array BALLOON_POPPING_SOUND = { + "balloon1.wav", "balloon2.wav", "balloon3.wav", "balloon4.wav"}; enum class BalloonSize : Uint8 { SIZE1 = 0, @@ -41,136 +46,136 @@ constexpr int BALLOON_MOVING_ANIMATION = 0; constexpr int BALLOON_POP_ANIMATION = 1; constexpr int BALLOON_BORN_ANIMATION = 2; -constexpr float BALLOON_SPEED[] = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f}; +constexpr std::array BALLOON_SPEED = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f}; constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10; constexpr int POWERBALL_COUNTER = 8; // --- Clase Balloon --- class Balloon { - public: - // --- Constructores y destructor --- - Balloon( - float x, - float y, - BalloonType type, - BalloonSize size, - float vel_x, - float speed, - Uint16 creation_timer, - SDL_FRect play_area, - std::shared_ptr texture, - const std::vector &animation); - ~Balloon() = default; + public: + // --- Constructores y destructor --- + Balloon( + float x, + float y, + BalloonType type, + BalloonSize size, + float vel_x, + float speed, + Uint16 creation_timer, + SDL_FRect play_area, + std::shared_ptr texture, + const std::vector &animation); + ~Balloon() = default; - // --- Métodos principales --- - void alignTo(int x); // Centra el globo en la posición X - void render(); // Pinta el globo en la pantalla - void move(); // Actualiza la posición y estados del globo - void update(); // Actualiza el globo (posición, animación, contadores) - void stop(); // Detiene el globo - void start(); // Pone el globo en movimiento - void pop(bool should_sound = false); // Explota el globo + // --- Métodos principales --- + void alignTo(int x); // Centra el globo en la posición X + void render(); // Pinta el globo en la pantalla + void move(); // Actualiza la posición y estados del globo + void update(); // Actualiza el globo (posición, animación, contadores) + void stop(); // Detiene el globo + void start(); // Pone el globo en movimiento + void pop(bool should_sound = false); // Explota el globo - // --- Métodos de color --- - void useReverseColor(); // Pone el color alternativo en el globo - void useNormalColor(); // Pone el color normal en el globo + // --- Métodos de color --- + void useReverseColor(); // Pone el color alternativo en el globo + void useNormalColor(); // Pone el color normal en el globo - // --- Getters --- - [[nodiscard]] auto getPosX() const -> float { return x_; } - [[nodiscard]] auto getPosY() const -> float { return y_; } - [[nodiscard]] auto getWidth() const -> int { return w_; } - [[nodiscard]] auto getHeight() const -> int { return h_; } - [[nodiscard]] auto getSize() const -> BalloonSize { return size_; } - [[nodiscard]] auto getType() const -> BalloonType { return type_; } - [[nodiscard]] auto getScore() const -> Uint16 { return score_; } - auto getCollider() -> Circle & { return collider_; } - [[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; } - [[nodiscard]] auto getPower() const -> Uint8 { return power_; } - [[nodiscard]] auto isStopped() const -> bool { return stopped_; } - [[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; } - [[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; } - [[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; } - [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - auto isUsingReversedColor() -> bool { return use_reversed_colors_; } - [[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); } + // --- Getters --- + [[nodiscard]] auto getPosX() const -> float { return x_; } + [[nodiscard]] auto getPosY() const -> float { return y_; } + [[nodiscard]] auto getWidth() const -> int { return w_; } + [[nodiscard]] auto getHeight() const -> int { return h_; } + [[nodiscard]] auto getSize() const -> BalloonSize { return size_; } + [[nodiscard]] auto getType() const -> BalloonType { return type_; } + [[nodiscard]] auto getScore() const -> Uint16 { return score_; } + auto getCollider() -> Circle & { return collider_; } + [[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; } + [[nodiscard]] auto getPower() const -> Uint8 { return power_; } + [[nodiscard]] auto isStopped() const -> bool { return stopped_; } + [[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; } + [[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; } + [[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; } + [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } + auto isUsingReversedColor() -> bool { return use_reversed_colors_; } + [[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); } - // --- Setters --- - void setVelY(float vel_y) { vy_ = vel_y; } - void setSpeed(float speed) { speed_ = speed; } - void setInvulnerable(bool value) { invulnerable_ = value; } - void setBouncingSound(bool value) { bouncing_sound_enabled_ = value; } - void setPoppingSound(bool value) { poping_sound_enabled_ = value; } - void setSound(bool value) { sound_enabled_ = value; } + // --- Setters --- + void setVelY(float vel_y) { vy_ = vel_y; } + void setSpeed(float speed) { speed_ = speed; } + void setInvulnerable(bool value) { invulnerable_ = value; } + void setBouncingSound(bool value) { bouncing_sound_enabled_ = value; } + void setPoppingSound(bool value) { poping_sound_enabled_ = value; } + void setSound(bool value) { sound_enabled_ = value; } - private: - // --- Estructura para el efecto de rebote --- - struct Bouncing { - bool enabled = false; // Si el efecto está activo - Uint8 counter = 0; // Contador para el efecto - Uint8 speed = 2; // Velocidad del efecto - float zoom_w = 1.0f; // Zoom en anchura - float zoom_h = 1.0f; // Zoom en altura - float desp_x = 0.0f; // Desplazamiento X antes de pintar - float desp_y = 0.0f; // Desplazamiento Y antes de pintar + private: + // --- Estructura para el efecto de rebote --- + struct Bouncing { + bool enabled = false; // Si el efecto está activo + Uint8 counter = 0; // Contador para el efecto + Uint8 speed = 2; // Velocidad del efecto + float horizontal_zoom = 1.0f; // Zoom en anchura + float verical_zoom = 1.0f; // Zoom en altura + float desp_x = 0.0f; // Desplazamiento X antes de pintar + float desp_y = 0.0f; // Desplazamiento Y antes de pintar - float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho - float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto + std::array horizontal_zoom_values = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho + std::array vertical_zoom_values = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto - Bouncing() = default; - void reset() { - counter = 0; - zoom_w = 1.0f; - zoom_h = 1.0f; - desp_x = 0.0f; - desp_y = 0.0f; - } - } bouncing_; + Bouncing() = default; + void reset() { + counter = 0; + horizontal_zoom = 1.0f; + verical_zoom = 1.0f; + desp_x = 0.0f; + desp_y = 0.0f; + } + } bouncing_; - // --- Objetos y punteros --- - std::unique_ptr sprite_; // Sprite del objeto globo + // --- Objetos y punteros --- + std::unique_ptr sprite_; // Sprite del objeto globo - // --- Variables de estado y físicas --- - float x_; // Posición X - float y_; // Posición Y - float w_; // Ancho - float h_; // Alto - float vx_; // Velocidad X - float vy_; // Velocidad Y - float gravity_; // Aceleración en Y - float default_vy_; // Velocidad inicial al rebotar - float max_vy_; // Máxima velocidad en Y - bool being_created_; // Si el globo se está creando - bool enabled_ = true; // Si el globo está activo - bool invulnerable_; // Si el globo es invulnerable - bool stopped_; // Si el globo está parado - bool use_reversed_colors_ = false; // Si se usa el color alternativo - Circle collider_; // Círculo de colisión - Uint16 creation_counter_; // Temporizador de creación - Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación - Uint16 score_; // Puntos al destruir el globo - BalloonType type_; // Tipo de globo - BalloonSize size_; // Tamaño de globo - Uint8 menace_; // Amenaza que genera el globo - Uint32 counter_ = 0; // Contador interno - float travel_y_ = 1.0f; // Distancia a recorrer en Y antes de aplicar gravedad - float speed_; // Velocidad del globo - Uint8 power_; // Poder que alberga el globo - SDL_FRect play_area_; // Zona de movimiento del globo - std::string bouncing_sound_; // Archivo de sonido al rebotar - std::string popping_sound_; // Archivo de sonido al explotar - bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar - bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar - bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido + // --- Variables de estado y físicas --- + float x_; // Posición X + float y_; // Posición Y + float w_; // Ancho + float h_; // Alto + float vx_; // Velocidad X + float vy_; // Velocidad Y + float gravity_; // Aceleración en Y + float default_vy_; // Velocidad inicial al rebotar + float max_vy_; // Máxima velocidad en Y + bool being_created_; // Si el globo se está creando + bool enabled_ = true; // Si el globo está activo + bool invulnerable_; // Si el globo es invulnerable + bool stopped_; // Si el globo está parado + bool use_reversed_colors_ = false; // Si se usa el color alternativo + Circle collider_; // Círculo de colisión + Uint16 creation_counter_; // Temporizador de creación + Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación + Uint16 score_; // Puntos al destruir el globo + BalloonType type_; // Tipo de globo + BalloonSize size_; // Tamaño de globo + Uint8 menace_; // Amenaza que genera el globo + Uint32 counter_ = 0; // Contador interno + float travel_y_ = 1.0f; // Distancia a recorrer en Y antes de aplicar gravedad + float speed_; // Velocidad del globo + Uint8 power_; // Poder que alberga el globo + SDL_FRect play_area_; // Zona de movimiento del globo + std::string bouncing_sound_; // Archivo de sonido al rebotar + std::string popping_sound_; // Archivo de sonido al explotar + bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar + bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar + bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido - // --- Métodos internos --- - void shiftColliders(); // Alinea el círculo de colisión - void shiftSprite(); // Alinea el sprite - void zoomSprite(); // Establece el nivel de zoom del sprite - void enableBounce(); // Activa el efecto de rebote - void disableBounce(); // Detiene el efecto de rebote - void updateBounce(); // Aplica el efecto de rebote - void updateState(); // Actualiza los estados del globo - void setAnimation(); // Establece la animación correspondiente - void playSound(const std::string &name); // Reproduce sonido + // --- Métodos internos --- + void shiftColliders(); // Alinea el círculo de colisión + void shiftSprite(); // Alinea el sprite + void zoomSprite(); // Establece el nivel de zoom del sprite + void enableBounce(); // Activa el efecto de rebote + void disableBounce(); // Detiene el efecto de rebote + void updateBounce(); // Aplica el efecto de rebote + void updateState(); // Actualiza los estados del globo + void setAnimation(); // Establece la animación correspondiente + void playSound(const std::string &name); // Reproduce sonido }; \ No newline at end of file diff --git a/source/balloon_manager.cpp b/source/balloon_manager.cpp index 6211437..11c3a0c 100644 --- a/source/balloon_manager.cpp +++ b/source/balloon_manager.cpp @@ -1,8 +1,9 @@ #include "balloon_manager.h" #include // Para remove_if -#include // Para rand -#include // Para accumulate +#include +#include // Para rand +#include // Para accumulate #include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX... #include "balloon_formations.h" // Para BalloonFormationParams, BalloonForma... @@ -209,8 +210,8 @@ void BalloonManager::createPowerBall() { const float RIGHT = param.game.play_area.rect.w - BALLOON_SIZE[4]; const int LUCK = rand() % VALUES; - const float POS_X[VALUES] = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT}; - const float VEL_X[VALUES] = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE}; + const std::array POS_X = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT}; + const std::array VEL_X = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE}; balloons_.emplace_back(std::make_unique(POS_X[LUCK], POS_Y, BalloonType::POWERBALL, BalloonSize::SIZE4, VEL_X[LUCK], balloon_speed_, CREATION_TIME, play_area_, balloon_textures_[4], balloon_animations_[4])); balloons_.back()->setInvulnerable(true); diff --git a/source/director.cpp b/source/director.cpp index e5a9cb8..ee32f27 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -11,6 +11,7 @@ #include // Para exit, EXIT_FAILURE, size_t, srand #include // Para time #include // Para make_unique, unique_ptr +#include #include // Para runtime_error #include // Para operator+, basic_string, allocator #include // Para vector @@ -41,7 +42,7 @@ #endif // Constructor -Director::Director(int argc, const char *argv[]) { +Director::Director(int argc, std::span argv) { #ifdef RECORDING Section::name = Section::Name::GAME; Section::options = Section::Options::GAME_PLAY_1P; @@ -434,7 +435,7 @@ void Director::setFileList() { } // Comprueba los parametros del programa -void Director::checkProgramArguments(int argc, const char *argv[]) { +void Director::checkProgramArguments(int argc, std::span argv) { // Establece la ruta del programa executable_path_ = getPath(argv[0]); diff --git a/source/director.h b/source/director.h index 52e0821..b27014d 100644 --- a/source/director.h +++ b/source/director.h @@ -1,6 +1,7 @@ #pragma once #include // Para manejar cadenas de texto +#include namespace Lang { enum class Code : int; @@ -9,7 +10,7 @@ enum class Code : int; class Director { public: // --- Constructor y destructor --- - Director(int argc, const char *argv[]); + Director(int argc, std::span argv); ~Director(); // --- Bucle principal --- @@ -32,7 +33,7 @@ private: // --- Gestión de entrada y archivos --- void bindInputs(); // Asigna botones y teclas al sistema de entrada void setFileList(); // Crea el índice de archivos disponibles - void checkProgramArguments(int argc, const char *argv[]); // Verifica los parámetros del programa + void checkProgramArguments(int argc, std::span argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays) // --- Secciones del programa --- void runLogo(); // Ejecuta la pantalla con el logo diff --git a/source/external/.clang-tidy b/source/external/.clang-tidy index 612bd0e..bbae176 100644 --- a/source/external/.clang-tidy +++ b/source/external/.clang-tidy @@ -1 +1,4 @@ +# source/external/.clang-tidy Checks: '-*' +WarningsAsErrors: '' +HeaderFilterRegex: '' \ No newline at end of file diff --git a/source/main.cpp b/source/main.cpp index a64d0b0..10a4284 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -11,9 +11,9 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024 #include "director.h" // Para Director -auto main(int argc, char *argv[]) -> int { +auto main(int argc, char* argv[]) -> int { // Crea el objeto Director - auto director = std::make_unique(argc, const_cast(argv)); + auto director = std::make_unique(argc, std::span(argv, argc)); // Bucle principal return director->run(); diff --git a/source/options.h b/source/options.h index c207686..dd6eb51 100644 --- a/source/options.h +++ b/source/options.h @@ -22,22 +22,22 @@ enum class DifficultyCode { // --- Estructura que representa un nivel de dificultad struct Difficulty { - DifficultyCode code; // Código que identifica la dificultad - std::string name; // Nombre que identifica la dificultad + DifficultyCode code; // Código que identifica la dificultad + std::string name; // Nombre que identifica la dificultad - Difficulty(DifficultyCode c, std::string n) - : code(c), name(std::move(n)) {} + Difficulty(DifficultyCode c, std::string n) + : code(c), name(std::move(n)) {} }; // --- Opciones de ventana --- struct WindowOptions { - std::string caption; // Texto que aparece en la barra de título de la ventana - int size{2}; // Valor por el que se multiplica el tamaño de la ventana - int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla + std::string caption; // Texto que aparece en la barra de título de la ventana + int size{2}; // Valor por el que se multiplica el tamaño de la ventana + int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla - // Constructor por defecto con valores iniciales - WindowOptions() - : caption("Coffee Crisis Arcade Edition") {} + // Constructor por defecto con valores iniciales + WindowOptions() + : caption("Coffee Crisis Arcade Edition") {} }; // --- Opciones de vídeo --- @@ -60,9 +60,7 @@ struct MusicOptions { int volume{100}; // Volumen de la música // Constructor por defecto - MusicOptions() - - {} + MusicOptions() = default; }; // --- Opciones de sonido --- @@ -71,22 +69,20 @@ struct SoundOptions { int volume{100}; // Volumen de los sonidos // Constructor por defecto - SoundOptions() - - {} + SoundOptions() = default; }; // --- Opciones de audio --- struct AudioOptions { - MusicOptions music; // Opciones para la música - SoundOptions sound; // Opciones para los efectos de sonido - bool enabled{true}; // Indica si el audio está activo o no - int volume{100}; // Volumen general del audio + MusicOptions music; // Opciones para la música + SoundOptions sound; // Opciones para los efectos de sonido + bool enabled{true}; // Indica si el audio está activo o no + int volume{100}; // Volumen general del audio - // Constructor por defecto - AudioOptions() - : music(), - sound() {} + // Constructor por defecto + AudioOptions() + : music(), + sound() {} }; // --- Opciones de configuración --- @@ -108,38 +104,36 @@ struct SettingsOptions { void clearLastHiScoreEntries() { last_hi_score_entry[0] = INVALID_INDEX; last_hi_score_entry[1] = INVALID_INDEX; - } + } }; // --- Opciones de mando --- struct GamepadOptions { - int index; // Índice en el vector de mandos - int player_id; // Jugador asociado al mando - InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos - std::string name; // Nombre del dispositivo - bool plugged{false}; // Indica si el mando está conectado - std::vector inputs; // Listado de acciones asignadas - std::vector buttons; // Listado de botones asignados a cada acción + int index; // Índice en el vector de mandos + int player_id; // Jugador asociado al mando + InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos + std::string name; // Nombre del dispositivo + bool plugged{false}; // Indica si el mando está conectado + std::vector inputs; // Listado de acciones asignadas + std::vector buttons; // Listado de botones asignados a cada acción - // Constructor por defecto - GamepadOptions() - : index(INVALID_INDEX), - player_id(INVALID_INDEX), - - name(), - - inputs{ - InputAction::FIRE_LEFT, - InputAction::FIRE_CENTER, - InputAction::FIRE_RIGHT, - InputAction::START, - InputAction::SERVICE}, - buttons{ - SDL_GAMEPAD_BUTTON_WEST, - SDL_GAMEPAD_BUTTON_NORTH, - SDL_GAMEPAD_BUTTON_EAST, - SDL_GAMEPAD_BUTTON_START, - SDL_GAMEPAD_BUTTON_BACK} {} + // Constructor por defecto + GamepadOptions() + : index(INVALID_INDEX), + player_id(INVALID_INDEX), + name(), + inputs{ + InputAction::FIRE_LEFT, + InputAction::FIRE_CENTER, + InputAction::FIRE_RIGHT, + InputAction::START, + InputAction::SERVICE}, + buttons{ + SDL_GAMEPAD_BUTTON_WEST, + SDL_GAMEPAD_BUTTON_NORTH, + SDL_GAMEPAD_BUTTON_EAST, + SDL_GAMEPAD_BUTTON_START, + SDL_GAMEPAD_BUTTON_BACK} {} }; // --- Opciones pendientes de aplicar --- @@ -149,9 +143,7 @@ struct PendingChanges { bool has_pending_changes{false}; // Indica si hay cambios pendientes // Constructor por defecto con valores iniciales - PendingChanges() - - {} + PendingChanges() = default; }; // --- Variables globales --- @@ -164,15 +156,15 @@ extern PendingChanges pending_changes; // Opciones que se aplican al c extern std::vector difficulties; // Lista de los diferentes tipos de dificultad // --- Funciones de configuración --- -void init(); // Inicializa las opciones del programa -auto loadFromFile() -> bool; // Carga el fichero de configuración -auto saveToFile() -> bool; // Guarda el fichero de configuración -void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador -void swapKeyboard(); // Intercambia el teclado de jugador -void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos -auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado -void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables -void checkPendingChanges(); // Verifica si hay cambios pendientes +void init(); // Inicializa las opciones del programa +auto loadFromFile() -> bool; // Carga el fichero de configuración +auto saveToFile() -> bool; // Guarda el fichero de configuración +void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador +void swapKeyboard(); // Intercambia el teclado de jugador +void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos +auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado +void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables +void checkPendingChanges(); // Verifica si hay cambios pendientes auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode; // Obtiene el código de dificultad a partir del nombre auto getDifficultyNameFromCode(DifficultyCode code) -> std::string; // Obtiene el nombre de la dificultad a partir del código } // namespace Options \ No newline at end of file diff --git a/source/scoreboard.h b/source/scoreboard.h index dce60b2..7308d01 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -2,6 +2,7 @@ #include // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64 +#include #include // Para size_t #include // Para shared_ptr, unique_ptr #include // Para basic_string, string @@ -35,87 +36,88 @@ enum class ScoreboardMode : int { // --- Structs --- struct Panel { - ScoreboardMode mode; // Modo en el que se encuentra el panel - SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador + ScoreboardMode mode; // Modo en el que se encuentra el panel + SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador }; // --- Clase Scoreboard --- class Scoreboard { - public: - // --- Métodos de singleton --- - static void init(); // Crea el objeto Scoreboard - static void destroy(); // Libera el objeto Scoreboard - static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard + public: + // --- Métodos de singleton --- + static void init(); // Crea el objeto Scoreboard + static void destroy(); // Libera el objeto Scoreboard + static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard - // --- Métodos principales --- - void update(); // Actualiza la lógica del marcador - void render(); // Pinta el marcador + // --- Métodos principales --- + void update(); // Actualiza la lógica del marcador + void render(); // Pinta el marcador - // --- Setters --- - void setColor(Color color); // Establece el color del marcador - void setPos(SDL_FRect rect); // Establece la posición y tamaño del marcador - void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; } - void setHiScore(int hi_score) { hi_score_ = hi_score; } - void setHiScoreName(const std::string &name) { hi_score_name_ = name; } - void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; } - void setMult(int panel, float mult) { mult_[panel] = mult; } - void setName(int panel, const std::string &name) { name_[panel] = name; } - void setPower(float power) { power_ = power; } - void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; } - void setScore(int panel, int score) { score_[panel] = score; } - void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; } - void setStage(int stage) { stage_ = stage; } + // --- Setters --- + void setColor(Color color); // Establece el color del marcador + void setPos(SDL_FRect rect); // Establece la posición y tamaño del marcador + void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; } + void setHiScore(int hi_score) { hi_score_ = hi_score; } + void setHiScoreName(const std::string &name) { hi_score_name_ = name; } + void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; } + void setMult(int panel, float mult) { mult_[panel] = mult; } + void setName(int panel, const std::string &name) { name_[panel] = name; } + void setPower(float power) { power_ = power; } + void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; } + void setScore(int panel, int score) { score_[panel] = score; } + void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; } + void setStage(int stage) { stage_ = stage; } - private: - // --- Objetos y punteros --- - SDL_Renderer *renderer_; // El renderizador de la ventana - std::shared_ptr game_power_meter_texture_; // Textura con el marcador de poder de la fase - std::unique_ptr power_meter_sprite_; // Sprite para el medidor de poder de la fase - std::shared_ptr text_scoreboard_; // Fuente para el marcador del juego - SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador - std::vector panel_texture_; // Texturas para dibujar cada panel + private: + // --- Objetos y punteros --- + SDL_Renderer *renderer_; // El renderizador de la ventana + std::shared_ptr game_power_meter_texture_; // Textura con el marcador de poder de la fase + std::unique_ptr power_meter_sprite_; // Sprite para el medidor de poder de la fase + std::shared_ptr text_scoreboard_; // Fuente para el marcador del juego + SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador + std::vector panel_texture_; // Texturas para dibujar cada panel - // --- Variables de estado --- - std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador - std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records - size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre - int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores - float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores - int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores - Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador - int stage_ = 1; // Número de fase actual - int hi_score_ = 0; // Máxima puntuación - float power_ = 0; // Poder actual de la fase - std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación - Color color_ = Color(); // Color del marcador - SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador - Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks() - int time_counter_ = 0; // Contador de segundos - int loop_counter_ = 0; // Contador de bucle - std::vector name_colors_; // Colores para destacar el nombre una vez introducido + // --- Variables de estado --- + std::array name_ = {}; // Nombre de cada jugador + std::array record_name_ = {}; // Nombre introducido para la tabla de records + std::array selector_pos_ = {}; // Posición del selector de letra para introducir el nombre + std::array score_ = {}; // Puntuación de los jugadores + std::array mult_ = {}; // Multiplicador de los jugadores + std::array continue_counter_ = {}; // Tiempo para continuar de los jugadores + std::array panel_ = {}; // Lista con todos los paneles del marcador - // --- Variables de aspecto --- - Color text_color1_, text_color2_; // Colores para los marcadores del texto; + int stage_ = 1; // Número de fase actual + int hi_score_ = 0; // Máxima puntuación + float power_ = 0; // Poder actual de la fase + std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación + Color color_ = Color(); // Color del marcador + SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador + Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks() + int time_counter_ = 0; // Contador de segundos + int loop_counter_ = 0; // Contador de bucle + std::vector name_colors_; // Colores para destacar el nombre una vez introducido - // --- Puntos predefinidos para colocar elementos en los paneles --- - SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_; - SDL_FPoint enter_name_pos_; + // --- Variables de aspecto --- + Color text_color1_, text_color2_; // Colores para los marcadores del texto; - // --- Métodos internos --- - void recalculateAnchors(); // Recalcula las anclas de los elementos - auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras - void createBackgroundTexture(); // Crea la textura de fondo - void createPanelTextures(); // Crea las texturas de los paneles - void fillPanelTextures(); // Rellena los diferentes paneles del marcador - void fillBackgroundTexture(); // Rellena la textura de fondo - void updateTimeCounter(); // Actualiza el contador - void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador - void iniNameColors(); // Inicializa el vector de colores para el nombre + // --- Puntos predefinidos para colocar elementos en los paneles --- + SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_; + SDL_FPoint enter_name_pos_; - // --- Constructor y destructor privados (singleton) --- - Scoreboard(); - ~Scoreboard(); + // --- Métodos internos --- + void recalculateAnchors(); // Recalcula las anclas de los elementos + auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras + void createBackgroundTexture(); // Crea la textura de fondo + void createPanelTextures(); // Crea las texturas de los paneles + void fillPanelTextures(); // Rellena los diferentes paneles del marcador + void fillBackgroundTexture(); // Rellena la textura de fondo + void updateTimeCounter(); // Actualiza el contador + void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador + void iniNameColors(); // Inicializa el vector de colores para el nombre - // --- Singleton --- - static Scoreboard *instance; + // --- Constructor y destructor privados (singleton) --- + Scoreboard(); + ~Scoreboard(); + + // --- Singleton --- + static Scoreboard *instance; }; diff --git a/source/screen.h b/source/screen.h index ef2e6a5..173a286 100644 --- a/source/screen.h +++ b/source/screen.h @@ -70,7 +70,7 @@ class Screen { int frame_count{0}; // Número acumulado de frames en el intervalo. int last_value{0}; // Número de frames calculado en el último segundo. - FPS() {} + FPS() = default; void increment() { frame_count++; } auto calculate(Uint32 current_ticks) -> int { if (current_ticks - ticks >= 1000) { diff --git a/source/sections/credits.cpp b/source/sections/credits.cpp index b68edf2..e3f0704 100644 --- a/source/sections/credits.cpp +++ b/source/sections/credits.cpp @@ -8,6 +8,7 @@ #include // Para abs #include // Para runtime_error #include // Para basic_string, string +#include #include // Para vector #include "audio.h" // Para Audio @@ -30,7 +31,8 @@ #include "utils.h" // Para Color, Zone, SHADOW_TEXT_COLOR, NO_TEXT... // Textos -constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner"; +constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner"; + // Constructor Credits::Credits() @@ -218,7 +220,7 @@ void Credits::fillTextTexture() { // Texto con el copyright y += mini_logo_sprite->getHeight() + 3; - text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR); + 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); // Resetea el renderizador SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr); diff --git a/source/sections/game.cpp b/source/sections/game.cpp index 9cae56f..fcc1c66 100644 --- a/source/sections/game.cpp +++ b/source/sections/game.cpp @@ -2,6 +2,7 @@ #include // Para SDL_GetTicks, SDL_SetRenderTarget +#include #include // Para find_if, clamp, find, min #include // Para rand, size_t #include // Para function @@ -1404,7 +1405,7 @@ void Game::initDemo(int player_id) { { constexpr auto NUM_DEMOS = 3; const auto DEMO = rand() % NUM_DEMOS; - const int STAGES[NUM_DEMOS] = {0, 3, 5}; + constexpr std::array STAGES = {0, 3, 5}; Stage::number = STAGES[DEMO]; } @@ -1695,7 +1696,7 @@ void Game::checkAndUpdateBalloonSpeed() { return; const float PERCENT = static_cast(Stage::power) / Stage::get(Stage::number).power_to_complete; - const float THRESHOLDS[] = {0.2f, 0.4f, 0.6f, 0.8f}; + constexpr std::array THRESHOLDS = {0.2f, 0.4f, 0.6f, 0.8f}; for (size_t i = 0; i < std::size(THRESHOLDS); ++i) { if (balloon_manager_->getBalloonSpeed() == BALLOON_SPEED[i] && PERCENT > THRESHOLDS[i]) { diff --git a/source/sections/title.cpp b/source/sections/title.cpp index c99f346..07c7c0d 100644 --- a/source/sections/title.cpp +++ b/source/sections/title.cpp @@ -433,7 +433,7 @@ void Title::renderCopyright() { text_->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, anchor_.copyright_text, - TEXT_COPYRIGHT, + std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, diff --git a/source/sections/title.h b/source/sections/title.h index 6fabeed..8d65c14 100644 --- a/source/sections/title.h +++ b/source/sections/title.h @@ -4,6 +4,7 @@ #include // Para unique_ptr, shared_ptr #include +#include #include "section.h" // Para Options @@ -16,7 +17,8 @@ class Text; class TiledBG; // Textos -constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner"; +constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner"; + // Parámetros constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false; diff --git a/source/tabe.cpp b/source/tabe.cpp index 72b86ef..3cf69fb 100644 --- a/source/tabe.cpp +++ b/source/tabe.cpp @@ -4,6 +4,7 @@ #include // Para SDL_FlipMode, SDL_GetTicks #include // Para max +#include #include // Para abs #include // Para rand, abs #include // Para basic_string @@ -25,7 +26,7 @@ void Tabe::update() { move(); updateState(); } - + timer_.update(); if (timer_.shouldSpawn()) { enable(); @@ -41,49 +42,62 @@ void Tabe::render() { // Mueve el objeto void Tabe::move() { - const int X = static_cast(x_); - speed_ += accel_; - x_ += speed_; - fly_distance_ -= std::abs(X - static_cast(x_)); + const int X = static_cast(x_); + speed_ += accel_; + x_ += speed_; + fly_distance_ -= std::abs(X - static_cast(x_)); - // Comprueba si sale por los bordes - const float MIN_X = param.game.game_area.rect.x - WIDTH; - const float MAX_X = param.game.game_area.rect.x + param.game.game_area.rect.w; - switch (destiny_) { - case TabeDirection::TO_THE_LEFT: { - if (x_ < MIN_X) { - disable(); - } - if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH && direction_ == TabeDirection::TO_THE_RIGHT) { - setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80); - x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH; - } - break; - } + // Comprueba si sale por los bordes + const float MIN_X = param.game.game_area.rect.x - WIDTH; + const float MAX_X = param.game.game_area.rect.x + param.game.game_area.rect.w; + switch (destiny_) { + case TabeDirection::TO_THE_LEFT: { + if (x_ < MIN_X) { + disable(); + } + if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH && direction_ == TabeDirection::TO_THE_RIGHT) { + setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80); + x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH; + } + break; + } - case TabeDirection::TO_THE_RIGHT: { - if (x_ > MAX_X) { - disable(); - } - if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) { - setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80); - x_ = param.game.game_area.rect.x; - } - break; - } - default: - break; + case TabeDirection::TO_THE_RIGHT: { + if (x_ > MAX_X) { + disable(); + } + if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) { + setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80); + x_ = param.game.game_area.rect.x; + } + break; + } + default: + break; } if (fly_distance_ <= 0) { if (waiting_counter_ > 0) { - accel_ = speed_ = 0.0F; - --waiting_counter_; + accel_ = speed_ = 0.0F; + --waiting_counter_; } else { constexpr int CHOICES = 4; - const TabeDirection LEFT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT}; - const TabeDirection RIGHT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT}; - const TabeDirection DIRECTION = destiny_ == TabeDirection::TO_THE_LEFT ? LEFT[rand() % CHOICES] : RIGHT[rand() % CHOICES]; + const std::array LEFT = { + TabeDirection::TO_THE_LEFT, + TabeDirection::TO_THE_LEFT, + TabeDirection::TO_THE_LEFT, + TabeDirection::TO_THE_RIGHT}; + + const std::array RIGHT = { + TabeDirection::TO_THE_LEFT, + TabeDirection::TO_THE_RIGHT, + TabeDirection::TO_THE_RIGHT, + TabeDirection::TO_THE_RIGHT}; + + const TabeDirection DIRECTION = destiny_ == TabeDirection::TO_THE_LEFT + ? LEFT[rand() % CHOICES] + : RIGHT[rand() % CHOICES]; + setRandomFlyPath(DIRECTION, 20 + rand() % 40); } } @@ -123,10 +137,10 @@ void Tabe::setRandomFlyPath(TabeDirection direction, int lenght) { switch (direction) { case TabeDirection::TO_THE_LEFT: { - speed_ = -1.0F * SPEED; - accel_ = -1.0F * (1 + rand() % 10) / 30.0F; - sprite_->setFlip(SDL_FLIP_NONE); - break; + speed_ = -1.0F * SPEED; + accel_ = -1.0F * (1 + rand() % 10) / 30.0F; + sprite_->setFlip(SDL_FLIP_NONE); + break; } case TabeDirection::TO_THE_RIGHT: { @@ -175,11 +189,11 @@ void Tabe::updateState() { // Intenta obtener el bonus auto Tabe::tryToGetBonus() -> bool { - if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) { - has_bonus_ = false; - return true; - } - return false; + if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) { + has_bonus_ = false; + return true; + } + return false; } // Actualiza el temporizador diff --git a/source/text.h b/source/text.h index 086bb81..16901a0 100644 --- a/source/text.h +++ b/source/text.h @@ -2,6 +2,7 @@ #include // Para Uint8 +#include #include // Para unique_ptr, shared_ptr #include // Para string @@ -18,13 +19,13 @@ constexpr int TEXT_STROKE = 8; // --- Estructuras auxiliares --- struct TextOffset { - int x, y, w; + int x, y, w; }; struct TextFile { - int box_width; // Anchura de la caja de cada caracter en el png - int box_height; // Altura de la caja de cada caracter en el png - TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra + int box_width; // Anchura de la caja de cada caracter en el png + int box_height; // Altura de la caja de cada caracter en el png + std::array offset = {}; // Vector con las posiciones y ancho de cada letra }; // Llena una estructura TextFile desde un fichero @@ -32,41 +33,42 @@ auto loadTextFile(const std::string &file_path) -> std::shared_ptr; // --- Clase Text: pinta texto en pantalla a partir de un bitmap --- class Text { - public: - // --- Constructores y destructor --- - Text(std::shared_ptr texture, const std::string &text_file); - Text(std::shared_ptr texture, std::shared_ptr text_file); - ~Text() = default; + public: + // --- Constructores y destructor --- + Text(std::shared_ptr texture, const std::string &text_file); + Text(std::shared_ptr texture, std::shared_ptr text_file); + ~Text() = default; - // --- Métodos de escritura en pantalla --- - void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla - void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño + // --- Métodos de escritura en pantalla --- + void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla + void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño - // --- Escritura en textura --- - auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1) -> std::shared_ptr; // Escribe el texto en una textura - auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura + // --- Escritura en textura --- + auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1) -> std::shared_ptr; // Escribe el texto en una textura + auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura - // --- Métodos de escritura avanzada --- - void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores - void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra - void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x - void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras + // --- Métodos de escritura avanzada --- + void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores + void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra + void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x + void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras - // --- Utilidades --- - [[nodiscard]] auto lenght(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena - [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual + // --- Utilidades --- + [[nodiscard]] auto lenght(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena + [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual - // --- Configuración --- - void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra - void setPalette(int number); // Establece una paleta + // --- Configuración --- + void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra + void setPalette(int number); // Establece una paleta - private: - // --- Objetos y punteros --- - std::unique_ptr sprite_ = nullptr; // Objeto con los gráficos para el texto + private: + // --- Objetos y punteros --- + std::unique_ptr sprite_ = nullptr; // Objeto con los gráficos para el texto - // --- Variables --- - int box_width_ = 0; // Anchura de la caja de cada caracter en el png - int box_height_ = 0; // Altura de la caja de cada caracter en el png - bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras - TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra + // --- Variables --- + int box_width_ = 0; // Anchura de la caja de cada caracter en el png + int box_height_ = 0; // Altura de la caja de cada caracter en el png + bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras + std::array offset_ = {}; + ; // Vector con las posiciones y ancho de cada letra }; \ No newline at end of file diff --git a/source/texture.cpp b/source/texture.cpp index 21f7e8e..6c52975 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -240,7 +240,7 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr: size_t pixel_count = raw_pixels.size(); - auto pixels = std::shared_ptr(new Uint8[pixel_count], std::default_delete()); + auto pixels = std::shared_ptr(new Uint8[pixel_count], std::default_delete()); // NOLINT(modernize-avoid-c-arrays) std::memcpy(pixels.get(), raw_pixels.data(), pixel_count); auto surface = std::make_shared(w, h, pixels); diff --git a/source/texture.h b/source/texture.h index b99d61d..19f7ab3 100644 --- a/source/texture.h +++ b/source/texture.h @@ -16,11 +16,11 @@ using Palette = std::array; // Definición de Surface para imágenes con paleta struct Surface { - std::shared_ptr data; + std::shared_ptr data; // NOLINT(modernize-avoid-c-arrays) Uint16 w, h; // Constructor - Surface(Uint16 width, Uint16 height, std::shared_ptr pixels) + Surface(Uint16 width, Uint16 height, std::shared_ptr pixels) // NOLINT(modernize-avoid-c-arrays) : data(std::move(pixels)), w(width), h(height) {} }; diff --git a/source/tiled_bg.h b/source/tiled_bg.h index f78dbc6..0f060f6 100644 --- a/source/tiled_bg.h +++ b/source/tiled_bg.h @@ -1,6 +1,7 @@ #pragma once #include // Para SDL_FRect, SDL_SetTextureColorMod, SDL_Renderer, SDL_Texture +#include #include "utils.h" // Para Color @@ -50,7 +51,7 @@ private: SDL_FRect pos_; // Posición y tamaño del mosaico SDL_FRect window_; // Ventana visible para la textura de fondo del título TiledBGMode mode_; // Tipo de movimiento del mosaico - double sin_[360]; // Vector con los valores del seno precalculados + std::array sin_; // Vector con los valores del seno precalculados float desp_ = 0.0f; // Desplazamiento aplicado float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle bool stopping_ = false; // Indica si se está deteniendo diff --git a/source/ui/menu_renderer.h b/source/ui/menu_renderer.h index 93f5b02..905b75d 100644 --- a/source/ui/menu_renderer.h +++ b/source/ui/menu_renderer.h @@ -2,6 +2,7 @@ #include // Para SDL_FRect, Uint32 +#include #include // Para size_t #include // Para shared_ptr, unique_ptr #include // Para vector @@ -14,59 +15,59 @@ class MenuOption; class Text; class MenuRenderer { - public: - MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr element_text, std::shared_ptr title_text); + public: + MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr element_text, std::shared_ptr title_text); - // Métodos principales de la vista - void render(const ServiceMenu *menu_state); - void update(const ServiceMenu *menu_state); + // Métodos principales de la vista + void render(const ServiceMenu *menu_state); + void update(const ServiceMenu *menu_state); - // Método para notificar al renderer que el layout puede haber cambiado - void onLayoutChanged(const ServiceMenu *menu_state); - void setLayout(const ServiceMenu *menu_state); + // Método para notificar al renderer que el layout puede haber cambiado + void onLayoutChanged(const ServiceMenu *menu_state); + void setLayout(const ServiceMenu *menu_state); - // Getters - [[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; } + // Getters + [[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; } -private: - // --- Referencias a los renderizadores de texto --- - std::shared_ptr element_text_; - std::shared_ptr title_text_; + private: + // --- Referencias a los renderizadores de texto --- + std::shared_ptr element_text_; + std::shared_ptr title_text_; - // --- Variables de estado de la vista (layout y animación) --- - SDL_FRect rect_{}; - SDL_FRect border_rect_{}; - size_t width_ = 0; - size_t height_ = 0; - size_t options_height_ = 0; - size_t options_padding_ = 0; - size_t options_y_ = 0; - size_t title_height_ = 0; - size_t title_padding_ = 0; - size_t upper_height_ = 0; - size_t lower_height_ = 0; - size_t lower_padding_ = 0; - Uint32 color_counter_ = 0; + // --- Variables de estado de la vista (layout y animación) --- + SDL_FRect rect_{}; + SDL_FRect border_rect_{}; + size_t width_ = 0; + size_t height_ = 0; + size_t options_height_ = 0; + size_t options_padding_ = 0; + size_t options_y_ = 0; + size_t title_height_ = 0; + size_t title_padding_ = 0; + size_t upper_height_ = 0; + size_t lower_height_ = 0; + size_t lower_padding_ = 0; + Uint32 color_counter_ = 0; - // --- Variables para animación de resize --- - SDL_FRect rect_anim_from_{}; - SDL_FRect rect_anim_to_{}; - int resize_anim_step_ = 0; - int resize_anim_steps_ = 8; - bool resizing_ = false; + // --- Variables para animación de resize --- + SDL_FRect rect_anim_from_{}; + SDL_FRect rect_anim_to_{}; + int resize_anim_step_ = 0; + int resize_anim_steps_ = 8; + bool resizing_ = false; - // --- Anchos precalculados --- - int group_menu_widths_[5]{}; + // --- Anchos precalculados --- + std::array group_menu_widths_ = {}; - // --- Métodos privados de la vista --- - void setAnchors(const ServiceMenu *menu_state); - auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect; - void resize(const ServiceMenu *menu_state); - void setSize(const ServiceMenu *menu_state); - void updateResizeAnimation(); - void precalculateMenuWidths(const std::vector> &all_options, const ServiceMenu *menu_state); - [[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int; - auto getAnimatedSelectedColor() -> Color; - void updateColorCounter(); - auto setRect(SDL_FRect rect) -> SDL_FRect; + // --- Métodos privados de la vista --- + void setAnchors(const ServiceMenu *menu_state); + auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect; + void resize(const ServiceMenu *menu_state); + void setSize(const ServiceMenu *menu_state); + void updateResizeAnimation(); + void precalculateMenuWidths(const std::vector> &all_options, const ServiceMenu *menu_state); + [[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int; + auto getAnimatedSelectedColor() -> Color; + void updateColorCounter(); + auto setRect(SDL_FRect rect) -> SDL_FRect; }; diff --git a/source/ui/service_menu.h b/source/ui/service_menu.h index 4cb3cc6..00515fb 100644 --- a/source/ui/service_menu.h +++ b/source/ui/service_menu.h @@ -31,10 +31,14 @@ class ServiceMenu { static constexpr size_t MIN_WIDTH = 240; static constexpr size_t MIN_GAP_OPTION_VALUE = 30; + // --- Métodos de singleton --- static void init(); static void destroy(); static auto get() -> ServiceMenu *; + ServiceMenu(const ServiceMenu &) = delete; + auto operator=(const ServiceMenu &) -> ServiceMenu & = delete; + // --- Métodos principales --- void toggle(); void render(); void update(); @@ -96,10 +100,10 @@ private: [[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string; void setHiddenOptions(); - // --- Singleton --- + // --- Constructores y destructor privados (singleton) --- ServiceMenu(); ~ServiceMenu() = default; - ServiceMenu(const ServiceMenu &) = delete; - auto operator=(const ServiceMenu &) -> ServiceMenu & = delete; + + // --- Instancia singleton --- static ServiceMenu *instance; };