From 3ca744ee46c0487706c65b4ce142cbef97f218db Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Mon, 23 Mar 2026 08:58:31 +0100 Subject: [PATCH] clang-format --- CMakeLists.txt | 58 ++ source/animated_sprite.hpp | 98 +-- source/asset.hpp | 110 +-- source/asset_integrated.hpp | 28 +- source/audio.hpp | 170 ++-- source/background.hpp | 216 ++--- source/balloon.hpp | 528 ++++++------- source/balloon_formations.hpp | 152 ++-- source/balloon_manager.hpp | 152 ++-- source/bullet.hpp | 106 +-- source/bullet_manager.hpp | 72 +- source/color.cpp | 124 +-- source/color.hpp | 214 ++--- source/cooldown.hpp | 7 +- source/defaults.hpp | 396 +++++----- source/define_buttons.hpp | 106 +-- source/demo.hpp | 52 +- source/difficulty.cpp | 52 +- source/difficulty.hpp | 28 +- source/director.hpp | 70 +- source/enter_name.hpp | 54 +- source/explosions.hpp | 48 +- source/fade.cpp | 19 +- source/fade.hpp | 174 ++-- source/game_logo.hpp | 194 ++--- source/gamepad_config_manager.hpp | 202 ++--- source/global_events.cpp | 86 +- source/global_events.hpp | 4 +- source/global_inputs.cpp | 362 ++++----- source/global_inputs.hpp | 4 +- source/input.hpp | 342 ++++---- source/item.hpp | 126 +-- source/lang.cpp | 296 +++---- source/lang.hpp | 42 +- source/manage_hiscore_table.cpp | 5 +- source/manage_hiscore_table.hpp | 72 +- source/mouse.cpp | 32 +- source/mouse.hpp | 14 +- source/moving_sprite.hpp | 128 +-- source/options.cpp | 748 +++++++++--------- source/options.hpp | 94 +-- source/param.cpp | 352 ++++----- source/param.hpp | 324 ++++---- source/path_sprite.hpp | 114 +-- source/pause_manager.hpp | 224 +++--- source/player.hpp | 636 +++++++-------- source/rendering/opengl/opengl_shader.cpp | 920 +++++++++++----------- source/rendering/opengl/opengl_shader.hpp | 24 +- source/rendering/shader_backend.hpp | 18 +- source/resource.cpp | 52 +- source/resource.hpp | 284 +++---- source/resource_helper.cpp | 144 ++-- source/resource_helper.hpp | 56 +- source/resource_loader.hpp | 40 +- source/resource_pack.hpp | 48 +- source/scoreboard.hpp | 266 +++---- source/screen.hpp | 394 ++++----- source/section.hpp | 70 +- source/sections/credits.hpp | 252 +++--- source/sections/game.hpp | 496 ++++++------ source/sections/hiscore_table.cpp | 8 +- source/sections/hiscore_table.hpp | 112 +-- source/sections/instructions.hpp | 118 +-- source/sections/intro.hpp | 158 ++-- source/sections/logo.hpp | 108 +-- source/sections/title.cpp | 4 +- source/sections/title.hpp | 190 ++--- source/shutdown.cpp | 218 ++--- source/shutdown.hpp | 36 +- source/smart_sprite.hpp | 60 +- source/sprite.hpp | 98 +-- source/stage.hpp | 144 ++-- source/stage_interface.hpp | 16 +- source/system_utils.cpp | 278 +++---- source/system_utils.hpp | 44 +- source/tabe.hpp | 240 +++--- source/text.hpp | 144 ++-- source/texture.hpp | 102 +-- source/tiled_bg.hpp | 86 +- source/ui/logger.hpp | 142 ++-- source/ui/menu_option.hpp | 314 ++++---- source/ui/menu_renderer.hpp | 186 ++--- source/ui/notifier.hpp | 162 ++-- source/ui/service_menu.hpp | 190 ++--- source/ui/ui_message.hpp | 68 +- source/ui/window_message.hpp | 394 ++++----- source/utils.hpp | 38 +- source/writer.hpp | 80 +- 88 files changed, 7147 insertions(+), 7090 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a17012..e1c8c29 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,6 +6,7 @@ project(coffee_crisis_arcade_edition VERSION 2.00) # Establecer estándar de C++ set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED True) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # Establece la política CMP0072 para indicar cómo se debe seleccionar la implementación de OpenGL. # En este caso, se elige la opción "GLVND", que utiliza bibliotecas modernas y modulares (libOpenGL, libGLX), @@ -176,3 +177,60 @@ endif() # Especificar la ubicación del ejecutable set_target_properties(${PROJECT_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}) + +# --- 5. STATIC ANALYSIS TARGETS --- + +find_program(CLANG_TIDY_EXE NAMES clang-tidy) +find_program(CLANG_FORMAT_EXE NAMES clang-format) + +# Recopilar todos los archivos fuente, excluyendo external/ +file(GLOB_RECURSE ALL_SOURCE_FILES + "${CMAKE_SOURCE_DIR}/source/*.cpp" + "${CMAKE_SOURCE_DIR}/source/*.hpp" + "${CMAKE_SOURCE_DIR}/source/*.h" +) +list(FILTER ALL_SOURCE_FILES EXCLUDE REGEX ".*/external/.*") + +# Targets de clang-tidy +if(CLANG_TIDY_EXE) + add_custom_target(tidy + COMMAND ${CLANG_TIDY_EXE} + -p ${CMAKE_BINARY_DIR} + ${ALL_SOURCE_FILES} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + COMMENT "Running clang-tidy..." + ) + + add_custom_target(tidy-fix + COMMAND ${CLANG_TIDY_EXE} + -p ${CMAKE_BINARY_DIR} + --fix + ${ALL_SOURCE_FILES} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + COMMENT "Running clang-tidy with fixes..." + ) +else() + message(STATUS "clang-tidy no encontrado - targets 'tidy' y 'tidy-fix' no disponibles") +endif() + +# Targets de clang-format +if(CLANG_FORMAT_EXE) + add_custom_target(format + COMMAND ${CLANG_FORMAT_EXE} + -i + ${ALL_SOURCE_FILES} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + COMMENT "Running clang-format..." + ) + + add_custom_target(format-check + COMMAND ${CLANG_FORMAT_EXE} + --dry-run + --Werror + ${ALL_SOURCE_FILES} + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + COMMENT "Checking clang-format..." + ) +else() + message(STATUS "clang-format no encontrado - targets 'format' y 'format-check' no disponibles") +endif() diff --git a/source/animated_sprite.hpp b/source/animated_sprite.hpp index d26e2a8..cf04548 100644 --- a/source/animated_sprite.hpp +++ b/source/animated_sprite.hpp @@ -16,25 +16,25 @@ class Texture; // --- Estructuras --- struct Animation { - static constexpr float DEFAULT_SPEED = 80.0F; + static constexpr float DEFAULT_SPEED = 80.0F; - std::string name; // Nombre de la animación - std::vector frames; // Frames que componen la animación - float speed{DEFAULT_SPEED}; // Velocidad de reproducción (ms entre frames) - int loop{0}; // Frame de vuelta al terminar (-1 para no repetir) - bool completed{false}; // Indica si la animación ha finalizado - size_t current_frame{0}; // Frame actual en reproducción - float time_accumulator{0.0F}; // Acumulador de tiempo para animaciones time-based - bool paused{false}; // La animación no avanza + std::string name; // Nombre de la animación + std::vector frames; // Frames que componen la animación + float speed{DEFAULT_SPEED}; // Velocidad de reproducción (ms entre frames) + int loop{0}; // Frame de vuelta al terminar (-1 para no repetir) + bool completed{false}; // Indica si la animación ha finalizado + size_t current_frame{0}; // Frame actual en reproducción + float time_accumulator{0.0F}; // Acumulador de tiempo para animaciones time-based + bool paused{false}; // La animación no avanza - Animation() = default; + Animation() = default; }; struct AnimationConfig { - float frame_width = 1.0F; - float frame_height = 1.0F; - int frames_per_row = 1; - int max_tiles = 1; + float frame_width = 1.0F; + float frame_height = 1.0F; + int frames_per_row = 1; + int max_tiles = 1; }; // --- Tipos --- @@ -45,44 +45,44 @@ auto loadAnimationsFromFile(const std::string& file_path) -> AnimationsFileBuffe // --- Clase AnimatedSprite: sprite animado que hereda de MovingSprite --- class AnimatedSprite : public MovingSprite { - public: - // --- 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(std::move(texture)) {} - ~AnimatedSprite() override = default; + public: + // --- 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(std::move(texture)) {} + ~AnimatedSprite() override = default; - // --- Métodos principales --- - void update(float delta_time) override; // Actualiza la animación (time-based) + // --- Métodos principales --- + void update(float delta_time) override; // Actualiza la animación (time-based) - // --- Control de animaciones --- - void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre - void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice - void resetAnimation(); // Reinicia la animación actual - void setAnimationSpeed(float value); // Establece la velocidad de la animación - auto getAnimationSpeed() const -> float { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual - void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación - void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación - auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual + // --- Control de animaciones --- + void setCurrentAnimation(const std::string& name = "default", bool reset = true); // Establece la animación por nombre + void setCurrentAnimation(int index = 0, bool reset = true); // Establece la animación por índice + void resetAnimation(); // Reinicia la animación actual + void setAnimationSpeed(float value); // Establece la velocidad de la animación + auto getAnimationSpeed() const -> float { return animations_[current_animation_].speed; } // Obtiene la velocidad de la animación actual + void animtionPause() { animations_[current_animation_].paused = true; } // Detiene la animación + void animationResume() { animations_[current_animation_].paused = false; } // Reanuda la animación + auto getCurrentAnimationFrame() const -> size_t { return animations_[current_animation_].current_frame; } // Obtiene el numero de frame de la animación actual - // --- Consultas --- - auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado - auto getAnimationIndex(const std::string& name) -> int; // Obtiene el índice de una animación por nombre + // --- Consultas --- + auto animationIsCompleted() -> bool; // Comprueba si la animación ha terminado + auto getAnimationIndex(const std::string& name) -> int; // Obtiene el índice de una animación por nombre - protected: - // --- Variables de estado --- - std::vector animations_; // Vector de animaciones disponibles - std::unordered_map animation_indices_; // Mapa para búsqueda rápida por nombre - int current_animation_ = 0; // Índice de la animación activa + protected: + // --- Variables de estado --- + std::vector animations_; // Vector de animaciones disponibles + std::unordered_map animation_indices_; // Mapa para búsqueda rápida por nombre + int current_animation_ = 0; // Índice de la animación activa - // --- Métodos internos --- - void animate(float delta_time); // Calcula el frame correspondiente a la animación (time-based) - void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas - void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración - void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame - auto processAnimationBlock(const AnimationsFileBuffer& source, size_t start_index, const AnimationConfig& config) -> size_t; // Procesa un bloque completo de animación - static void processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config); // Procesa un parámetro individual de animación - static void parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config); // Parsea el parámetro de frames (lista separada por comas) - void updateSpriteClip(); // Actualiza el spriteClip con el frame correspondiente + // --- Métodos internos --- + void animate(float delta_time); // Calcula el frame correspondiente a la animación (time-based) + void loadFromAnimationsFileBuffer(const AnimationsFileBuffer& source); // Carga la animación desde un vector de cadenas + void processConfigLine(const std::string& line, AnimationConfig& config); // Procesa una línea de configuración + void updateFrameCalculations(AnimationConfig& config); // Actualiza los cálculos basados en las dimensiones del frame + auto processAnimationBlock(const AnimationsFileBuffer& source, size_t start_index, const AnimationConfig& config) -> size_t; // Procesa un bloque completo de animación + static void processAnimationParameter(const std::string& line, Animation& animation, const AnimationConfig& config); // Procesa un parámetro individual de animación + static void parseFramesParameter(const std::string& frames_str, Animation& animation, const AnimationConfig& config); // Parsea el parámetro de frames (lista separada por comas) + void updateSpriteClip(); // Actualiza el spriteClip con el frame correspondiente }; \ No newline at end of file diff --git a/source/asset.hpp b/source/asset.hpp index df36c49..fcb9a8d 100644 --- a/source/asset.hpp +++ b/source/asset.hpp @@ -8,67 +8,67 @@ // --- Clase Asset: gestor optimizado de recursos (singleton) --- class Asset { - public: - // --- Enums --- - enum class Type : int { - BITMAP, // Imágenes - MUSIC, // Música - SOUND, // Sonidos - FONT, // Fuentes - LANG, // Idiomas - DATA, // Datos - DEMODATA, // Datos de demo - ANIMATION, // Animaciones - PALETTE, // Paletas - SIZE, // Tamaño - }; + public: + // --- Enums --- + enum class Type : int { + BITMAP, // Imágenes + MUSIC, // Música + SOUND, // Sonidos + FONT, // Fuentes + LANG, // Idiomas + DATA, // Datos + DEMODATA, // Datos de demo + ANIMATION, // Animaciones + PALETTE, // Paletas + SIZE, // Tamaño + }; - // --- Métodos de singleton --- - static void init(const std::string& executable_path); - static void destroy(); - static auto get() -> Asset*; - Asset(const Asset&) = delete; - auto operator=(const Asset&) -> Asset& = delete; + // --- Métodos de singleton --- + static void init(const std::string& executable_path); + static void destroy(); + static auto get() -> Asset*; + Asset(const Asset&) = delete; + auto operator=(const Asset&) -> Asset& = delete; - // --- Métodos para la gestión de recursos --- - void add(const std::string& file_path, Type type, bool required = true, bool absolute = false); - void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables - [[nodiscard]] auto get(const std::string& filename) const -> std::string; // Mantener nombre original - [[nodiscard]] auto loadData(const std::string& filename) const -> std::vector; // Carga datos del archivo - [[nodiscard]] auto check() const -> bool; - [[nodiscard]] auto getListByType(Type type) const -> std::vector; - [[nodiscard]] auto exists(const std::string& filename) const -> bool; // Nueva función para verificar existencia + // --- Métodos para la gestión de recursos --- + void add(const std::string& file_path, Type type, bool required = true, bool absolute = false); + void loadFromFile(const std::string& config_file_path, const std::string& prefix = "", const std::string& system_folder = ""); // Con soporte para variables + [[nodiscard]] auto get(const std::string& filename) const -> std::string; // Mantener nombre original + [[nodiscard]] auto loadData(const std::string& filename) const -> std::vector; // Carga datos del archivo + [[nodiscard]] auto check() const -> bool; + [[nodiscard]] auto getListByType(Type type) const -> std::vector; + [[nodiscard]] auto exists(const std::string& filename) const -> bool; // Nueva función para verificar existencia - private: - // --- Estructuras privadas --- - struct Item { - std::string file; // Ruta completa del archivo - Type type; // Tipo de recurso - bool required; // Indica si el archivo es obligatorio + private: + // --- Estructuras privadas --- + struct Item { + std::string file; // Ruta completa del archivo + Type type; // Tipo de recurso + bool required; // Indica si el archivo es obligatorio - Item(std::string path, Type asset_type, bool is_required) - : file(std::move(path)), - type(asset_type), - required(is_required) {} - }; + Item(std::string path, Type asset_type, bool is_required) + : file(std::move(path)), + type(asset_type), + required(is_required) {} + }; - // --- Variables internas --- - std::unordered_map file_list_; // Mapa para búsqueda O(1) - std::string executable_path_; // Ruta del ejecutable + // --- Variables internas --- + std::unordered_map file_list_; // Mapa para búsqueda O(1) + std::string executable_path_; // Ruta del ejecutable - // --- Métodos internos --- - [[nodiscard]] auto checkFile(const std::string& path) const -> bool; // Verifica si un archivo existe - [[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo - [[nodiscard]] static auto parseAssetType(const std::string& type_str) -> Type; // Convierte string a tipo - void addToMap(const std::string& file_path, Type type, bool required, bool absolute); // Añade archivo al mapa - [[nodiscard]] static auto replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string; // Reemplaza variables en la ruta - static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones + // --- Métodos internos --- + [[nodiscard]] auto checkFile(const std::string& path) const -> bool; // Verifica si un archivo existe + [[nodiscard]] static auto getTypeName(Type type) -> std::string; // Obtiene el nombre del tipo + [[nodiscard]] static auto parseAssetType(const std::string& type_str) -> Type; // Convierte string a tipo + void addToMap(const std::string& file_path, Type type, bool required, bool absolute); // Añade archivo al mapa + [[nodiscard]] static auto replaceVariables(const std::string& path, const std::string& prefix, const std::string& system_folder) -> std::string; // Reemplaza variables en la ruta + static auto parseOptions(const std::string& options, bool& required, bool& absolute) -> void; // Parsea opciones - // --- Constructores y destructor privados (singleton) --- - explicit Asset(std::string executable_path) // Constructor privado - : executable_path_(std::move(executable_path)) {} - ~Asset() = default; // Destructor privado + // --- Constructores y destructor privados (singleton) --- + explicit Asset(std::string executable_path) // Constructor privado + : executable_path_(std::move(executable_path)) {} + ~Asset() = default; // Destructor privado - // --- Instancia singleton --- - static Asset* instance; // Instancia única de Asset + // --- Instancia singleton --- + static Asset* instance; // Instancia única de Asset }; \ No newline at end of file diff --git a/source/asset_integrated.hpp b/source/asset_integrated.hpp index 721f78b..791e341 100644 --- a/source/asset_integrated.hpp +++ b/source/asset_integrated.hpp @@ -7,23 +7,23 @@ // Extensión de Asset que integra ResourceLoader class AssetIntegrated : public Asset { - public: - // Inicializa Asset con ResourceLoader - static void initWithResourcePack(const std::string& executable_path, - const std::string& resource_pack_path = "resources.pack"); + public: + // Inicializa Asset con ResourceLoader + static void initWithResourcePack(const std::string& executable_path, + const std::string& resource_pack_path = "resources.pack"); - // Carga un archivo usando ResourceLoader como primera opción - static auto loadFile(const std::string& filename) -> std::vector; + // Carga un archivo usando ResourceLoader como primera opción + static auto loadFile(const std::string& filename) -> std::vector; - // Verifica si un archivo existe (pack o filesystem) - static auto fileExists(const std::string& filename) -> bool; + // Verifica si un archivo existe (pack o filesystem) + static auto fileExists(const std::string& filename) -> bool; - // Obtiene la ruta completa para archivos del sistema/config - static auto getSystemPath(const std::string& filename) -> std::string; + // Obtiene la ruta completa para archivos del sistema/config + static auto getSystemPath(const std::string& filename) -> std::string; - private: - static bool resource_pack_enabled; + private: + static bool resource_pack_enabled; - // Determina si un archivo debe cargarse del pack o del filesystem - static auto shouldUseResourcePack(const std::string& filepath) -> bool; + // Determina si un archivo debe cargarse del pack o del filesystem + static auto shouldUseResourcePack(const std::string& filepath) -> bool; }; \ No newline at end of file diff --git a/source/audio.hpp b/source/audio.hpp index adaef96..22593fb 100644 --- a/source/audio.hpp +++ b/source/audio.hpp @@ -5,107 +5,107 @@ // --- Clase Audio: gestor de audio (singleton) --- class Audio { - public: - // --- Enums --- - enum class Group : int { - ALL = -1, // Todos los grupos - GAME = 0, // Sonidos del juego - INTERFACE = 1 // Sonidos de la interfaz - }; + public: + // --- Enums --- + enum class Group : int { + ALL = -1, // Todos los grupos + GAME = 0, // Sonidos del juego + INTERFACE = 1 // Sonidos de la interfaz + }; - enum class MusicState { - PLAYING, // Reproduciendo música - PAUSED, // Música pausada - STOPPED, // Música detenida - }; + enum class MusicState { + PLAYING, // Reproduciendo música + PAUSED, // Música pausada + STOPPED, // Música detenida + }; - // --- Constantes --- - static constexpr int MAX_VOLUME = 100; // Volumen máximo - static constexpr int MIN_VOLUME = 0; // Volumen mínimo - static constexpr int FREQUENCY = 48000; // Frecuencia de audio + // --- Constantes --- + static constexpr int MAX_VOLUME = 100; // Volumen máximo + static constexpr int MIN_VOLUME = 0; // Volumen mínimo + static constexpr int FREQUENCY = 48000; // Frecuencia de audio - // --- Métodos de singleton --- - static void init(); // Inicializa el objeto Audio - static void destroy(); // Libera el objeto Audio - static auto get() -> Audio*; // Obtiene el puntero al objeto Audio - Audio(const Audio&) = delete; // Evitar copia - auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación + // --- Métodos de singleton --- + static void init(); // Inicializa el objeto Audio + static void destroy(); // Libera el objeto Audio + static auto get() -> Audio*; // Obtiene el puntero al objeto Audio + Audio(const Audio&) = delete; // Evitar copia + auto operator=(const Audio&) -> Audio& = delete; // Evitar asignación - // --- Método principal --- - static void update(); + // --- Método principal --- + static void update(); - // --- Control de Música --- - void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle - void pauseMusic(); // Pausar reproducción de música - void resumeMusic(); // Continua la música pausada - void stopMusic(); // Detener completamente la música - void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música + // --- Control de Música --- + void playMusic(const std::string& name, int loop = -1); // Reproducir música en bucle + void pauseMusic(); // Pausar reproducción de música + void resumeMusic(); // Continua la música pausada + void stopMusic(); // Detener completamente la música + void fadeOutMusic(int milliseconds) const; // Fundido de salida de la música - // --- Control de Sonidos --- - void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual - void stopAllSounds() const; // Detener todos los sonidos + // --- Control de Sonidos --- + void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual + void stopAllSounds() const; // Detener todos los sonidos - // --- Configuración General --- - void enable(bool value); // Establecer estado general - void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general - void applySettings(); // Aplica la configuración + // --- Configuración General --- + void enable(bool value); // Establecer estado general + void toggleEnabled() { enabled_ = !enabled_; } // Alternar estado general + void applySettings(); // Aplica la configuración - // --- Configuración de Sonidos --- - void enableSound() { sound_enabled_ = true; } // Habilitar sonidos - void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos - void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos - void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos + // --- Configuración de Sonidos --- + void enableSound() { sound_enabled_ = true; } // Habilitar sonidos + void disableSound() { sound_enabled_ = false; } // Deshabilitar sonidos + void enableSound(bool value) { sound_enabled_ = value; } // Establecer estado de sonidos + void toggleSound() { sound_enabled_ = !sound_enabled_; } // Alternar estado de sonidos - // --- Configuración de Música --- - void enableMusic() { music_enabled_ = true; } // Habilitar música - void disableMusic() { music_enabled_ = false; } // Deshabilitar música - void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música - void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música + // --- Configuración de Música --- + void enableMusic() { music_enabled_ = true; } // Habilitar música + void disableMusic() { music_enabled_ = false; } // Deshabilitar música + void enableMusic(bool value) { music_enabled_ = value; } // Establecer estado de música + void toggleMusic() { music_enabled_ = !music_enabled_; } // Alternar estado de música - // --- Control de Volumen --- - void setSoundVolume(int volume, Group group = Group::ALL) const; // Ajustar volumen de efectos - void setMusicVolume(int volume) const; // Ajustar volumen de música + // --- Control de Volumen --- + void setSoundVolume(int volume, Group group = Group::ALL) const; // Ajustar volumen de efectos + void setMusicVolume(int volume) const; // Ajustar volumen de música - // --- Getters para debug --- - [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - [[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; } - [[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; } - [[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; } - [[nodiscard]] static auto getRealMusicState() -> MusicState; // Consulta directamente a jailaudio - [[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; } + // --- Getters para debug --- + [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } + [[nodiscard]] auto isSoundEnabled() const -> bool { return sound_enabled_; } + [[nodiscard]] auto isMusicEnabled() const -> bool { return music_enabled_; } + [[nodiscard]] auto getMusicState() const -> MusicState { return music_.state; } + [[nodiscard]] static auto getRealMusicState() -> MusicState; // Consulta directamente a jailaudio + [[nodiscard]] auto getCurrentMusicName() const -> const std::string& { return music_.name; } - private: - // --- Estructuras privadas --- - struct Music { - MusicState state; // Estado actual de la música (reproduciendo, detenido, en pausa) - std::string name; // Última pista de música reproducida - bool loop; // Indica si la última pista de música se debe reproducir en bucle + private: + // --- Estructuras privadas --- + struct Music { + MusicState state; // Estado actual de la música (reproduciendo, detenido, en pausa) + std::string name; // Última pista de música reproducida + bool loop; // Indica si la última pista de música se debe reproducir en bucle - // Constructor para inicializar la música con valores predeterminados - Music() - : state(MusicState::STOPPED), - loop(false) {} + // Constructor para inicializar la música con valores predeterminados + Music() + : state(MusicState::STOPPED), + loop(false) {} - // Constructor para inicializar con valores específicos - Music(MusicState init_state, std::string init_name, bool init_loop) - : state(init_state), - name(std::move(init_name)), - loop(init_loop) {} - }; + // Constructor para inicializar con valores específicos + Music(MusicState init_state, std::string init_name, bool init_loop) + : state(init_state), + name(std::move(init_name)), + loop(init_loop) {} + }; - // --- Variables de estado --- - Music music_; // Estado de la música - bool enabled_ = true; // Estado general del audio - bool sound_enabled_ = true; // Estado de los efectos de sonido - bool music_enabled_ = true; // Estado de la música + // --- Variables de estado --- + Music music_; // Estado de la música + bool enabled_ = true; // Estado general del audio + bool sound_enabled_ = true; // Estado de los efectos de sonido + bool music_enabled_ = true; // Estado de la música - // --- Métodos internos --- - void initSDLAudio(); // Inicializa SDL Audio + // --- Métodos internos --- + void initSDLAudio(); // Inicializa SDL Audio - // --- Constructores y destructor privados (singleton) --- - Audio(); // Constructor privado - ~Audio(); // Destructor privado + // --- Constructores y destructor privados (singleton) --- + Audio(); // Constructor privado + ~Audio(); // Destructor privado - // --- Instancia singleton --- - static Audio* instance; // Instancia única de Audio + // --- Instancia singleton --- + static Audio* instance; // Instancia única de Audio }; \ No newline at end of file diff --git a/source/background.hpp b/source/background.hpp index afb4f00..6d0c939 100644 --- a/source/background.hpp +++ b/source/background.hpp @@ -17,124 +17,124 @@ class AnimatedSprite; // --- Clase Background: gestiona el fondo de la sección jugable --- class Background { - public: - // --- Enums --- - enum class State { - NORMAL, // Progresión normal del día - COMPLETED // Reducción gradual de la actividad - }; + public: + // --- Enums --- + enum class State { + NORMAL, // Progresión normal del día + COMPLETED // Reducción gradual de la actividad + }; - // --- Tipos --- - using ProgressCallback = std::function; // Callback para sincronización + // --- Tipos --- + using ProgressCallback = std::function; // Callback para sincronización - // --- Constructor y destructor --- - Background(float total_progress_to_complete = 6100.0F); // Constructor principal - ~Background(); // Destructor + // --- Constructor y destructor --- + Background(float total_progress_to_complete = 6100.0F); // Constructor principal + ~Background(); // Destructor - // --- Métodos principales --- - void update(float delta_time); // Actualiza la lógica del objeto - void render(); // Dibuja el objeto - void reset(); // Reinicia la progresión + // --- Métodos principales --- + void update(float delta_time); // Actualiza la lógica del objeto + void render(); // Dibuja el objeto + void reset(); // Reinicia la progresión - // --- Configuración --- - void setPos(SDL_FRect pos); // Establece la posición del objeto - void setState(State new_state); // Cambia el estado del fondo - void setProgressCallback(ProgressCallback callback); // Establece callback para sincronización - void removeProgressCallback(); // Elimina el callback - void setManualMode(bool manual); // Activa/desactiva el modo manual - void setCloudsSpeed(float value); // Ajusta la velocidad de las nubes - void setGradientNumber(int value); // Establece el degradado de fondo - void setTransition(float value); // Ajusta la transición entre texturas - void setSunProgression(float progress); // Establece la posición del sol - void setMoonProgression(float progress); // Establece la posición de la luna - void setColor(Color color); // Establece el color de atenuación - void setAlpha(int alpha); // Ajusta la transparencia del fondo + // --- Configuración --- + void setPos(SDL_FRect pos); // Establece la posición del objeto + void setState(State new_state); // Cambia el estado del fondo + void setProgressCallback(ProgressCallback callback); // Establece callback para sincronización + void removeProgressCallback(); // Elimina el callback + void setManualMode(bool manual); // Activa/desactiva el modo manual + void setCloudsSpeed(float value); // Ajusta la velocidad de las nubes + void setGradientNumber(int value); // Establece el degradado de fondo + void setTransition(float value); // Ajusta la transición entre texturas + void setSunProgression(float progress); // Establece la posición del sol + void setMoonProgression(float progress); // Establece la posición de la luna + void setColor(Color color); // Establece el color de atenuación + 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 setProgress(float absolute_progress); // Establece la progresión absoluta + // --- Control de progresión --- + void incrementProgress(float amount = 1.0F); // Incrementa la progresión interna + void setProgress(float absolute_progress); // Establece la progresión absoluta - // --- Getters --- - [[nodiscard]] auto getProgress() const -> float { return progress_; } // Obtiene el progreso actual - [[nodiscard]] auto getState() const -> State { return state_; } // Obtiene el estado actual - [[nodiscard]] auto getCurrentGradient() const -> int { return static_cast(gradient_number_); } // Obtiene el gradiente actual + // --- Getters --- + [[nodiscard]] auto getProgress() const -> float { return progress_; } // Obtiene el progreso actual + [[nodiscard]] auto getState() const -> State { return state_; } // Obtiene el estado actual + [[nodiscard]] auto getCurrentGradient() const -> int { return static_cast(gradient_number_); } // Obtiene el gradiente actual - private: - // --- Constantes --- - static constexpr size_t STAGES = 4; // Número de etapas - static constexpr float MINIMUM_COMPLETED_PROGRESS_PERCENTAGE = 0.05F; // Porcentaje mínimo completado (10%) - static constexpr float SUN_COMPLETION_FACTOR = 0.5F; // Factor de completado del sol - static constexpr float COMPLETION_TRANSITION_DURATION_S = 3.0F; // Duración de la transición de completado en segundos + private: + // --- Constantes --- + static constexpr size_t STAGES = 4; // Número de etapas + static constexpr float MINIMUM_COMPLETED_PROGRESS_PERCENTAGE = 0.05F; // Porcentaje mínimo completado (10%) + static constexpr float SUN_COMPLETION_FACTOR = 0.5F; // Factor de completado del sol + static constexpr float COMPLETION_TRANSITION_DURATION_S = 3.0F; // Duración de la transición de completado en segundos - // --- Objetos y punteros --- - SDL_Renderer* renderer_; // Renderizador de la ventana - SDL_Texture* canvas_; // Textura para componer el fondo - SDL_Texture* color_texture_; // Textura para atenuar el fondo - std::shared_ptr buildings_texture_; // Textura de edificios - std::shared_ptr top_clouds_texture_; // Textura de nubes superiores - std::shared_ptr bottom_clouds_texture_; // Textura de nubes inferiores - std::shared_ptr gradients_texture_; // Textura de gradientes - std::shared_ptr sun_texture_; // Textura del sol - std::shared_ptr moon_texture_; // Textura de la luna - std::unique_ptr top_clouds_sprite_a_; // Sprite de nubes superiores A - std::unique_ptr top_clouds_sprite_b_; // Sprite de nubes superiores B - std::unique_ptr bottom_clouds_sprite_a_; // Sprite de nubes inferiores A - std::unique_ptr bottom_clouds_sprite_b_; // Sprite de nubes inferiores B - std::unique_ptr buildings_sprite_; // Sprite de edificios - std::unique_ptr gradient_sprite_; // Sprite de gradiente - std::unique_ptr sun_sprite_; // Sprite del sol - std::unique_ptr moon_sprite_; // Sprite de la luna - std::unique_ptr grass_sprite_; // Sprite con la hierba + // --- Objetos y punteros --- + SDL_Renderer* renderer_; // Renderizador de la ventana + SDL_Texture* canvas_; // Textura para componer el fondo + SDL_Texture* color_texture_; // Textura para atenuar el fondo + std::shared_ptr buildings_texture_; // Textura de edificios + std::shared_ptr top_clouds_texture_; // Textura de nubes superiores + std::shared_ptr bottom_clouds_texture_; // Textura de nubes inferiores + std::shared_ptr gradients_texture_; // Textura de gradientes + std::shared_ptr sun_texture_; // Textura del sol + std::shared_ptr moon_texture_; // Textura de la luna + std::unique_ptr top_clouds_sprite_a_; // Sprite de nubes superiores A + std::unique_ptr top_clouds_sprite_b_; // Sprite de nubes superiores B + std::unique_ptr bottom_clouds_sprite_a_; // Sprite de nubes inferiores A + std::unique_ptr bottom_clouds_sprite_b_; // Sprite de nubes inferiores B + std::unique_ptr buildings_sprite_; // Sprite de edificios + std::unique_ptr gradient_sprite_; // Sprite de gradiente + std::unique_ptr sun_sprite_; // Sprite del sol + std::unique_ptr moon_sprite_; // Sprite de la luna + std::unique_ptr grass_sprite_; // Sprite con la hierba - // --- Variables de configuración --- - const float total_progress_to_complete_; // Progreso total para completar - const float progress_per_stage_; // Progreso por etapa - const float sun_completion_progress_; // Progreso de completado del sol - const float minimum_completed_progress_; // Progreso mínimo calculado dinámicamente - ProgressCallback progress_callback_; // Callback para notificar cambios de progreso + // --- Variables de configuración --- + const float total_progress_to_complete_; // Progreso total para completar + const float progress_per_stage_; // Progreso por etapa + const float sun_completion_progress_; // Progreso de completado del sol + const float minimum_completed_progress_; // Progreso mínimo calculado dinámicamente + ProgressCallback progress_callback_; // Callback para notificar cambios de progreso - // --- Variables de estado --- - std::vector sun_path_; // Recorrido del sol - std::vector moon_path_; // Recorrido de la luna - std::array gradient_rect_; // Fondos degradados - std::array top_clouds_rect_; // Nubes superiores - std::array bottom_clouds_rect_; // Nubes inferiores - SDL_FRect rect_; // Tamaño del objeto - SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla - 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 clouds_speed_ = 0; // Velocidad de las nubes - float transition_ = 0; // Porcentaje de transición - float current_alpha_float_ = 0.0F; // Acumulador para el valor alfa preciso - size_t gradient_number_ = 0; // Índice de fondo degradado - size_t alpha_color_texture_ = 0; // Transparencia de atenuación - size_t previous_alpha_color_texture_ = 0; // Transparencia anterior - size_t sun_index_ = 0; // Índice del recorrido del sol - size_t moon_index_ = 0; // Índice del recorrido de la luna - int base_ = 0; // Posición base del fondo - Uint8 alpha_ = 0; // Transparencia entre fases - bool manual_mode_ = false; // Si está en modo manual + // --- Variables de estado --- + std::vector sun_path_; // Recorrido del sol + std::vector moon_path_; // Recorrido de la luna + std::array gradient_rect_; // Fondos degradados + std::array top_clouds_rect_; // Nubes superiores + std::array bottom_clouds_rect_; // Nubes inferiores + SDL_FRect rect_; // Tamaño del objeto + SDL_FRect src_rect_; // Parte del objeto para copiar en pantalla + 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 clouds_speed_ = 0; // Velocidad de las nubes + float transition_ = 0; // Porcentaje de transición + float current_alpha_float_ = 0.0F; // Acumulador para el valor alfa preciso + size_t gradient_number_ = 0; // Índice de fondo degradado + size_t alpha_color_texture_ = 0; // Transparencia de atenuación + size_t previous_alpha_color_texture_ = 0; // Transparencia anterior + size_t sun_index_ = 0; // Índice del recorrido del sol + size_t moon_index_ = 0; // Índice del recorrido de la luna + int base_ = 0; // Posición base del fondo + Uint8 alpha_ = 0; // Transparencia entre fases + bool manual_mode_ = false; // Si está en modo manual - // --- Variables para transición suave de completado --- - float completion_transition_timer_ = 0.0F; // Timer para la transición de completado - float completion_initial_progress_ = 0.0F; // Progreso inicial al entrar en estado completado + // --- Variables para transición suave de completado --- + float completion_transition_timer_ = 0.0F; // Timer para la transición de completado + float completion_initial_progress_ = 0.0F; // Progreso inicial al entrar en estado completado - // --- Métodos internos --- - void initializePaths(); // Inicializa las rutas del sol y la luna - void initializeRects(); // Inicializa los rectángulos de gradientes y nubes - void initializeSprites(); // Crea los sprites - void initializeSpriteProperties(); // Configura las propiedades iniciales de los sprites - void initializeTextures(); // Inicializa las texturas de renderizado - void updateProgression(float delta_time); // Actualiza la progresión y calcula transiciones - void updateCloudsSpeed(); // Actualiza la velocidad de las nubes según el estado - 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(float delta_time); // Actualiza el alpha de la textura de atenuación - void updateClouds(float delta_time); // Actualiza el movimiento de las nubes (time-based) - void createSunPath(); // Precalcula el recorrido del sol - void createMoonPath(); // Precalcula el recorrido de la luna + // --- Métodos internos --- + void initializePaths(); // Inicializa las rutas del sol y la luna + void initializeRects(); // Inicializa los rectángulos de gradientes y nubes + void initializeSprites(); // Crea los sprites + void initializeSpriteProperties(); // Configura las propiedades iniciales de los sprites + void initializeTextures(); // Inicializa las texturas de renderizado + void updateProgression(float delta_time); // Actualiza la progresión y calcula transiciones + void updateCloudsSpeed(); // Actualiza la velocidad de las nubes según el estado + 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(float delta_time); // Actualiza el alpha de la textura de atenuación + void updateClouds(float delta_time); // Actualiza el movimiento de las nubes (time-based) + void createSunPath(); // Precalcula el recorrido del sol + void createMoonPath(); // Precalcula el recorrido de la luna }; \ No newline at end of file diff --git a/source/balloon.hpp b/source/balloon.hpp index 278cc27..404cf40 100644 --- a/source/balloon.hpp +++ b/source/balloon.hpp @@ -15,291 +15,291 @@ class Texture; // --- Clase Balloon --- class Balloon { - public: - // --- Constantes relacionadas con globos --- - static constexpr int MAX_BOUNCE = 10; // Cantidad de elementos del vector de deformación + public: + // --- Constantes relacionadas con globos --- + static constexpr int MAX_BOUNCE = 10; // Cantidad de elementos del vector de deformación - static constexpr std::array SCORE = {50, 100, 200, 400}; - static constexpr std::array POWER = {1, 3, 7, 15}; - static constexpr std::array MENACE = {1, 2, 4, 8}; - static constexpr std::array WIDTH = {10, 16, 26, 48, 49}; + static constexpr std::array SCORE = {50, 100, 200, 400}; + static constexpr std::array POWER = {1, 3, 7, 15}; + static constexpr std::array MENACE = {1, 2, 4, 8}; + static constexpr std::array WIDTH = {10, 16, 26, 48, 49}; - static constexpr std::array BOUNCING_SOUND = { - "balloon_bounce0.wav", - "balloon_bounce1.wav", - "balloon_bounce2.wav", - "balloon_bounce3.wav"}; + static constexpr std::array BOUNCING_SOUND = { + "balloon_bounce0.wav", + "balloon_bounce1.wav", + "balloon_bounce2.wav", + "balloon_bounce3.wav"}; - static constexpr std::array POPPING_SOUND = { - "balloon_pop0.wav", - "balloon_pop1.wav", - "balloon_pop2.wav", - "balloon_pop3.wav"}; + static constexpr std::array POPPING_SOUND = { + "balloon_pop0.wav", + "balloon_pop1.wav", + "balloon_pop2.wav", + "balloon_pop3.wav"}; - // Velocidades horizontales en pixels/segundo (convertidas desde 0.7 pixels/frame a 60fps) - static constexpr float VELX_POSITIVE = 0.7F * 60.0F; // 42 pixels/segundo - static constexpr float VELX_NEGATIVE = -0.7F * 60.0F; // -42 pixels/segundo + // Velocidades horizontales en pixels/segundo (convertidas desde 0.7 pixels/frame a 60fps) + static constexpr float VELX_POSITIVE = 0.7F * 60.0F; // 42 pixels/segundo + static constexpr float VELX_NEGATIVE = -0.7F * 60.0F; // -42 pixels/segundo - // Multiplicadores de tempo del juego (sin cambios, son puros multiplicadores) - static constexpr std::array GAME_TEMPO = {0.60F, 0.70F, 0.80F, 0.90F, 1.00F}; + // Multiplicadores de tempo del juego (sin cambios, son puros multiplicadores) + static constexpr std::array GAME_TEMPO = {0.60F, 0.70F, 0.80F, 0.90F, 1.00F}; - static constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10; - static constexpr int POWERBALL_COUNTER = 8; + static constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10; + static constexpr int POWERBALL_COUNTER = 8; - // --- Enums --- - enum class Size : Uint8 { - SMALL = 0, // Tamaño pequeño - MEDIUM = 1, // Tamaño mediano - LARGE = 2, // Tamaño grande - EXTRALARGE = 3, // Tamaño extra grande - }; + // --- Enums --- + enum class Size : Uint8 { + SMALL = 0, // Tamaño pequeño + MEDIUM = 1, // Tamaño mediano + LARGE = 2, // Tamaño grande + EXTRALARGE = 3, // Tamaño extra grande + }; - enum class Type : Uint8 { - BALLOON = 0, // Globo normal - FLOATER = 1, // Globo flotante - POWERBALL = 2, // Globo de poder - }; + enum class Type : Uint8 { + BALLOON = 0, // Globo normal + FLOATER = 1, // Globo flotante + POWERBALL = 2, // Globo de poder + }; - // --- Estructura para manejo de sonido --- - struct Sound { - std::string bouncing_file; // Archivo de sonido al rebotar - std::string popping_file; // Archivo de sonido al explotar - bool bouncing_enabled = false; // Si debe sonar el globo al rebotar - bool poping_enabled = true; // Si debe sonar el globo al explotar - bool enabled = true; // Indica si los globos deben hacer algun sonido - }; + // --- Estructura para manejo de sonido --- + struct Sound { + std::string bouncing_file; // Archivo de sonido al rebotar + std::string popping_file; // Archivo de sonido al explotar + bool bouncing_enabled = false; // Si debe sonar el globo al rebotar + bool poping_enabled = true; // Si debe sonar el globo al explotar + bool enabled = true; // Indica si los globos deben hacer algun sonido + }; - // --- Estructura de configuración para inicialización --- - struct Config { - float x = 0.0F; - float y = 0.0F; - Type type = Type::BALLOON; - Size size = Size::EXTRALARGE; - float vel_x = VELX_POSITIVE; - float game_tempo = GAME_TEMPO.at(0); - float creation_counter = 0.0F; - SDL_FRect play_area = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; - std::shared_ptr texture = nullptr; - std::vector animation; - Sound sound; - }; + // --- Estructura de configuración para inicialización --- + struct Config { + float x = 0.0F; + float y = 0.0F; + Type type = Type::BALLOON; + Size size = Size::EXTRALARGE; + float vel_x = VELX_POSITIVE; + float game_tempo = GAME_TEMPO.at(0); + float creation_counter = 0.0F; + SDL_FRect play_area = {.x = 0.0F, .y = 0.0F, .w = 0.0F, .h = 0.0F}; + std::shared_ptr texture = nullptr; + std::vector animation; + Sound sound; + }; - // --- Constructores y destructor --- - Balloon(const Config& config); - ~Balloon() = default; + // --- Constructores y destructor --- + Balloon(const Config& config); + ~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(float delta_time); // Actualiza la posición y estados del globo (time-based) - void update(float delta_time); // Actualiza el globo (posición, animación, contadores) (time-based) - 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(float delta_time); // Actualiza la posición y estados del globo (time-based) + void update(float delta_time); // Actualiza el globo (posición, animación, contadores) (time-based) + 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 -> Size { return size_; } - [[nodiscard]] auto getType() const -> Type { 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_ == Type::POWERBALL; } - [[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; } - [[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; } + // --- 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 -> Size { return size_; } + [[nodiscard]] auto getType() const -> Type { 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_ == Type::POWERBALL; } + [[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; } + [[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; } + [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } + [[nodiscard]] auto isUsingReversedColor() const -> bool { return use_reversed_colors_; } + [[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); } + + // --- Setters --- + void setVelY(float vel_y) { vy_ = vel_y; } + void setVelX(float vel_x) { vx_ = vel_x; } + void alterVelX(float percent) { vx_ *= percent; } + void setGameTempo(float tempo) { game_tempo_ = tempo; } + void setInvulnerable(bool value) { invulnerable_ = value; } + void setBouncingSound(bool value) { sound_.bouncing_enabled = value; } + void setPoppingSound(bool value) { sound_.poping_enabled = value; } + void setSound(bool value) { sound_.enabled = value; } + + private: + // --- Estructura para el efecto de rebote --- + struct BounceEffect { + private: + static constexpr int BOUNCE_FRAMES = 10; // Cantidad de elementos del vector de deformación + + // Tablas de valores predefinidos para el efecto de rebote + static constexpr 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}; + + static constexpr 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}; + + // Estado del efecto + bool enabled_ = false; // Si el efecto está activo + Uint8 counter_ = 0; // Contador para el efecto + Uint8 speed_ = 2; // Velocidad del efecto + + // Valores actuales de transformación + float horizontal_zoom_ = 1.0F; // Zoom en anchura + float verical_zoom_ = 1.0F; // Zoom en altura + float x_offset_ = 0.0F; // Desplazamiento X antes de pintar + float y_offset_ = 0.0F; // Desplazamiento Y antes de pintar + + public: + // Constructor por defecto + BounceEffect() = default; + + // Reinicia el efecto a sus valores iniciales + void reset() { + counter_ = 0; + horizontal_zoom_ = 1.0F; + verical_zoom_ = 1.0F; + x_offset_ = 0.0F; + y_offset_ = 0.0F; + } + + // Aplica la deformación visual al sprite + void apply(AnimatedSprite* sprite) const { + if (sprite != nullptr) { + sprite->setHorizontalZoom(horizontal_zoom_); + sprite->setVerticalZoom(verical_zoom_); + } + } + + // Activa el efecto de rebote + void enable(AnimatedSprite* sprite, Size balloon_size) { + // Los globos pequeños no tienen efecto de rebote + if (balloon_size == Size::SMALL) { + return; + } + enabled_ = true; + reset(); + apply(sprite); + } + + // Detiene el efecto de rebote + void disable(AnimatedSprite* sprite) { + enabled_ = false; + reset(); + apply(sprite); + } + + // Actualiza el efecto en cada frame + void update(AnimatedSprite* sprite) { + if (!enabled_) { + return; + } + + // Calcula el índice basado en el contador y velocidad + const int INDEX = counter_ / speed_; + + // Actualiza los valores de zoom desde las tablas predefinidas + horizontal_zoom_ = HORIZONTAL_ZOOM_VALUES.at(INDEX); + verical_zoom_ = VERTICAL_ZOOM_VALUES.at(INDEX); + + // Aplica la deformación al sprite + apply(sprite); + + // Incrementa el contador y verifica si el efecto debe terminar + if (++counter_ / speed_ >= BOUNCE_FRAMES) { + disable(sprite); + } + } + + // Getters para acceso a los valores actuales [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - [[nodiscard]] auto isUsingReversedColor() const -> bool { return use_reversed_colors_; } - [[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); } + [[nodiscard]] auto getHorizontalZoom() const -> float { return horizontal_zoom_; } + [[nodiscard]] auto getVerticalZoom() const -> float { return verical_zoom_; } + [[nodiscard]] auto getXOffset() const -> float { return x_offset_; } + [[nodiscard]] auto getYOffset() const -> float { return y_offset_; } + }; - // --- Setters --- - void setVelY(float vel_y) { vy_ = vel_y; } - void setVelX(float vel_x) { vx_ = vel_x; } - void alterVelX(float percent) { vx_ *= percent; } - void setGameTempo(float tempo) { game_tempo_ = tempo; } - void setInvulnerable(bool value) { invulnerable_ = value; } - void setBouncingSound(bool value) { sound_.bouncing_enabled = value; } - void setPoppingSound(bool value) { sound_.poping_enabled = value; } - void setSound(bool value) { sound_.enabled = value; } + // --- Objetos y punteros --- + std::unique_ptr sprite_; // Sprite del objeto globo - private: - // --- Estructura para el efecto de rebote --- - struct BounceEffect { - private: - static constexpr int BOUNCE_FRAMES = 10; // Cantidad de elementos del vector de deformación + // --- 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 + float creation_counter_; // Temporizador de creación + float creation_counter_ini_; // Valor inicial del temporizador de creación + Uint16 score_; // Puntos al destruir el globo + Type type_; // Tipo de globo + Size size_; // Tamaño de globo + Uint8 menace_; // Amenaza que genera el globo + Uint32 counter_ = 0; // Contador interno + float game_tempo_; // Multiplicador de tempo del juego + float movement_accumulator_ = 0.0F; // Acumulador para movimiento durante creación (deltaTime) + Uint8 power_; // Poder que alberga el globo + SDL_FRect play_area_; // Zona de movimiento del globo + Sound sound_; // Configuración de sonido del globo + BounceEffect bounce_effect_; // Efecto de rebote - // Tablas de valores predefinidos para el efecto de rebote - static constexpr 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}; + // --- Posicionamiento y transformación --- + void shiftColliders(); // Alinea el círculo de colisión con el sprite + void shiftSprite(); // Alinea el sprite en pantalla - static constexpr 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}; + // --- Animación y sonido --- + void setAnimation(); // Establece la animación correspondiente + void playBouncingSound() const; // Reproduce el sonido de rebote + void playPoppingSound() const; // Reproduce el sonido de reventar - // Estado del efecto - bool enabled_ = false; // Si el efecto está activo - Uint8 counter_ = 0; // Contador para el efecto - Uint8 speed_ = 2; // Velocidad del efecto + // --- Movimiento y física --- + void handleHorizontalMovement(float delta_time); // Maneja el movimiento horizontal (time-based) + void handleVerticalMovement(float delta_time); // Maneja el movimiento vertical (time-based) + void applyGravity(float delta_time); // Aplica la gravedad al objeto (time-based) - // Valores actuales de transformación - float horizontal_zoom_ = 1.0F; // Zoom en anchura - float verical_zoom_ = 1.0F; // Zoom en altura - float x_offset_ = 0.0F; // Desplazamiento X antes de pintar - float y_offset_ = 0.0F; // Desplazamiento Y antes de pintar + // --- Rebote --- + void enableBounceEffect(); // Activa el efecto de rebote + void disableBounceEffect(); // Detiene el efecto de rebote + void updateBounceEffect(); // Actualiza el estado del rebote + void handleHorizontalBounce(float min_x, float max_x); // Maneja el rebote horizontal dentro de límites - public: - // Constructor por defecto - BounceEffect() = default; + // --- Colisiones --- + [[nodiscard]] auto isOutOfHorizontalBounds(float min_x, float max_x) const -> bool; // Verifica si está fuera de los límites horizontales + [[nodiscard]] auto shouldCheckTopCollision() const -> bool; // Determina si debe comprobarse la colisión superior + void handleTopCollision(); // Maneja la colisión superior + void handleBottomCollision(); // Maneja la colisión inferior - // Reinicia el efecto a sus valores iniciales - void reset() { - counter_ = 0; - horizontal_zoom_ = 1.0F; - verical_zoom_ = 1.0F; - x_offset_ = 0.0F; - y_offset_ = 0.0F; - } - - // Aplica la deformación visual al sprite - void apply(AnimatedSprite* sprite) const { - if (sprite != nullptr) { - sprite->setHorizontalZoom(horizontal_zoom_); - sprite->setVerticalZoom(verical_zoom_); - } - } - - // Activa el efecto de rebote - void enable(AnimatedSprite* sprite, Size balloon_size) { - // Los globos pequeños no tienen efecto de rebote - if (balloon_size == Size::SMALL) { - return; - } - enabled_ = true; - reset(); - apply(sprite); - } - - // Detiene el efecto de rebote - void disable(AnimatedSprite* sprite) { - enabled_ = false; - reset(); - apply(sprite); - } - - // Actualiza el efecto en cada frame - void update(AnimatedSprite* sprite) { - if (!enabled_) { - return; - } - - // Calcula el índice basado en el contador y velocidad - const int INDEX = counter_ / speed_; - - // Actualiza los valores de zoom desde las tablas predefinidas - horizontal_zoom_ = HORIZONTAL_ZOOM_VALUES.at(INDEX); - verical_zoom_ = VERTICAL_ZOOM_VALUES.at(INDEX); - - // Aplica la deformación al sprite - apply(sprite); - - // Incrementa el contador y verifica si el efecto debe terminar - if (++counter_ / speed_ >= BOUNCE_FRAMES) { - disable(sprite); - } - } - - // Getters para acceso a los valores actuales - [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - [[nodiscard]] auto getHorizontalZoom() const -> float { return horizontal_zoom_; } - [[nodiscard]] auto getVerticalZoom() const -> float { return verical_zoom_; } - [[nodiscard]] auto getXOffset() const -> float { return x_offset_; } - [[nodiscard]] auto getYOffset() const -> float { return y_offset_; } - }; - - // --- 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 - float creation_counter_; // Temporizador de creación - float creation_counter_ini_; // Valor inicial del temporizador de creación - Uint16 score_; // Puntos al destruir el globo - Type type_; // Tipo de globo - Size size_; // Tamaño de globo - Uint8 menace_; // Amenaza que genera el globo - Uint32 counter_ = 0; // Contador interno - float game_tempo_; // Multiplicador de tempo del juego - float movement_accumulator_ = 0.0F; // Acumulador para movimiento durante creación (deltaTime) - Uint8 power_; // Poder que alberga el globo - SDL_FRect play_area_; // Zona de movimiento del globo - Sound sound_; // Configuración de sonido del globo - BounceEffect bounce_effect_; // Efecto de rebote - - // --- Posicionamiento y transformación --- - void shiftColliders(); // Alinea el círculo de colisión con el sprite - void shiftSprite(); // Alinea el sprite en pantalla - - // --- Animación y sonido --- - void setAnimation(); // Establece la animación correspondiente - void playBouncingSound() const; // Reproduce el sonido de rebote - void playPoppingSound() const; // Reproduce el sonido de reventar - - // --- Movimiento y física --- - void handleHorizontalMovement(float delta_time); // Maneja el movimiento horizontal (time-based) - void handleVerticalMovement(float delta_time); // Maneja el movimiento vertical (time-based) - void applyGravity(float delta_time); // Aplica la gravedad al objeto (time-based) - - // --- Rebote --- - void enableBounceEffect(); // Activa el efecto de rebote - void disableBounceEffect(); // Detiene el efecto de rebote - void updateBounceEffect(); // Actualiza el estado del rebote - void handleHorizontalBounce(float min_x, float max_x); // Maneja el rebote horizontal dentro de límites - - // --- Colisiones --- - [[nodiscard]] auto isOutOfHorizontalBounds(float min_x, float max_x) const -> bool; // Verifica si está fuera de los límites horizontales - [[nodiscard]] auto shouldCheckTopCollision() const -> bool; // Determina si debe comprobarse la colisión superior - void handleTopCollision(); // Maneja la colisión superior - void handleBottomCollision(); // Maneja la colisión inferior - - // --- Lógica de estado --- - void updateState(float delta_time); // Actualiza los estados del globo (time-based) + // --- Lógica de estado --- + void updateState(float delta_time); // Actualiza los estados del globo (time-based) }; \ No newline at end of file diff --git a/source/balloon_formations.hpp b/source/balloon_formations.hpp index e2b1e7d..5809b1d 100644 --- a/source/balloon_formations.hpp +++ b/source/balloon_formations.hpp @@ -12,99 +12,99 @@ // --- Clase BalloonFormations --- class BalloonFormations { - public: - // --- Estructuras --- - struct SpawnParams { - float x = 0; // Posición en el eje X donde crear el globo - float y = 0; // Posición en el eje Y donde crear el globo - float vel_x = 0.0F; // Velocidad inicial en el eje X - Balloon::Type type = Balloon::Type::BALLOON; // Tipo de globo - Balloon::Size size = Balloon::Size::SMALL; // Tamaño de globo - float creation_counter = 0.0F; // Temporizador para la creación del globo + public: + // --- Estructuras --- + struct SpawnParams { + float x = 0; // Posición en el eje X donde crear el globo + float y = 0; // Posición en el eje Y donde crear el globo + float vel_x = 0.0F; // Velocidad inicial en el eje X + Balloon::Type type = Balloon::Type::BALLOON; // Tipo de globo + Balloon::Size size = Balloon::Size::SMALL; // Tamaño de globo + float creation_counter = 0.0F; // Temporizador para la creación del globo - // Constructor por defecto - SpawnParams() = default; + // Constructor por defecto + SpawnParams() = default; - // Constructor con parámetros - SpawnParams(float x, float y, float vel_x, Balloon::Type type, Balloon::Size size, float creation_counter) - : x(x), - y(y), - vel_x(vel_x), - type(type), - size(size), - creation_counter(creation_counter) {} - }; + // Constructor con parámetros + SpawnParams(float x, float y, float vel_x, Balloon::Type type, Balloon::Size size, float creation_counter) + : x(x), + y(y), + vel_x(vel_x), + type(type), + size(size), + creation_counter(creation_counter) {} + }; - struct Formation { - std::vector balloons; // Vector con todas las inicializaciones de los globos de la formación + struct Formation { + std::vector balloons; // Vector con todas las inicializaciones de los globos de la formación - // Constructor con parámetros - Formation(const std::vector& spawn_params) - : balloons(spawn_params) {} + // Constructor con parámetros + Formation(const std::vector& spawn_params) + : balloons(spawn_params) {} - // Constructor por defecto - Formation() = default; - }; + // Constructor por defecto + Formation() = default; + }; - // --- Types --- - using Pool = std::vector; // Vector de índices a formaciones + // --- Types --- + using Pool = std::vector; // Vector de índices a formaciones - // --- Constructor y destructor --- - BalloonFormations() { - initFormations(); - initFormationPools(); - } - ~BalloonFormations() = default; + // --- Constructor y destructor --- + BalloonFormations() { + initFormations(); + initFormationPools(); + } + ~BalloonFormations() = default; - // --- Getters --- - auto getPool(int pool_id) -> const Pool& { - return pools_.at(pool_id); - } + // --- Getters --- + auto getPool(int pool_id) -> const Pool& { + return pools_.at(pool_id); + } - auto getFormationFromPool(int pool_id, int formation_index) -> const Formation& { - int formation_id = pools_.at(pool_id).at(formation_index); - return formations_.at(formation_id); - } + auto getFormationFromPool(int pool_id, int formation_index) -> const Formation& { + int formation_id = pools_.at(pool_id).at(formation_index); + return formations_.at(formation_id); + } - [[nodiscard]] auto getFormation(int formation_id) const -> const Formation& { - return formations_.at(formation_id); - } + [[nodiscard]] auto getFormation(int formation_id) const -> const Formation& { + return formations_.at(formation_id); + } - // --- Nuevos getters para información de pools --- - [[nodiscard]] auto getPoolCount() const -> size_t { - return pools_.size(); - } + // --- Nuevos getters para información de pools --- + [[nodiscard]] auto getPoolCount() const -> size_t { + return pools_.size(); + } - [[nodiscard]] auto getPoolSize(int pool_id) const -> size_t { - return pools_.at(pool_id).size(); - } + [[nodiscard]] auto getPoolSize(int pool_id) const -> size_t { + return pools_.at(pool_id).size(); + } - private: - // --- Constantes --- - static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos - static constexpr float CREATION_TIME = 5.0F; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) - static constexpr float DEFAULT_CREATION_TIME = 3.334F; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s) + private: + // --- Constantes --- + static constexpr int BALLOON_SPAWN_HEIGHT = 208; // Altura desde el suelo en la que aparecen los globos + static constexpr float CREATION_TIME = 5.0F; // Tiempo base de creación de los globos en segundos (300 frames ÷ 60fps = 5.0s) + static constexpr float DEFAULT_CREATION_TIME = 3.334F; // Tiempo base de creación de los globos en segundos (200 frames ÷ 60fps = 3.334s) - // --- Variables --- - std::vector formations_; // Vector con todas las formaciones disponibles - std::vector pools_; // Vector de pools, cada pool contiene índices a formaciones + // --- Variables --- + std::vector formations_; // Vector con todas las formaciones disponibles + std::vector pools_; // Vector de pools, cada pool contiene índices a formaciones - // --- Métodos internos --- - void initFormations(); // Inicializa la lista principal de formaciones de globos disponibles - void initFormationPools(); // Carga los pools desde archivo de configuración - auto loadFormationsFromFile(const std::string& filename, const std::map& variables) -> bool; - auto parseBalloonLine(const std::string& line, const std::map& variables) -> std::optional; - auto loadPoolsFromFile(const std::string& filename) -> bool; // Nueva función para cargar pools - auto parsePoolLine(const std::string& line) -> std::optional>>; // Nueva función para parsear líneas de pools - auto evaluateExpression(const std::string& expr, const std::map& variables) -> float; - auto evaluateSimpleExpression(const std::string& expr, const std::map& variables) -> float; - static auto trim(const std::string& str) -> std::string; - void createFloaterVariants(); - void loadDefaultFormations(); - void loadDefaultPools(); // Nueva función para pools por defecto + // --- Métodos internos --- + void initFormations(); // Inicializa la lista principal de formaciones de globos disponibles + void initFormationPools(); // Carga los pools desde archivo de configuración + auto loadFormationsFromFile(const std::string& filename, const std::map& variables) -> bool; + auto parseBalloonLine(const std::string& line, const std::map& variables) -> std::optional; + auto loadPoolsFromFile(const std::string& filename) -> bool; // Nueva función para cargar pools + auto parsePoolLine(const std::string& line) -> std::optional>>; // Nueva función para parsear líneas de pools + auto evaluateExpression(const std::string& expr, const std::map& variables) -> float; + auto evaluateSimpleExpression(const std::string& expr, const std::map& variables) -> float; + static auto trim(const std::string& str) -> std::string; + void createFloaterVariants(); + void loadDefaultFormations(); + void loadDefaultPools(); // Nueva función para pools por defecto // --- Depuración (solo en modo DEBUG) --- #ifdef _DEBUG - void addTestFormation(); + void addTestFormation(); #endif }; \ No newline at end of file diff --git a/source/balloon_manager.hpp b/source/balloon_manager.hpp index 0666054..5387cf5 100644 --- a/source/balloon_manager.hpp +++ b/source/balloon_manager.hpp @@ -22,94 +22,94 @@ using Balloons = std::list>; // --- Clase BalloonManager: gestiona todos los globos del juego --- class BalloonManager { - public: - // --- Constructor y destructor --- - BalloonManager(IStageInfo* stage_info); - ~BalloonManager() = default; + public: + // --- Constructor y destructor --- + BalloonManager(IStageInfo* stage_info); + ~BalloonManager() = default; - // --- Métodos principales --- - void update(float delta_time); // Actualiza el estado de los globos (time-based) - void render(); // Renderiza los globos en pantalla + // --- Métodos principales --- + void update(float delta_time); // Actualiza el estado de los globos (time-based) + void render(); // Renderiza los globos en pantalla - // --- Gestión de globos --- - void freeBalloons(); // Libera globos que ya no sirven + // --- Gestión de globos --- + void freeBalloons(); // Libera globos que ya no sirven - // --- Creación de formaciones enemigas --- - void deployRandomFormation(int stage); // Crea una formación de globos aleatoria - void deployFormation(int formation_id); // Crea una formación específica - void deployFormation(int formation_id, float y); // Crea una formación específica con coordenadas + // --- Creación de formaciones enemigas --- + void deployRandomFormation(int stage); // Crea una formación de globos aleatoria + void deployFormation(int formation_id); // Crea una formación específica + void deployFormation(int formation_id, float y); // Crea una formación específica con coordenadas - // --- Creación de globos --- - auto createBalloon(Balloon::Config config) -> std::shared_ptr; // Crea un nuevo globo - void createChildBalloon(const std::shared_ptr& balloon, const std::string& direction); // Crea un globo a partir de otro - void createPowerBall(); // Crea una PowerBall - void createTwoBigBalloons(); // Crea dos globos grandes + // --- Creación de globos --- + auto createBalloon(Balloon::Config config) -> std::shared_ptr; // Crea un nuevo globo + void createChildBalloon(const std::shared_ptr& balloon, const std::string& direction); // Crea un globo a partir de otro + void createPowerBall(); // Crea una PowerBall + void createTwoBigBalloons(); // Crea dos globos grandes - // --- Control de velocidad y despliegue --- - void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos - void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base - void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos - void updateBalloonDeployCounter(float delta_time); // Actualiza el contador de despliegue (time-based) - auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall - auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla + // --- Control de velocidad y despliegue --- + void setBalloonSpeed(float speed); // Ajusta la velocidad de los globos + void setDefaultBalloonSpeed(float speed) { default_balloon_speed_ = speed; }; // Establece la velocidad base + void resetBalloonSpeed() { setBalloonSpeed(default_balloon_speed_); }; // Restablece la velocidad de los globos + void updateBalloonDeployCounter(float delta_time); // Actualiza el contador de despliegue (time-based) + auto canPowerBallBeCreated() -> bool; // Indica si se puede crear una PowerBall + auto calculateScreenPower() -> int; // Calcula el poder de los globos en pantalla - // --- Manipulación de globos existentes --- - 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 - void startAllBalloons(); // Reactiva el movimiento de los globos + // --- Manipulación de globos existentes --- + 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 + void startAllBalloons(); // Reactiva el movimiento de los globos - // --- Cambios de apariencia --- - void reverseColorsToAllBalloons(); // Invierte los colores de los globos - void normalColorsToAllBalloons(); // Restaura los colores originales + // --- Cambios de apariencia --- + void reverseColorsToAllBalloons(); // Invierte los colores de los globos + void normalColorsToAllBalloons(); // Restaura los colores originales - // --- Configuración de sonido --- - void setSounds(bool value); // Activa o desactiva los sonidos de los globos - void setBouncingSounds(bool value); // Activa o desactiva los sonidos de rebote los globos - void setPoppingSounds(bool value); // Activa o desactiva los sonidos de los globos al explotar + // --- Configuración de sonido --- + void setSounds(bool value); // Activa o desactiva los sonidos de los globos + void setBouncingSounds(bool value); // Activa o desactiva los sonidos de rebote los globos + void setPoppingSounds(bool value); // Activa o desactiva los sonidos de los globos al explotar - // --- Configuración de juego --- - void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego - void setCreationTimeEnabled(bool value) { creation_time_enabled_ = value; }; // Activa o desactiva el tiempo de creación de globos - void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos + // --- Configuración de juego --- + void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego + void setCreationTimeEnabled(bool value) { creation_time_enabled_ = value; }; // Activa o desactiva el tiempo de creación de globos + void enableBalloonDeployment(bool value) { can_deploy_balloons_ = value; }; // Activa o desactiva la generación de globos - // --- Getters --- - auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos - [[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; } - auto getBalloons() -> Balloons& { return balloons_; } - [[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); } + // --- Getters --- + auto getMenace() -> int; // Obtiene el nivel de amenaza generado por los globos + [[nodiscard]] auto getBalloonSpeed() const -> float { return balloon_speed_; } + auto getBalloons() -> Balloons& { return balloons_; } + [[nodiscard]] auto getNumBalloons() const -> int { return balloons_.size(); } - private: - // --- Constantes --- - static constexpr float DEFAULT_BALLOON_DEPLOY_DELAY = 5.0F; // 300 frames = 5 segundos - static constexpr float POWERBALL_DEPLOY_DELAY = 0.167F; // 10 frames = 0.167 segundos - static constexpr float BALLOON_POP_DELAY = 0.333F; // 20 frames = 0.333 segundos + private: + // --- Constantes --- + static constexpr float DEFAULT_BALLOON_DEPLOY_DELAY = 5.0F; // 300 frames = 5 segundos + static constexpr float POWERBALL_DEPLOY_DELAY = 0.167F; // 10 frames = 0.167 segundos + static constexpr float BALLOON_POP_DELAY = 0.333F; // 20 frames = 0.333 segundos - // --- Objetos y punteros --- - Balloons balloons_; // Vector con los globos activos - std::unique_ptr explosions_; // Objeto para gestionar explosiones - std::unique_ptr balloon_formations_; // Objeto para manejar formaciones enemigas - std::vector> balloon_textures_; // Texturas de los globos - std::vector> explosions_textures_; // Texturas de explosiones - std::vector> balloon_animations_; // Animaciones de los globos - std::vector> explosions_animations_; // Animaciones de las explosiones - IStageInfo* stage_info_; // Informacion de la pantalla actual + // --- Objetos y punteros --- + Balloons balloons_; // Vector con los globos activos + std::unique_ptr explosions_; // Objeto para gestionar explosiones + std::unique_ptr balloon_formations_; // Objeto para manejar formaciones enemigas + std::vector> balloon_textures_; // Texturas de los globos + std::vector> explosions_textures_; // Texturas de explosiones + std::vector> balloon_animations_; // Animaciones de los globos + std::vector> explosions_animations_; // Animaciones de las explosiones + IStageInfo* stage_info_; // Informacion de la pantalla actual - // --- Variables de estado --- - SDL_FRect play_area_ = param.game.play_area.rect; - float balloon_speed_ = Balloon::GAME_TEMPO.at(0); - float default_balloon_speed_ = Balloon::GAME_TEMPO.at(0); - float balloon_deploy_counter_ = 0; - int power_ball_counter_ = 0; - int last_balloon_deploy_ = 0; - bool power_ball_enabled_ = false; - bool creation_time_enabled_ = true; - bool can_deploy_balloons_ = true; - 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 --- + SDL_FRect play_area_ = param.game.play_area.rect; + float balloon_speed_ = Balloon::GAME_TEMPO.at(0); + float default_balloon_speed_ = Balloon::GAME_TEMPO.at(0); + float balloon_deploy_counter_ = 0; + int power_ball_counter_ = 0; + int last_balloon_deploy_ = 0; + bool power_ball_enabled_ = false; + bool creation_time_enabled_ = true; + bool can_deploy_balloons_ = true; + 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 init(); + // --- Métodos internos --- + void init(); }; diff --git a/source/bullet.hpp b/source/bullet.hpp index 8034de1..9f49504 100644 --- a/source/bullet.hpp +++ b/source/bullet.hpp @@ -10,67 +10,67 @@ // --- Clase Bullet: representa una bala del jugador --- class Bullet { - public: - // --- Constantes --- - static constexpr float WIDTH = 12.0F; // Anchura de la bala - static constexpr float HEIGHT = 12.0F; // Altura de la bala + public: + // --- Constantes --- + static constexpr float WIDTH = 12.0F; // Anchura de la bala + static constexpr float HEIGHT = 12.0F; // Altura de la bala - // --- Enums --- - enum class Type : Uint8 { - UP, // Bala hacia arriba - LEFT, // Bala hacia la izquierda - RIGHT, // Bala hacia la derecha - NONE // Sin bala - }; + // --- Enums --- + enum class Type : Uint8 { + UP, // Bala hacia arriba + LEFT, // Bala hacia la izquierda + RIGHT, // Bala hacia la derecha + NONE // Sin bala + }; - enum class MoveStatus : Uint8 { - OK = 0, // Movimiento normal - OUT = 1 // Fuera de los límites - }; + enum class MoveStatus : Uint8 { + OK = 0, // Movimiento normal + OUT = 1 // Fuera de los límites + }; - enum class Color : Uint8 { - YELLOW, - GREEN, - RED, - PURPLE - }; + enum class Color : Uint8 { + YELLOW, + GREEN, + RED, + PURPLE + }; - // --- Constructor y destructor --- - Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal - ~Bullet() = default; // Destructor + // --- Constructor y destructor --- + Bullet(float x, float y, Type type, Color color, int owner); // Constructor principal + ~Bullet() = default; // Destructor - // --- Métodos principales --- - void render(); // Dibuja la bala en pantalla - auto update(float delta_time) -> MoveStatus; // Actualiza el estado del objeto (time-based) - void disable(); // Desactiva la bala + // --- Métodos principales --- + void render(); // Dibuja la bala en pantalla + auto update(float delta_time) -> MoveStatus; // Actualiza el estado del objeto (time-based) + void disable(); // Desactiva la bala - // --- Getters --- - [[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa - [[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño - auto getCollider() -> Circle&; // Devuelve el círculo de colisión + // --- Getters --- + [[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa + [[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño + auto getCollider() -> Circle&; // Devuelve el círculo de colisión - private: - // --- Constantes --- - static constexpr float VEL_Y = -180.0F; // Velocidad vertical (pixels/segundo) - era -0.18F pixels/ms - static constexpr float VEL_X_LEFT = -120.0F; // Velocidad izquierda (pixels/segundo) - era -0.12F pixels/ms - static constexpr float VEL_X_RIGHT = 120.0F; // Velocidad derecha (pixels/segundo) - era 0.12F pixels/ms - static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central + private: + // --- Constantes --- + static constexpr float VEL_Y = -180.0F; // Velocidad vertical (pixels/segundo) - era -0.18F pixels/ms + static constexpr float VEL_X_LEFT = -120.0F; // Velocidad izquierda (pixels/segundo) - era -0.12F pixels/ms + static constexpr float VEL_X_RIGHT = 120.0F; // Velocidad derecha (pixels/segundo) - era 0.12F pixels/ms + static constexpr float VEL_X_CENTER = 0.0F; // Velocidad central - // --- Objetos y punteros --- - std::unique_ptr sprite_; // Sprite con los gráficos + // --- Objetos y punteros --- + std::unique_ptr sprite_; // Sprite con los gráficos - // --- Variables de estado --- - Circle collider_; // Círculo de colisión - Type type_; // Tipo de bala - int owner_; // Identificador del jugador - float pos_x_; // Posición en el eje X - float pos_y_; // Posición en el eje Y - float vel_x_; // Velocidad en el eje X + // --- Variables de estado --- + Circle collider_; // Círculo de colisión + Type type_; // Tipo de bala + int owner_; // Identificador del jugador + float pos_x_; // Posición en el eje X + float pos_y_; // Posición en el eje Y + float vel_x_; // Velocidad en el eje X - // --- Métodos internos --- - void shiftColliders(); // Ajusta el círculo de colisión - void shiftSprite(); // Ajusta el sprite - auto move(float delta_time) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) - static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala - static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación + // --- Métodos internos --- + void shiftColliders(); // Ajusta el círculo de colisión + void shiftSprite(); // Ajusta el sprite + auto move(float delta_time) -> MoveStatus; // Mueve la bala y devuelve su estado (time-based) + static auto calculateVelocity(Type type) -> float; // Calcula la velocidad horizontal de la bala + static auto buildAnimationString(Type type, Color color) -> std::string; // Construye el string de animación }; diff --git a/source/bullet_manager.hpp b/source/bullet_manager.hpp index f3f7539..156ea95 100644 --- a/source/bullet_manager.hpp +++ b/source/bullet_manager.hpp @@ -27,50 +27,50 @@ using Bullets = std::list>; // La clase utiliza un sistema de callbacks para manejar las colisiones, // permitiendo que la lógica específica del juego permanezca en Game. class BulletManager { - public: - // --- Types para callbacks --- - using CollisionCallback = std::function&)>; - using OutOfBoundsCallback = std::function&)>; + public: + // --- Types para callbacks --- + using CollisionCallback = std::function&)>; + using OutOfBoundsCallback = std::function&)>; - // --- Constructor y destructor --- - BulletManager(); - ~BulletManager() = default; + // --- Constructor y destructor --- + BulletManager(); + ~BulletManager() = default; - // --- Métodos principales --- - void update(float delta_time); // Actualiza el estado de las balas (time-based) - void render(); // Renderiza las balas en pantalla + // --- Métodos principales --- + void update(float delta_time); // Actualiza el estado de las balas (time-based) + void render(); // Renderiza las balas en pantalla - // --- Gestión de balas --- - void createBullet(int x, int y, Bullet::Type type, Bullet::Color color, int owner); // Crea una nueva bala - void freeBullets(); // Libera balas que ya no sirven - void clearAllBullets(); // Elimina todas las balas + // --- Gestión de balas --- + void createBullet(int x, int y, Bullet::Type type, Bullet::Color color, int owner); // Crea una nueva bala + void freeBullets(); // Libera balas que ya no sirven + void clearAllBullets(); // Elimina todas las balas - // --- Detección de colisiones --- - void checkCollisions(); // Verifica colisiones de todas las balas - void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe - void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos - void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites + // --- Detección de colisiones --- + void checkCollisions(); // Verifica colisiones de todas las balas + void setTabeCollisionCallback(CollisionCallback callback); // Establece callback para colisión con Tabe + void setBalloonCollisionCallback(CollisionCallback callback); // Establece callback para colisión con globos + void setOutOfBoundsCallback(OutOfBoundsCallback callback); // Establece callback para balas fuera de límites - // --- Configuración --- - void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego + // --- Configuración --- + void setPlayArea(SDL_FRect play_area) { play_area_ = play_area; }; // Define el área de juego - // --- Getters --- - auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas - [[nodiscard]] auto getNumBullets() const -> int { return bullets_.size(); } // Obtiene el número de balas activas + // --- Getters --- + auto getBullets() -> Bullets& { return bullets_; } // Obtiene referencia al vector de balas + [[nodiscard]] auto getNumBullets() const -> int { return bullets_.size(); } // Obtiene el número de balas activas - private: - // --- Objetos y punteros --- - Bullets bullets_; // Vector con las balas activas + private: + // --- Objetos y punteros --- + Bullets bullets_; // Vector con las balas activas - // --- Variables de configuración --- - SDL_FRect play_area_; // Área de juego para límites + // --- Variables de configuración --- + SDL_FRect play_area_; // Área de juego para límites - // --- Callbacks para colisiones --- - CollisionCallback tabe_collision_callback_; // Callback para colisión con Tabe - CollisionCallback balloon_collision_callback_; // Callback para colisión con globos - OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites + // --- Callbacks para colisiones --- + CollisionCallback tabe_collision_callback_; // Callback para colisión con Tabe + CollisionCallback balloon_collision_callback_; // Callback para colisión con globos + OutOfBoundsCallback out_of_bounds_callback_; // Callback para balas fuera de límites - // --- Métodos internos --- - void processBulletUpdate(const std::shared_ptr& bullet, float delta_time); // Procesa actualización individual - [[nodiscard]] auto isBulletOutOfBounds(const std::shared_ptr& bullet) const -> bool; // Verifica si la bala está fuera de límites + // --- Métodos internos --- + void processBulletUpdate(const std::shared_ptr& bullet, float delta_time); // Procesa actualización individual + [[nodiscard]] auto isBulletOutOfBounds(const std::shared_ptr& bullet) const -> bool; // Verifica si la bala está fuera de límites }; \ No newline at end of file diff --git a/source/color.cpp b/source/color.cpp index f0e2c40..645aa06 100644 --- a/source/color.cpp +++ b/source/color.cpp @@ -116,71 +116,71 @@ constexpr auto Color::HSV_TO_RGB(HSV hsv) -> Color { // Implementaciones del namespace Colors namespace Colors { -// Obtiene un color del vector de colores imitando al Coche Fantástico -auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color { - int cycle_length = (colors.size() * 2) - 2; - size_t n = counter % cycle_length; + // Obtiene un color del vector de colores imitando al Coche Fantástico + auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color { + int cycle_length = (colors.size() * 2) - 2; + size_t n = counter % cycle_length; - size_t index; - if (n < colors.size()) { - index = n; // Avanza: 0,1,2,3 - } else { - index = 2 * (colors.size() - 1) - n; // Retrocede: 2,1 - } - - return colors[index]; -} - -auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle { - Cycle result{}; - HSV base_hsv = Color::RGB_TO_HSV(base); - - for (size_t i = 0; i < CYCLE_SIZE; ++i) { - float t = static_cast(i) / (CYCLE_SIZE - 1); // 0 → 1 - float hue_shift = 0.0F; - float sat_shift = 0.0F; - float val_shift = 0.0F; - - switch (style) { - case ColorCycleStyle::SUBTLE_PULSE: - // Solo brillo suave - val_shift = 0.07F * sinf(t * M_PI); - break; - - case ColorCycleStyle::HUE_WAVE: - // Oscilación leve de tono - hue_shift = 15.0F * (t - 0.5F) * 2.0F; - val_shift = 0.05F * sinf(t * M_PI); - break; - - case ColorCycleStyle::VIBRANT: - // Cambios fuertes en tono y brillo - hue_shift = 35.0F * sinf(t * M_PI); - val_shift = 0.2F * sinf(t * M_PI); - sat_shift = -0.2F * sinf(t * M_PI); - break; - - case ColorCycleStyle::DARKEN_GLOW: - // Se oscurece al centro - val_shift = -0.15F * sinf(t * M_PI); - break; - - case ColorCycleStyle::LIGHT_FLASH: - // Se ilumina al centro - val_shift = 0.25F * sinf(t * M_PI); - break; + size_t index; + if (n < colors.size()) { + index = n; // Avanza: 0,1,2,3 + } else { + index = 2 * (colors.size() - 1) - n; // Retrocede: 2,1 } - HSV adjusted = { - .h = fmodf(base_hsv.h + hue_shift + 360.0F, 360.0F), - .s = fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)), - .v = fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))}; - - Color c = Color::HSV_TO_RGB(adjusted); - result[i] = c; - result[(2 * CYCLE_SIZE) - 1 - i] = c; // espejo + return colors[index]; } - return result; -} + auto generateMirroredCycle(Color base, ColorCycleStyle style) -> Cycle { + Cycle result{}; + HSV base_hsv = Color::RGB_TO_HSV(base); + + for (size_t i = 0; i < CYCLE_SIZE; ++i) { + float t = static_cast(i) / (CYCLE_SIZE - 1); // 0 → 1 + float hue_shift = 0.0F; + float sat_shift = 0.0F; + float val_shift = 0.0F; + + switch (style) { + case ColorCycleStyle::SUBTLE_PULSE: + // Solo brillo suave + val_shift = 0.07F * sinf(t * M_PI); + break; + + case ColorCycleStyle::HUE_WAVE: + // Oscilación leve de tono + hue_shift = 15.0F * (t - 0.5F) * 2.0F; + val_shift = 0.05F * sinf(t * M_PI); + break; + + case ColorCycleStyle::VIBRANT: + // Cambios fuertes en tono y brillo + hue_shift = 35.0F * sinf(t * M_PI); + val_shift = 0.2F * sinf(t * M_PI); + sat_shift = -0.2F * sinf(t * M_PI); + break; + + case ColorCycleStyle::DARKEN_GLOW: + // Se oscurece al centro + val_shift = -0.15F * sinf(t * M_PI); + break; + + case ColorCycleStyle::LIGHT_FLASH: + // Se ilumina al centro + val_shift = 0.25F * sinf(t * M_PI); + break; + } + + HSV adjusted = { + .h = fmodf(base_hsv.h + hue_shift + 360.0F, 360.0F), + .s = fminf(1.0F, fmaxf(0.0F, base_hsv.s + sat_shift)), + .v = fminf(1.0F, fmaxf(0.0F, base_hsv.v + val_shift))}; + + Color c = Color::HSV_TO_RGB(adjusted); + result[i] = c; + result[(2 * CYCLE_SIZE) - 1 - i] = c; // espejo + } + + return result; + } } // namespace Colors \ No newline at end of file diff --git a/source/color.hpp b/source/color.hpp index 5baecf1..f14ea56 100644 --- a/source/color.hpp +++ b/source/color.hpp @@ -11,119 +11,119 @@ // --- Estructura HSV: define un color en formato HSV --- struct HSV { - float h; // Matiz (Hue) - float s; // Saturación (Saturation) - float v; // Valor (Value) + float h; // Matiz (Hue) + float s; // Saturación (Saturation) + float v; // Valor (Value) }; // --- Estructura Color: define un color RGBA --- struct Color { - private: - static constexpr int DEFAULT_LIGHTEN_AMOUNT = 50; - static constexpr int DEFAULT_DARKEN_AMOUNT = 50; - static constexpr int DEFAULT_APPROACH_STEP = 1; - static constexpr size_t HEX_RGB_LENGTH = 6; - static constexpr size_t HEX_RGBA_LENGTH = 8; - static constexpr int HEX_BASE = 16; - static constexpr size_t HEX_COMPONENT_LENGTH = 2; + private: + static constexpr int DEFAULT_LIGHTEN_AMOUNT = 50; + static constexpr int DEFAULT_DARKEN_AMOUNT = 50; + static constexpr int DEFAULT_APPROACH_STEP = 1; + static constexpr size_t HEX_RGB_LENGTH = 6; + static constexpr size_t HEX_RGBA_LENGTH = 8; + static constexpr int HEX_BASE = 16; + static constexpr size_t HEX_COMPONENT_LENGTH = 2; - public: - static constexpr Uint8 MAX_COLOR_VALUE = 255; - static constexpr Uint8 MIN_COLOR_VALUE = 0; - static constexpr Uint8 DEFAULT_ALPHA = 255; - static constexpr Uint8 MAX_ALPHA_VALUE = 255; - static constexpr Uint8 MIN_ALPHA_VALUE = 0; + public: + static constexpr Uint8 MAX_COLOR_VALUE = 255; + static constexpr Uint8 MIN_COLOR_VALUE = 0; + static constexpr Uint8 DEFAULT_ALPHA = 255; + static constexpr Uint8 MAX_ALPHA_VALUE = 255; + static constexpr Uint8 MIN_ALPHA_VALUE = 0; - Uint8 r, g, b, a; + Uint8 r, g, b, a; - constexpr Color() - : r(MIN_COLOR_VALUE), - g(MIN_COLOR_VALUE), - b(MIN_COLOR_VALUE), - a(DEFAULT_ALPHA) {} + constexpr Color() + : r(MIN_COLOR_VALUE), + g(MIN_COLOR_VALUE), + b(MIN_COLOR_VALUE), + a(DEFAULT_ALPHA) {} - explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = DEFAULT_ALPHA) - : r(red), - g(green), - b(blue), - a(alpha) {} + explicit constexpr Color(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha = DEFAULT_ALPHA) + : r(red), + g(green), + b(blue), + a(alpha) {} - [[nodiscard]] constexpr auto INVERSE() const -> Color { - return Color(MAX_COLOR_VALUE - r, MAX_COLOR_VALUE - g, MAX_COLOR_VALUE - b, a); - } + [[nodiscard]] constexpr auto INVERSE() const -> Color { + return Color(MAX_COLOR_VALUE - r, MAX_COLOR_VALUE - g, MAX_COLOR_VALUE - b, a); + } - [[nodiscard]] constexpr auto LIGHTEN(int amount = DEFAULT_LIGHTEN_AMOUNT) const -> Color { - return Color( - std::min(static_cast(MAX_COLOR_VALUE), r + amount), - std::min(static_cast(MAX_COLOR_VALUE), g + amount), - std::min(static_cast(MAX_COLOR_VALUE), b + amount), - a); - } + [[nodiscard]] constexpr auto LIGHTEN(int amount = DEFAULT_LIGHTEN_AMOUNT) const -> Color { + return Color( + std::min(static_cast(MAX_COLOR_VALUE), r + amount), + std::min(static_cast(MAX_COLOR_VALUE), g + amount), + std::min(static_cast(MAX_COLOR_VALUE), b + amount), + a); + } - [[nodiscard]] constexpr auto DARKEN(int amount = DEFAULT_DARKEN_AMOUNT) const -> Color { - return Color( - std::max(static_cast(MIN_COLOR_VALUE), r - amount), - std::max(static_cast(MIN_COLOR_VALUE), g - amount), - std::max(static_cast(MIN_COLOR_VALUE), b - amount), - a); - } + [[nodiscard]] constexpr auto DARKEN(int amount = DEFAULT_DARKEN_AMOUNT) const -> Color { + return Color( + std::max(static_cast(MIN_COLOR_VALUE), r - amount), + std::max(static_cast(MIN_COLOR_VALUE), g - amount), + std::max(static_cast(MIN_COLOR_VALUE), b - amount), + a); + } - // Método estático para crear Color desde string hexadecimal - static auto fromHex(const std::string& hex_str) -> Color; + // Método estático para crear Color desde string hexadecimal + static auto fromHex(const std::string& hex_str) -> Color; - // Conversiones de formato de color - [[nodiscard]] constexpr static auto RGB_TO_HSV(Color color) -> HSV; - [[nodiscard]] constexpr static auto HSV_TO_RGB(HSV hsv) -> Color; + // Conversiones de formato de color + [[nodiscard]] constexpr static auto RGB_TO_HSV(Color color) -> HSV; + [[nodiscard]] constexpr static auto HSV_TO_RGB(HSV hsv) -> Color; - [[nodiscard]] constexpr auto IS_EQUAL_TO(const Color& other) const -> bool { - return r == other.r && g == other.g && b == other.b && a == other.a; - } + [[nodiscard]] constexpr auto IS_EQUAL_TO(const Color& other) const -> bool { + return r == other.r && g == other.g && b == other.b && a == other.a; + } - [[nodiscard]] constexpr auto APPROACH_TO(const Color& target, int step = DEFAULT_APPROACH_STEP) const -> Color { - auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 { - if (std::abs(current - target_val) <= step) { - return target_val; - } - return (current < target_val) ? current + step : current - step; - }; + [[nodiscard]] constexpr auto APPROACH_TO(const Color& target, int step = DEFAULT_APPROACH_STEP) const -> Color { + auto approach_component = [step](Uint8 current, Uint8 target_val) -> Uint8 { + if (std::abs(current - target_val) <= step) { + return target_val; + } + return (current < target_val) ? current + step : current - step; + }; - Uint8 new_r = approach_component(r, target.r); - Uint8 new_g = approach_component(g, target.g); - Uint8 new_b = approach_component(b, target.b); - Uint8 new_a = approach_component(a, target.a); + Uint8 new_r = approach_component(r, target.r); + Uint8 new_g = approach_component(g, target.g); + Uint8 new_b = approach_component(b, target.b); + Uint8 new_a = approach_component(a, target.a); - return Color(new_r, new_g, new_b, new_a); - } + return Color(new_r, new_g, new_b, new_a); + } - // Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target) - [[nodiscard]] constexpr auto LERP(const Color& target, float t) const -> Color { - // Asegurar que t esté en el rango [0.0, 1.0] - t = std::clamp(t, 0.0F, 1.0F); + // Interpolación lineal hacia otro color (t=0.0: this, t=1.0: target) + [[nodiscard]] constexpr auto LERP(const Color& target, float t) const -> Color { + // Asegurar que t esté en el rango [0.0, 1.0] + t = std::clamp(t, 0.0F, 1.0F); - // Interpolación lineal para cada componente - auto lerp_component = [t](Uint8 start, Uint8 end) -> Uint8 { - return static_cast(start + ((end - start) * t)); - }; + // Interpolación lineal para cada componente + auto lerp_component = [t](Uint8 start, Uint8 end) -> Uint8 { + return static_cast(start + ((end - start) * t)); + }; - return Color( - lerp_component(r, target.r), - lerp_component(g, target.g), - lerp_component(b, target.b), - lerp_component(a, target.a)); - } + return Color( + lerp_component(r, target.r), + lerp_component(g, target.g), + lerp_component(b, target.b), + lerp_component(a, target.a)); + } - // Sobrecarga para aceptar componentes RGBA directamente - [[nodiscard]] constexpr auto LERP(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, float t) const -> Color { - return LERP(Color(red, green, blue, alpha), t); - } + // Sobrecarga para aceptar componentes RGBA directamente + [[nodiscard]] constexpr auto LERP(Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, float t) const -> Color { + return LERP(Color(red, green, blue, alpha), t); + } - // Convierte el color a un entero de 32 bits en formato RGBA - [[nodiscard]] constexpr auto TO_UINT32() const -> Uint32 { - return (static_cast(r) << 24) | - (static_cast(g) << 16) | - (static_cast(b) << 8) | - static_cast(a); - } + // Convierte el color a un entero de 32 bits en formato RGBA + [[nodiscard]] constexpr auto TO_UINT32() const -> Uint32 { + return (static_cast(r) << 24) | + (static_cast(g) << 16) | + (static_cast(b) << 8) | + static_cast(a); + } }; // --- Enum ColorCycleStyle: define estilos de ciclo de color --- @@ -137,25 +137,25 @@ enum class ColorCycleStyle { // --- Namespace Colors: constantes y utilidades de color --- namespace Colors { -// --- Constantes --- -constexpr size_t CYCLE_SIZE = 6; // Mitad del ciclo espejado + // --- Constantes --- + constexpr size_t CYCLE_SIZE = 6; // Mitad del ciclo espejado -// --- Alias --- -using Cycle = std::array; + // --- Alias --- + using Cycle = std::array; -// --- Colores predefinidos --- -constexpr Color NO_COLOR_MOD = Color(0XFF, 0XFF, 0XFF); -constexpr Color SHADOW_TEXT = Color(0X43, 0X43, 0X4F); -constexpr Color TITLE_SHADOW_TEXT = Color(0x14, 0x87, 0xc4); -constexpr Color ORANGE_TEXT = Color(0XFF, 0X7A, 0X00); + // --- Colores predefinidos --- + constexpr Color NO_COLOR_MOD = Color(0XFF, 0XFF, 0XFF); + constexpr Color SHADOW_TEXT = Color(0X43, 0X43, 0X4F); + constexpr Color TITLE_SHADOW_TEXT = Color(0x14, 0x87, 0xc4); + constexpr Color ORANGE_TEXT = Color(0XFF, 0X7A, 0X00); -constexpr Color FLASH = Color(0XFF, 0XFF, 0XFF); + constexpr Color FLASH = Color(0XFF, 0XFF, 0XFF); -constexpr Color BLUE_SKY = Color(0X02, 0X88, 0XD1); -constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97); -constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B); + constexpr Color BLUE_SKY = Color(0X02, 0X88, 0XD1); + constexpr Color PINK_SKY = Color(0XFF, 0X6B, 0X97); + constexpr Color GREEN_SKY = Color(0X00, 0X79, 0X6B); -// --- Funciones --- -auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color; -auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle; + // --- Funciones --- + auto getColorLikeKnightRider(const std::vector& colors, int counter) -> Color; + auto generateMirroredCycle(Color base, ColorCycleStyle style = ColorCycleStyle::SUBTLE_PULSE) -> Cycle; } // namespace Colors \ No newline at end of file diff --git a/source/cooldown.hpp b/source/cooldown.hpp index 278c08e..46eb8f2 100644 --- a/source/cooldown.hpp +++ b/source/cooldown.hpp @@ -3,9 +3,10 @@ #include // Para std::max class Cooldown { -public: + public: Cooldown(float first_delay_s = 0.0F, float repeat_delay_s = 0.0F) - : first_delay_s_(first_delay_s), repeat_delay_s_(repeat_delay_s) {} + : first_delay_s_(first_delay_s), + repeat_delay_s_(repeat_delay_s) {} // Llamar cada frame con delta en segundos (float) void update(float delta_s) { @@ -40,7 +41,7 @@ public: // Fuerza un valor en segundos (útil para tests o resets) void forceSet(float seconds) { remaining_s_ = seconds > 0.0F ? seconds : 0.0F; } -private: + private: float first_delay_s_; float repeat_delay_s_; float remaining_s_{0.0F}; diff --git a/source/defaults.hpp b/source/defaults.hpp index 3db5c67..37af09c 100644 --- a/source/defaults.hpp +++ b/source/defaults.hpp @@ -11,232 +11,232 @@ // --- Namespace GameDefaults: configuración centralizada con valores por defecto del juego --- namespace GameDefaults { -// --- GAME --- -namespace Game { -constexpr float WIDTH = 320.0F; -constexpr float HEIGHT = 256.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; -constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0 + // --- GAME --- + namespace Game { + constexpr float WIDTH = 320.0F; + constexpr float HEIGHT = 256.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; + constexpr const char* ITEM_TEXT_OUTLINE_COLOR = "FFFFFF00"; // 255, 255, 255, 0 -// 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; -} // namespace Game + // 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; + } // 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 int RANDOM_SQUARES_DURATION_MS = 1; -constexpr int POST_DURATION_MS = 80; -constexpr float VENETIAN_SIZE = 12.0F; -} // namespace Fade + // --- FADE --- + namespace Fade { + constexpr const char* COLOR = "1F2B30"; + constexpr float NUM_SQUARES_WIDTH = 160.0F; + constexpr float NUM_SQUARES_HEIGHT = 128.0F; + constexpr int RANDOM_SQUARES_DURATION_MS = 1; + constexpr int POST_DURATION_MS = 80; + 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 bool SEPARATOR_AUTOCOLOR = true; -constexpr const char* SEPARATOR_COLOR = "0D1A2B"; -constexpr const char* EASY_COLOR = "4B692F"; -constexpr const char* NORMAL_COLOR = "2E3F47"; -constexpr const char* HARD_COLOR = "76428A"; -constexpr bool TEXT_AUTOCOLOR = true; -constexpr const char* TEXT_COLOR1 = "FFFFFF"; -constexpr const char* TEXT_COLOR2 = "FFFFFF"; -constexpr int SKIP_COUNTDOWN_VALUE = 8; -} // namespace Scoreboard + // --- 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 bool SEPARATOR_AUTOCOLOR = true; + constexpr const char* SEPARATOR_COLOR = "0D1A2B"; + constexpr const char* EASY_COLOR = "4B692F"; + constexpr const char* NORMAL_COLOR = "2E3F47"; + constexpr const char* HARD_COLOR = "76428A"; + constexpr bool TEXT_AUTOCOLOR = true; + constexpr const char* TEXT_COLOR1 = "FFFFFF"; + constexpr const char* TEXT_COLOR2 = "FFFFFF"; + constexpr int SKIP_COUNTDOWN_VALUE = 8; + } // namespace Scoreboard -// --- TITLE --- -namespace Title { -constexpr int PRESS_START_POSITION = 180; -constexpr float DURATION_S = 14.0F; -constexpr int ARCADE_EDITION_POSITION = 123; -constexpr int TITLE_C_C_POSITION = 80; -constexpr const char* BG_COLOR = "41526F"; -} // namespace Title + // --- TITLE --- + namespace Title { + constexpr int PRESS_START_POSITION = 180; + constexpr float DURATION_S = 14.0F; + constexpr int ARCADE_EDITION_POSITION = 123; + constexpr int TITLE_C_C_POSITION = 80; + constexpr const char* BG_COLOR = "41526F"; + } // namespace Title -// --- BACKGROUND --- -namespace Background { -constexpr const char* ATTENUATE_COLOR = "FFFFFF00"; -} + // --- BACKGROUND --- + namespace Background { + constexpr const char* ATTENUATE_COLOR = "FFFFFF00"; + } -// --- BALLOONS --- -namespace Balloon { -// Configuración de física para cada nivel de globo -struct BalloonSettings { - float vel; - float grav; - constexpr BalloonSettings(float v, float g) - : vel(v), - grav(g) {} -}; + // --- BALLOONS --- + namespace Balloon { + // Configuración de física para cada nivel de globo + struct BalloonSettings { + float vel; + float grav; + constexpr BalloonSettings(float v, float g) + : vel(v), + grav(g) {} + }; -// Valores para deltaTime en segundos: vel en pixels/s, grav en pixels/s² (aceleración) -constexpr std::array SETTINGS = {{ - BalloonSettings(165.0F, 320.0F), // Globo 0: vel=165 pixels/s, grav=320 pixels/s² - BalloonSettings(222.0F, 360.0F), // Globo 1: vel=222 pixels/s, grav=360 pixels/s² - BalloonSettings(282.0F, 360.0F), // Globo 2: vel=282 pixels/s, grav=360 pixels/s² - BalloonSettings(327.0F, 360.0F) // Globo 3: vel=327 pixels/s, grav=360 pixels/s² -}}; + // Valores para deltaTime en segundos: vel en pixels/s, grav en pixels/s² (aceleración) + constexpr std::array SETTINGS = {{ + BalloonSettings(165.0F, 320.0F), // Globo 0: vel=165 pixels/s, grav=320 pixels/s² + BalloonSettings(222.0F, 360.0F), // Globo 1: vel=222 pixels/s, grav=360 pixels/s² + BalloonSettings(282.0F, 360.0F), // Globo 2: vel=282 pixels/s, grav=360 pixels/s² + BalloonSettings(327.0F, 360.0F) // Globo 3: vel=327 pixels/s, grav=360 pixels/s² + }}; -constexpr std::array COLORS = { - "blue", - "orange", - "red", - "green"}; + constexpr std::array COLORS = { + "blue", + "orange", + "red", + "green"}; -constexpr bool BOUNCING_SOUND = false; -} // namespace Balloon + constexpr bool BOUNCING_SOUND = false; + } // namespace Balloon -// --- NOTIFICATION --- -namespace Notification { -constexpr Notifier::Position POS_V = Notifier::Position::TOP; -constexpr Notifier::Position POS_H = Notifier::Position::LEFT; -constexpr bool SOUND = false; -constexpr const char* COLOR = "303030"; -} // namespace Notification + // --- NOTIFICATION --- + namespace Notification { + constexpr Notifier::Position POS_V = Notifier::Position::TOP; + constexpr Notifier::Position POS_H = Notifier::Position::LEFT; + constexpr bool SOUND = false; + constexpr const char* COLOR = "303030"; + } // namespace Notification -// --- SERVICE MENU --- -namespace ServiceMenu { -constexpr const char* TITLE_COLOR = "99FF62"; -constexpr const char* TEXT_COLOR = "FFFFFF"; -constexpr const char* SELECTED_COLOR = "FFDC44"; -constexpr const char* BG_COLOR = "000F00F5"; -constexpr bool DROP_SHADOW = false; + // --- SERVICE MENU --- + namespace ServiceMenu { + constexpr const char* TITLE_COLOR = "99FF62"; + constexpr const char* TEXT_COLOR = "FFFFFF"; + constexpr const char* SELECTED_COLOR = "FFDC44"; + constexpr const char* BG_COLOR = "000F00F5"; + constexpr bool DROP_SHADOW = false; -// WindowMessage defaults -namespace WindowMessage { -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; -} // namespace WindowMessage -} // namespace ServiceMenu + // WindowMessage defaults + namespace WindowMessage { + 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; + } // namespace WindowMessage + } // namespace ServiceMenu -// --- INTRO --- -namespace Intro { -constexpr const char* BG_COLOR = "4664BD"; -constexpr const char* CARD_COLOR = "CBDBFC"; -constexpr const char* SHADOW_COLOR = "00000080"; -constexpr int TEXT_DISTANCE_FROM_BOTTOM = 48; -} // namespace Intro + // --- INTRO --- + namespace Intro { + constexpr const char* BG_COLOR = "4664BD"; + constexpr const char* CARD_COLOR = "CBDBFC"; + constexpr const char* SHADOW_COLOR = "00000080"; + constexpr int TEXT_DISTANCE_FROM_BOTTOM = 48; + } // namespace Intro -// --- DEBUG --- -namespace Debug { -constexpr const char* COLOR = "00FFFF"; -} + // --- DEBUG --- + namespace Debug { + constexpr const char* COLOR = "00FFFF"; + } -// --- RESOURCE --- -namespace Resource { -constexpr const char* COLOR = "FFFFFF"; -} + // --- RESOURCE --- + namespace Resource { + constexpr const char* COLOR = "FFFFFF"; + } -// --- TABE --- -namespace Tabe { -constexpr float MIN_SPAWN_TIME = 2.0F; -constexpr float MAX_SPAWN_TIME = 3.0F; -} // namespace Tabe + // --- TABE --- + namespace Tabe { + constexpr float MIN_SPAWN_TIME = 2.0F; + constexpr float MAX_SPAWN_TIME = 3.0F; + } // namespace Tabe -// --- PLAYER --- -namespace Player { -namespace DefaultShirt { -// Player 0 (Jugador 1) -constexpr const char* PLAYER0_DARKEST = "028ECFFF"; // 2, 142, 207, 255 -constexpr const char* PLAYER0_DARK = "0297DBFF"; // 2, 151, 219, 255 -constexpr const char* PLAYER0_BASE = "029FE8FF"; // 2, 159, 232, 255 -constexpr const char* PLAYER0_LIGHT = "03A9F4FF"; // 3, 169, 244, 255 + // --- PLAYER --- + namespace Player { + namespace DefaultShirt { + // Player 0 (Jugador 1) + constexpr const char* PLAYER0_DARKEST = "028ECFFF"; // 2, 142, 207, 255 + constexpr const char* PLAYER0_DARK = "0297DBFF"; // 2, 151, 219, 255 + constexpr const char* PLAYER0_BASE = "029FE8FF"; // 2, 159, 232, 255 + constexpr const char* PLAYER0_LIGHT = "03A9F4FF"; // 3, 169, 244, 255 -// Player 1 (Jugador 2) -constexpr const char* PLAYER1_DARKEST = "8E8E8EFF"; // 142, 142, 142, 255 -constexpr const char* PLAYER1_DARK = "AEADADFF"; // 174, 173, 173, 255 -constexpr const char* PLAYER1_BASE = "E4E4E4FF"; // 228, 228, 228, 255 -constexpr const char* PLAYER1_LIGHT = "F7F1F1FF"; // 247, 241, 241, 255 -} // namespace DefaultShirt + // Player 1 (Jugador 2) + constexpr const char* PLAYER1_DARKEST = "8E8E8EFF"; // 142, 142, 142, 255 + constexpr const char* PLAYER1_DARK = "AEADADFF"; // 174, 173, 173, 255 + constexpr const char* PLAYER1_BASE = "E4E4E4FF"; // 228, 228, 228, 255 + constexpr const char* PLAYER1_LIGHT = "F7F1F1FF"; // 247, 241, 241, 255 + } // namespace DefaultShirt -namespace OneCoffeeShirt { -// Player 0 (Jugador 1) -constexpr const char* PLAYER0_DARKEST = "3D9C70FF"; // 61, 156, 112, 255 -constexpr const char* PLAYER0_DARK = "4FA370FF"; // 79, 163, 112, 255 -constexpr const char* PLAYER0_BASE = "5DDE70FF"; // 93, 222, 112, 255 -constexpr const char* PLAYER0_LIGHT = "7DF25CFF"; // 125, 242, 92, 255 + namespace OneCoffeeShirt { + // Player 0 (Jugador 1) + constexpr const char* PLAYER0_DARKEST = "3D9C70FF"; // 61, 156, 112, 255 + constexpr const char* PLAYER0_DARK = "4FA370FF"; // 79, 163, 112, 255 + constexpr const char* PLAYER0_BASE = "5DDE70FF"; // 93, 222, 112, 255 + constexpr const char* PLAYER0_LIGHT = "7DF25CFF"; // 125, 242, 92, 255 -// Player 1 (Jugador 2) -constexpr const char* PLAYER1_DARKEST = "2E8B57FF"; // 46, 139, 87, 255 -constexpr const char* PLAYER1_DARK = "3CB371FF"; // 60, 179, 113, 255 -constexpr const char* PLAYER1_BASE = "48D181FF"; // 72, 209, 129, 255 -constexpr const char* PLAYER1_LIGHT = "55EF8DFF"; // 85, 239, 141, 255 -} // namespace OneCoffeeShirt + // Player 1 (Jugador 2) + constexpr const char* PLAYER1_DARKEST = "2E8B57FF"; // 46, 139, 87, 255 + constexpr const char* PLAYER1_DARK = "3CB371FF"; // 60, 179, 113, 255 + constexpr const char* PLAYER1_BASE = "48D181FF"; // 72, 209, 129, 255 + constexpr const char* PLAYER1_LIGHT = "55EF8DFF"; // 85, 239, 141, 255 + } // namespace OneCoffeeShirt -namespace TwoCoffeeShirt { -// Player 0 (Jugador 1) -constexpr const char* PLAYER0_DARKEST = "D6A41AFF"; // 214, 164, 26, 255 -constexpr const char* PLAYER0_DARK = "E3AE1BFF"; // 227, 174, 27, 255 -constexpr const char* PLAYER0_BASE = "EFB71DFF"; // 239, 183, 29, 255 -constexpr const char* PLAYER0_LIGHT = "FCC11EFF"; // 252, 193, 30, 255 + namespace TwoCoffeeShirt { + // Player 0 (Jugador 1) + constexpr const char* PLAYER0_DARKEST = "D6A41AFF"; // 214, 164, 26, 255 + constexpr const char* PLAYER0_DARK = "E3AE1BFF"; // 227, 174, 27, 255 + constexpr const char* PLAYER0_BASE = "EFB71DFF"; // 239, 183, 29, 255 + constexpr const char* PLAYER0_LIGHT = "FCC11EFF"; // 252, 193, 30, 255 -// Player 1 (Jugador 2) -constexpr const char* PLAYER1_DARKEST = "E08500FF"; // 224, 133, 0, 255 -constexpr const char* PLAYER1_DARK = "FA7D00FF"; // 250, 125, 0, 255 -constexpr const char* PLAYER1_BASE = "FAA200FF"; // 250, 162, 0, 255 -constexpr const char* PLAYER1_LIGHT = "FA8500FF"; // 250, 133, 0, 255 -} // namespace TwoCoffeeShirt + // Player 1 (Jugador 2) + constexpr const char* PLAYER1_DARKEST = "E08500FF"; // 224, 133, 0, 255 + constexpr const char* PLAYER1_DARK = "FA7D00FF"; // 250, 125, 0, 255 + constexpr const char* PLAYER1_BASE = "FAA200FF"; // 250, 162, 0, 255 + constexpr const char* PLAYER1_LIGHT = "FA8500FF"; // 250, 133, 0, 255 + } // namespace TwoCoffeeShirt -namespace OutlineColor { -// Player 0 (Jugador 1) -constexpr const char* PLAYER0 = "66323FFF"; + namespace OutlineColor { + // Player 0 (Jugador 1) + constexpr const char* PLAYER0 = "66323FFF"; -// Player 1 (Jugador 2) -constexpr const char* PLAYER1 = "422028FF"; -} // namespace OutlineColor -} // namespace Player + // Player 1 (Jugador 2) + constexpr const char* PLAYER1 = "422028FF"; + } // namespace OutlineColor + } // namespace Player -// --- OPTIONS --- -namespace Options { -// Window -constexpr const char* WINDOW_CAPTION = "© 2025 Coffee Crisis Arcade Edition — JailDesigner"; -constexpr int WINDOW_ZOOM = 2; -constexpr int WINDOW_MAX_ZOOM = 2; + // --- OPTIONS --- + namespace Options { + // Window + constexpr const char* WINDOW_CAPTION = "© 2025 Coffee Crisis Arcade Edition — JailDesigner"; + constexpr int WINDOW_ZOOM = 2; + constexpr int WINDOW_MAX_ZOOM = 2; -// Video -constexpr SDL_ScaleMode VIDEO_SCALE_MODE = SDL_ScaleMode::SDL_SCALEMODE_NEAREST; -constexpr bool VIDEO_FULLSCREEN = false; -constexpr bool VIDEO_VSYNC = true; -constexpr bool VIDEO_INTEGER_SCALE = true; -constexpr bool VIDEO_SHADERS = false; + // Video + constexpr SDL_ScaleMode VIDEO_SCALE_MODE = SDL_ScaleMode::SDL_SCALEMODE_NEAREST; + constexpr bool VIDEO_FULLSCREEN = false; + constexpr bool VIDEO_VSYNC = true; + constexpr bool VIDEO_INTEGER_SCALE = true; + constexpr bool VIDEO_SHADERS = false; -// Music -constexpr bool MUSIC_ENABLED = true; -constexpr int MUSIC_VOLUME = 100; + // Music + constexpr bool MUSIC_ENABLED = true; + constexpr int MUSIC_VOLUME = 100; -// Sound -constexpr bool SOUND_ENABLED = true; -constexpr int SOUND_VOLUME = 100; + // Sound + constexpr bool SOUND_ENABLED = true; + constexpr int SOUND_VOLUME = 100; -// Audio -constexpr bool AUDIO_ENABLED = true; -constexpr int AUDIO_VOLUME = 100; + // Audio + constexpr bool AUDIO_ENABLED = true; + constexpr int AUDIO_VOLUME = 100; -// Settings -constexpr bool SETTINGS_AUTOFIRE = true; -constexpr bool SETTINGS_SHUTDOWN_ENABLED = false; -constexpr const char* PARAMS_FILE = "param_320x256.txt"; -} // namespace Options + // Settings + constexpr bool SETTINGS_AUTOFIRE = true; + constexpr bool SETTINGS_SHUTDOWN_ENABLED = false; + constexpr const char* PARAMS_FILE = "param_320x256.txt"; + } // namespace Options } // namespace GameDefaults \ No newline at end of file diff --git a/source/define_buttons.hpp b/source/define_buttons.hpp index 2377770..4e49f0a 100644 --- a/source/define_buttons.hpp +++ b/source/define_buttons.hpp @@ -12,69 +12,69 @@ #include "ui/window_message.hpp" namespace Options { -struct Gamepad; + struct Gamepad; } // --- Clase DefineButtons: configuración de botones de gamepad --- class DefineButtons { - public: - // --- Estructuras --- - struct Button { - std::string label; - Input::Action action; - int button; + public: + // --- Estructuras --- + struct Button { + std::string label; + Input::Action action; + int button; - Button(std::string label, Input::Action action, int button) - : label(std::move(label)), - action(action), - button(button) {} - }; + Button(std::string label, Input::Action action, int button) + : label(std::move(label)), + action(action), + button(button) {} + }; - // --- Constructor y destructor --- - DefineButtons(); - ~DefineButtons() = default; + // --- Constructor y destructor --- + DefineButtons(); + ~DefineButtons() = default; - // --- Métodos principales --- - void render(); - void update(float delta_time); - void handleEvents(const SDL_Event& event); - auto enable(Options::Gamepad* options_gamepad) -> bool; - void disable(); + // --- Métodos principales --- + void render(); + void update(float delta_time); + void handleEvents(const SDL_Event& event); + auto enable(Options::Gamepad* options_gamepad) -> bool; + void disable(); - // --- Getters --- - [[nodiscard]] auto isReadyToClose() const -> bool; - [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } - [[nodiscard]] auto isFinished() const -> bool { return finished_; } + // --- Getters --- + [[nodiscard]] auto isReadyToClose() const -> bool; + [[nodiscard]] auto isEnabled() const -> bool { return enabled_; } + [[nodiscard]] auto isFinished() const -> bool { return finished_; } - private: - // --- Constantes --- - static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0F; // Cuánto tiempo mostrar el mensaje en segundos + private: + // --- Constantes --- + static constexpr float MESSAGE_DISPLAY_DURATION_S = 2.0F; // Cuánto tiempo mostrar el mensaje en segundos - // --- Objetos y punteros --- - Input* input_ = nullptr; // Entrada del usuario - Options::Gamepad* options_gamepad_ = nullptr; // Opciones del gamepad - std::unique_ptr window_message_; // Mensaje de ventana + // --- Objetos y punteros --- + Input* input_ = nullptr; // Entrada del usuario + Options::Gamepad* options_gamepad_ = nullptr; // Opciones del gamepad + std::unique_ptr window_message_; // Mensaje de ventana - // --- Variables de estado --- - std::vector