From 88ce6cd570b7cf7fd4fc42600415a4adda230f04 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Fri, 21 Nov 2025 18:02:53 +0100 Subject: [PATCH] clang-format --- source/core/audio/audio.hpp | 14 +- source/core/input/global_inputs.cpp | 2 +- source/core/input/input.hpp | 70 +++++----- source/core/rendering/screen.hpp | 94 ++++++------- .../rendering/surface_animated_sprite.hpp | 2 +- source/core/rendering/surface_sprite.hpp | 4 +- source/core/rendering/text.hpp | 12 +- source/core/rendering/texture.hpp | 20 +-- source/core/resources/resource_cache.hpp | 6 +- source/core/resources/resource_loader.hpp | 8 +- source/core/resources/resource_pack.cpp | 3 +- source/core/resources/resource_pack.hpp | 12 +- source/core/resources/resource_types.hpp | 4 +- source/core/system/director.hpp | 4 +- source/game/entities/enemy.hpp | 22 +-- source/game/entities/item.hpp | 12 +- source/game/gameplay/cheevos.hpp | 26 ++-- source/game/gameplay/collision_map.cpp | 8 +- source/game/gameplay/collision_map.hpp | 42 +++--- source/game/gameplay/enemy_manager.cpp | 2 +- source/game/gameplay/enemy_manager.hpp | 6 +- source/game/gameplay/item_manager.cpp | 16 +-- source/game/gameplay/item_manager.hpp | 8 +- source/game/gameplay/item_tracker.hpp | 2 +- source/game/gameplay/room.hpp | 128 +++++++++--------- source/game/gameplay/room_loader.cpp | 2 +- source/game/gameplay/stats.hpp | 8 +- source/game/scene_manager.hpp | 2 +- source/game/scenes/ending.cpp | 68 ++++------ source/game/scenes/ending.hpp | 20 +-- source/game/scenes/game.cpp | 109 ++++++++++++--- source/game/scenes/game.hpp | 21 ++- source/game/scenes/game_over.hpp | 8 +- source/game/scenes/loading_screen.hpp | 20 +-- source/game/scenes/logo.hpp | 48 +++---- source/game/scenes/title.hpp | 16 +-- source/utils/easing_functions.hpp | 2 +- source/utils/utils.hpp | 46 +++---- 38 files changed, 484 insertions(+), 413 deletions(-) diff --git a/source/core/audio/audio.hpp b/source/core/audio/audio.hpp index b2eea8b..16ff733 100644 --- a/source/core/audio/audio.hpp +++ b/source/core/audio/audio.hpp @@ -77,9 +77,9 @@ class Audio { private: // --- Tipos anidados --- struct Music { - MusicState state{MusicState::STOPPED}; // Estado actual de la música - std::string name; // Última pista de música reproducida - bool loop{false}; // Indica si se reproduce en bucle + MusicState state{MusicState::STOPPED}; // Estado actual de la música + std::string name; // Última pista de música reproducida + bool loop{false}; // Indica si se reproduce en bucle }; // --- Métodos --- @@ -90,8 +90,8 @@ class Audio { // --- Variables miembro --- static Audio* instance; // Instancia única de Audio - 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 + 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 }; \ No newline at end of file diff --git a/source/core/input/global_inputs.cpp b/source/core/input/global_inputs.cpp index e354c25..f0a3a90 100644 --- a/source/core/input/global_inputs.cpp +++ b/source/core/input/global_inputs.cpp @@ -218,7 +218,7 @@ void handle() { break; case InputAction::TOGGLE_DEBUG: - //handleToggleDebug(); + // handleToggleDebug(); break; #ifdef _DEBUG diff --git a/source/core/input/input.hpp b/source/core/input/input.hpp index 5d0e77c..1fda900 100644 --- a/source/core/input/input.hpp +++ b/source/core/input/input.hpp @@ -9,7 +9,7 @@ #include // Para pair #include // Para vector -#include "core/input/input_types.hpp" // for InputAction +#include "core/input/input_types.hpp" // for InputAction // --- Clase Input: gestiona la entrada de teclado y mandos (singleton) --- class Input { @@ -27,17 +27,17 @@ class Input { // --- Estructuras --- struct KeyState { - Uint8 scancode{0}; // Scancode asociado - bool is_held{false}; // Está pulsada ahora mismo - bool just_pressed{false}; // Se acaba de pulsar en este fotograma + Uint8 scancode{0}; // Scancode asociado + bool is_held{false}; // Está pulsada ahora mismo + bool just_pressed{false}; // Se acaba de pulsar en este fotograma }; struct ButtonState { - int button{static_cast(SDL_GAMEPAD_BUTTON_INVALID)}; // GameControllerButton asociado - bool is_held{false}; // Está pulsada ahora mismo - bool just_pressed{false}; // Se acaba de pulsar en este fotograma - bool axis_active{false}; // Estado del eje - bool trigger_active{false}; // Estado del trigger como botón digital + int button{static_cast(SDL_GAMEPAD_BUTTON_INVALID)}; // GameControllerButton asociado + bool is_held{false}; // Está pulsada ahora mismo + bool just_pressed{false}; // Se acaba de pulsar en este fotograma + bool axis_active{false}; // Estado del eje + bool trigger_active{false}; // Estado del trigger como botón digital }; struct Keyboard { @@ -45,33 +45,33 @@ class Input { }; struct Gamepad { - SDL_Gamepad* pad{nullptr}; // Puntero al gamepad SDL - SDL_JoystickID instance_id{0}; // ID de instancia del joystick - std::string name; // Nombre del gamepad - std::string path; // Ruta del dispositivo - std::unordered_map bindings; // Mapa de acciones a estados de botón + SDL_Gamepad* pad{nullptr}; // Puntero al gamepad SDL + SDL_JoystickID instance_id{0}; // ID de instancia del joystick + std::string name; // Nombre del gamepad + std::string path; // Ruta del dispositivo + std::unordered_map bindings; // Mapa de acciones a estados de botón - explicit Gamepad(SDL_Gamepad* gamepad) - : pad(gamepad), - instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))), - name(std::string(SDL_GetGamepadName(gamepad))), - path(std::string(SDL_GetGamepadPath(pad))), - bindings{ - // Movimiento del jugador - {Action::LEFT, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}}, - {Action::RIGHT, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}}, - {Action::JUMP, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_WEST)}}} {} + explicit Gamepad(SDL_Gamepad* gamepad) + : pad(gamepad), + instance_id(SDL_GetJoystickID(SDL_GetGamepadJoystick(gamepad))), + name(std::string(SDL_GetGamepadName(gamepad))), + path(std::string(SDL_GetGamepadPath(pad))), + bindings{ + // Movimiento del jugador + {Action::LEFT, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_DPAD_LEFT)}}, + {Action::RIGHT, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_DPAD_RIGHT)}}, + {Action::JUMP, ButtonState{.button = static_cast(SDL_GAMEPAD_BUTTON_WEST)}}} {} - ~Gamepad() { - if (pad != nullptr) { - SDL_CloseGamepad(pad); + ~Gamepad() { + if (pad != nullptr) { + SDL_CloseGamepad(pad); + } } - } - // Reasigna un botón a una acción - void rebindAction(Action action, SDL_GamepadButton new_button) { - bindings[action].button = static_cast(new_button); - } + // Reasigna un botón a una acción + void rebindAction(Action action, SDL_GamepadButton new_button) { + bindings[action].button = static_cast(new_button); + } }; // --- Tipos --- @@ -134,7 +134,7 @@ class Input { // --- Variables miembro --- static Input* instance; // Instancia única del singleton - Gamepads gamepads_; // Lista de gamepads conectados - Keyboard keyboard_{}; // Estado del teclado - std::string gamepad_mappings_file_; // Ruta al archivo de mappings + Gamepads gamepads_; // Lista de gamepads conectados + Keyboard keyboard_{}; // Estado del teclado + std::string gamepad_mappings_file_; // Ruta al archivo de mappings }; \ No newline at end of file diff --git a/source/core/rendering/screen.hpp b/source/core/rendering/screen.hpp index 3f4f210..625c32c 100644 --- a/source/core/rendering/screen.hpp +++ b/source/core/rendering/screen.hpp @@ -23,8 +23,8 @@ class Screen { }; // Singleton - static void init(); // Crea el singleton - static void destroy(); // Destruye el singleton + static void init(); // Crea el singleton + static void destroy(); // Destruye el singleton static auto get() -> Screen*; // Obtiene el singleton // Renderizado @@ -35,32 +35,32 @@ class Screen { void update(float delta_time); // Actualiza la lógica de la clase // Video y ventana - void setVideoMode(bool mode); // Establece el modo de video - void toggleVideoMode(); // Cambia entre pantalla completa y ventana - void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero - void toggleVSync(); // Alterna entre activar y desactivar el V-Sync - auto decWindowZoom() -> bool; // Reduce el tamaño de la ventana - auto incWindowZoom() -> bool; // Aumenta el tamaño de la ventana - void show(); // Muestra la ventana - void hide(); // Oculta la ventana + void setVideoMode(bool mode); // Establece el modo de video + void toggleVideoMode(); // Cambia entre pantalla completa y ventana + void toggleIntegerScale(); // Alterna entre activar y desactivar el escalado entero + void toggleVSync(); // Alterna entre activar y desactivar el V-Sync + auto decWindowZoom() -> bool; // Reduce el tamaño de la ventana + auto incWindowZoom() -> bool; // Aumenta el tamaño de la ventana + void show(); // Muestra la ventana + void hide(); // Oculta la ventana // Borde - void setBorderColor(Uint8 color); // Cambia el color del borde - static void setBorderWidth(int width); // Establece el ancho del borde - static void setBorderHeight(int height); // Establece el alto del borde - static void setBorderEnabled(bool value); // Establece si se ha de ver el borde - void toggleBorder(); // Cambia entre borde visible y no visible + void setBorderColor(Uint8 color); // Cambia el color del borde + static void setBorderWidth(int width); // Establece el ancho del borde + static void setBorderHeight(int height); // Establece el alto del borde + static void setBorderEnabled(bool value); // Establece si se ha de ver el borde + void toggleBorder(); // Cambia entre borde visible y no visible // Paletas y shaders - void nextPalette(); // Cambia a la siguiente paleta - void previousPalette(); // Cambia a la paleta anterior - void setPalete(); // Establece la paleta actual - void toggleShaders(); // Cambia el estado de los shaders + void nextPalette(); // Cambia a la siguiente paleta + void previousPalette(); // Cambia a la paleta anterior + void setPalete(); // Establece la paleta actual + void toggleShaders(); // Cambia el estado de los shaders // Surfaces y notificaciones void setRendererSurface(const std::shared_ptr& surface = nullptr); // Establece el renderizador para las surfaces - void setNotificationsEnabled(bool value); // Establece la visibilidad de las notificaciones - void toggleDebugInfo(); // Activa o desactiva la información de debug + void setNotificationsEnabled(bool value); // Establece la visibilidad de las notificaciones + void toggleDebugInfo(); // Activa o desactiva la información de debug // Getters auto getRenderer() -> SDL_Renderer*; @@ -78,22 +78,22 @@ class Screen { }; struct FPS { - Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar - int frame_count{0}; // Número acumulado de frames en el intervalo - int last_value{0}; // Número de frames calculado en el último segundo + Uint32 ticks{0}; // Tiempo en milisegundos desde que se comenzó a contar + int frame_count{0}; // Número acumulado de frames en el intervalo + int last_value{0}; // Número de frames calculado en el último segundo - void increment() { - frame_count++; - } - - auto calculate(Uint32 current_ticks) -> int { - if (current_ticks - ticks >= 1000) { - last_value = frame_count; - frame_count = 0; - ticks = current_ticks; + void increment() { + frame_count++; + } + + auto calculate(Uint32 current_ticks) -> int { + if (current_ticks - ticks >= 1000) { + last_value = frame_count; + frame_count = 0; + ticks = current_ticks; + } + return last_value; } - return last_value; - } }; // Constantes @@ -123,8 +123,8 @@ class Screen { ~Screen(); // Objetos SDL - SDL_Window* window_{nullptr}; // Ventana de la aplicación - SDL_Renderer* renderer_{nullptr}; // Renderizador de la ventana + SDL_Window* window_{nullptr}; // Ventana de la aplicación + SDL_Renderer* renderer_{nullptr}; // Renderizador de la ventana SDL_Texture* game_texture_{nullptr}; // Textura donde se dibuja el juego SDL_Texture* border_texture_{nullptr}; // Textura donde se dibuja el borde del juego @@ -136,14 +136,14 @@ class Screen { std::shared_ptr text_; // Objeto para escribir texto // Configuración de ventana y pantalla - int window_width_{0}; // Ancho de la pantalla o ventana - int window_height_{0}; // Alto de la pantalla o ventana - SDL_FRect game_surface_dstrect_; // Coordenadas donde se dibuja la textura del juego + int window_width_{0}; // Ancho de la pantalla o ventana + int window_height_{0}; // Alto de la pantalla o ventana + SDL_FRect game_surface_dstrect_; // Coordenadas donde se dibuja la textura del juego // Paletas y colores - Uint8 border_color_{0}; // Color del borde - std::vector palettes_; // Listado de ficheros de paleta disponibles - Uint8 current_palette_{0}; // Índice para el vector de paletas + Uint8 border_color_{0}; // Color del borde + std::vector palettes_; // Listado de ficheros de paleta disponibles + Uint8 current_palette_{0}; // Índice para el vector de paletas // Estado y configuración bool notifications_enabled_{false}; // Indica si se muestran las notificaciones @@ -151,12 +151,12 @@ class Screen { DisplayMonitor display_monitor_; // Información de la pantalla // Shaders - std::string info_resolution_; // Texto con la información de la pantalla - std::string vertex_shader_source_; // Almacena el vertex shader - std::string fragment_shader_source_; // Almacena el fragment shader + std::string info_resolution_; // Texto con la información de la pantalla + std::string vertex_shader_source_; // Almacena el vertex shader + std::string fragment_shader_source_; // Almacena el fragment shader #ifdef _DEBUG - bool show_debug_info_{true}; // Indica si ha de mostrar la información de debug + bool show_debug_info_{true}; // Indica si ha de mostrar la información de debug #else bool show_debug_info_{false}; // Indica si ha de mostrar la información de debug #endif diff --git a/source/core/rendering/surface_animated_sprite.hpp b/source/core/rendering/surface_animated_sprite.hpp index 295a052..887a2bb 100644 --- a/source/core/rendering/surface_animated_sprite.hpp +++ b/source/core/rendering/surface_animated_sprite.hpp @@ -8,7 +8,7 @@ #include // Para vector #include "core/rendering/surface_moving_sprite.hpp" // Para SMovingSprite -#include "core/resources/resource_types.hpp" // Para AnimationResource +#include "core/resources/resource_types.hpp" // Para AnimationResource class Surface; diff --git a/source/core/rendering/surface_sprite.hpp b/source/core/rendering/surface_sprite.hpp index eab485e..8cdad48 100644 --- a/source/core/rendering/surface_sprite.hpp +++ b/source/core/rendering/surface_sprite.hpp @@ -19,8 +19,8 @@ class SurfaceSprite { virtual ~SurfaceSprite() = default; // Actualización y renderizado - virtual void update(float delta_time); // Actualiza el estado del sprite (time-based) - virtual void render(); // Muestra el sprite por pantalla + virtual void update(float delta_time); // Actualiza el estado del sprite (time-based) + virtual void render(); // Muestra el sprite por pantalla virtual void render(Uint8 source_color, Uint8 target_color); // Renderiza con reemplazo de color // Gestión de estado diff --git a/source/core/rendering/text.hpp b/source/core/rendering/text.hpp index 0455b22..2e79316 100644 --- a/source/core/rendering/text.hpp +++ b/source/core/rendering/text.hpp @@ -36,17 +36,17 @@ class Text { static constexpr int CENTER_FLAG = 4; static constexpr int STROKE_FLAG = 8; - void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla - void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1); // Escribe el texto con colores - void writeShadowed(int x, int y, const std::string& text, Uint8 color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra - void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x + void write(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla + void writeColored(int x, int y, const std::string& text, Uint8 color, int kerning = 1, int lenght = -1); // Escribe el texto con colores + void writeShadowed(int x, int y, const std::string& text, Uint8 color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra + void writeCentered(int x, int y, const std::string& text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x void writeDX(Uint8 flags, int x, int y, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1); // Escribe texto con extras - auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr; // Escribe el texto en una textura + auto writeToSurface(const std::string& text, int zoom = 1, int kerning = 1) -> std::shared_ptr; // Escribe el texto en una textura auto writeDXToSurface(Uint8 flags, const std::string& text, int kerning = 1, Uint8 text_color = Uint8(), Uint8 shadow_distance = 1, Uint8 shadow_color = Uint8(), int lenght = -1) -> std::shared_ptr; // Escribe el texto con extras en una textura [[nodiscard]] auto length(const std::string& text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena - [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter + [[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño del caracter void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra diff --git a/source/core/rendering/texture.hpp b/source/core/rendering/texture.hpp index 9e2fbfc..ed71d52 100644 --- a/source/core/rendering/texture.hpp +++ b/source/core/rendering/texture.hpp @@ -9,24 +9,24 @@ struct Color; // lines 11-11 class Texture { public: explicit Texture(SDL_Renderer* renderer, std::string path = std::string()); // Constructor - ~Texture(); // Destructor + ~Texture(); // Destructor - auto loadFromFile(const std::string& path) -> bool; // Carga una imagen desde un fichero + auto loadFromFile(const std::string& path) -> bool; // Carga una imagen desde un fichero auto createBlank(int width, int height, SDL_PixelFormat format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess access = SDL_TEXTUREACCESS_STREAMING) -> bool; // Crea una textura en blanco - auto reLoad() -> bool; // Recarga la textura + auto reLoad() -> bool; // Recarga la textura void setColor(Uint8 red, Uint8 green, Uint8 blue); // Establece el color para la modulacion - void setColor(Color color); // Establece el color para la modulacion - void setBlendMode(SDL_BlendMode blending); // Establece el blending - void setAlpha(Uint8 alpha); // Establece el alpha para la modulación - void setAsRenderTarget(SDL_Renderer* renderer); // Establece la textura como objetivo de renderizado + void setColor(Color color); // Establece el color para la modulacion + void setBlendMode(SDL_BlendMode blending); // Establece el blending + void setAlpha(Uint8 alpha); // Establece el alpha para la modulación + void setAsRenderTarget(SDL_Renderer* renderer); // Establece la textura como objetivo de renderizado void render(float x, float y, SDL_FRect* clip = nullptr, float zoom_w = 1, float zoom_h = 1, double angle = 0.0, SDL_FPoint* center = nullptr, SDL_FlipMode flip = SDL_FLIP_NONE); // Renderiza la textura en un punto específico - [[nodiscard]] auto getWidth() const -> int { return width_; } // Obtiene el ancho de la imagen + [[nodiscard]] auto getWidth() const -> int { return width_; } // Obtiene el ancho de la imagen [[nodiscard]] auto getHeight() const -> int { return height_; } // Obtiene el alto de la imagen - auto getSDLTexture() -> SDL_Texture*; // Obtiene la textura - auto getRenderer() -> SDL_Renderer*; // Obtiene el renderizador + auto getSDLTexture() -> SDL_Texture*; // Obtiene la textura + auto getRenderer() -> SDL_Renderer*; // Obtiene el renderizador private: void unloadTexture(); // Libera la memoria de la textura diff --git a/source/core/resources/resource_cache.hpp b/source/core/resources/resource_cache.hpp index 1176868..132dea7 100644 --- a/source/core/resources/resource_cache.hpp +++ b/source/core/resources/resource_cache.hpp @@ -15,7 +15,7 @@ class Cache { static void destroy(); // Destrucción singleton static auto get() -> Cache*; // Acceso al singleton - auto getSound(const std::string& name) -> JA_Sound_t*; // Getters de recursos + auto getSound(const std::string& name) -> JA_Sound_t*; // Getters de recursos auto getMusic(const std::string& name) -> JA_Music_t*; auto getSurface(const std::string& name) -> std::shared_ptr; auto getPalette(const std::string& name) -> Palette; @@ -86,8 +86,8 @@ class Cache { std::vector animations_; // Vector con las animaciones std::vector rooms_; // Vector con las habitaciones - ResourceCount count_{}; // Contador de recursos - std::shared_ptr loading_text_; // Texto para la pantalla de carga + ResourceCount count_{}; // Contador de recursos + std::shared_ptr loading_text_; // Texto para la pantalla de carga }; } // namespace Resource diff --git a/source/core/resources/resource_loader.hpp b/source/core/resources/resource_loader.hpp index ebe5b92..834641a 100644 --- a/source/core/resources/resource_loader.hpp +++ b/source/core/resources/resource_loader.hpp @@ -21,14 +21,14 @@ class Loader { auto loadResource(const std::string& filename) -> std::vector; // Load resource data auto resourceExists(const std::string& filename) -> bool; // Check resource availability - [[nodiscard]] auto isPackLoaded() const -> bool; // Pack status queries + [[nodiscard]] auto isPackLoaded() const -> bool; // Pack status queries [[nodiscard]] auto getPackResourceCount() const -> size_t; - [[nodiscard]] auto validatePack() const -> bool; // Validate pack integrity - [[nodiscard]] auto loadAssetsConfig() const -> std::string; // Load assets.yaml from pack + [[nodiscard]] auto validatePack() const -> bool; // Validate pack integrity + [[nodiscard]] auto loadAssetsConfig() const -> std::string; // Load assets.yaml from pack void shutdown(); // Cleanup - Loader(const Loader&) = delete; // Deleted copy/move constructors + Loader(const Loader&) = delete; // Deleted copy/move constructors auto operator=(const Loader&) -> Loader& = delete; Loader(Loader&&) = delete; auto operator=(Loader&&) -> Loader& = delete; diff --git a/source/core/resources/resource_pack.cpp b/source/core/resources/resource_pack.cpp index 6222f3f..838e7e6 100644 --- a/source/core/resources/resource_pack.cpp +++ b/source/core/resources/resource_pack.cpp @@ -68,8 +68,7 @@ auto Pack::addFile(const std::string& filepath, const std::string& pack_name) .filename = pack_name, .offset = data_.size(), .size = file_data.size(), - .checksum = calculateChecksum(file_data) - }; + .checksum = calculateChecksum(file_data)}; // Append file data to the data block data_.insert(data_.end(), file_data.begin(), file_data.end()); diff --git a/source/core/resources/resource_pack.hpp b/source/core/resources/resource_pack.hpp index 2e87aa0..7a9f761 100644 --- a/source/core/resources/resource_pack.hpp +++ b/source/core/resources/resource_pack.hpp @@ -13,10 +13,10 @@ namespace Resource { // Entry metadata for each resource in the pack struct ResourceEntry { - std::string filename; // Relative path within pack - uint64_t offset{0}; // Byte offset in data block - uint64_t size{0}; // Size in bytes - uint32_t checksum{0}; // CRC32 checksum for verification + std::string filename; // Relative path within pack + uint64_t offset{0}; // Byte offset in data block + uint64_t size{0}; // Size in bytes + uint32_t checksum{0}; // CRC32 checksum for verification }; // Resource pack file format @@ -28,7 +28,7 @@ class Pack { Pack() = default; ~Pack() = default; - Pack(const Pack&) = delete; // Deleted copy/move constructors + Pack(const Pack&) = delete; // Deleted copy/move constructors auto operator=(const Pack&) -> Pack& = delete; Pack(Pack&&) = delete; auto operator=(Pack&&) -> Pack& = delete; @@ -43,7 +43,7 @@ class Pack { auto hasResource(const std::string& filename) const -> bool; auto getResourceList() const -> std::vector; - auto isLoaded() const -> bool { return loaded_; } // Status queries + auto isLoaded() const -> bool { return loaded_; } // Status queries auto getResourceCount() const -> size_t { return resources_.size(); } auto getDataSize() const -> size_t { return data_.size(); } auto calculatePackChecksum() const -> uint32_t; // Validation diff --git a/source/core/resources/resource_types.hpp b/source/core/resources/resource_types.hpp index 227fe18..48eac0d 100644 --- a/source/core/resources/resource_types.hpp +++ b/source/core/resources/resource_types.hpp @@ -33,8 +33,8 @@ struct SurfaceResource { // Estructura para almacenar objetos Palette y su nombre struct ResourcePalette { - std::string name; // Nombre de la surface - Palette palette{}; // Paleta + std::string name; // Nombre de la surface + Palette palette{}; // Paleta }; // Estructura para almacenar ficheros TextFile y su nombre diff --git a/source/core/system/director.hpp b/source/core/system/director.hpp index d1b681b..69a6d55 100644 --- a/source/core/system/director.hpp +++ b/source/core/system/director.hpp @@ -8,8 +8,8 @@ class Director { public: explicit Director(std::vector const& args); // Constructor - ~Director(); // Destructor - static auto run() -> int; // Bucle principal + ~Director(); // Destructor + static auto run() -> int; // Bucle principal private: // --- Variables --- diff --git a/source/game/entities/enemy.hpp b/source/game/entities/enemy.hpp index d5faa99..8fe6811 100644 --- a/source/game/entities/enemy.hpp +++ b/source/game/entities/enemy.hpp @@ -27,8 +27,8 @@ class Enemy { explicit Enemy(const Data& enemy); // Constructor ~Enemy() = default; // Destructor - void render(); // Pinta el enemigo en pantalla - void update(float delta_time); // Actualiza las variables del objeto + void render(); // Pinta el enemigo en pantalla + void update(float delta_time); // Actualiza las variables del objeto auto getRect() -> SDL_FRect; // Devuelve el rectangulo que contiene al enemigo auto getCollider() -> SDL_FRect&; // Obtiene el rectangulo de colision del enemigo @@ -39,13 +39,13 @@ class Enemy { std::shared_ptr sprite_; // Sprite del enemigo // Variables - Uint8 color_{0}; // Color del enemigo - std::string color_string_; // Color del enemigo en formato texto - int x1_{0}; // Limite izquierdo de la ruta en el eje X - int x2_{0}; // Limite derecho de la ruta en el eje X - int y1_{0}; // Limite superior de la ruta en el eje Y - int y2_{0}; // Limite inferior de la ruta en el eje Y - SDL_FRect collider_{}; // Caja de colisión - bool should_flip_{false}; // Indica si el enemigo hace flip al terminar su ruta - bool should_mirror_{false}; // Indica si el enemigo se dibuja volteado verticalmente + Uint8 color_{0}; // Color del enemigo + std::string color_string_; // Color del enemigo en formato texto + int x1_{0}; // Limite izquierdo de la ruta en el eje X + int x2_{0}; // Limite derecho de la ruta en el eje X + int y1_{0}; // Limite superior de la ruta en el eje Y + int y2_{0}; // Limite inferior de la ruta en el eje Y + SDL_FRect collider_{}; // Caja de colisión + bool should_flip_{false}; // Indica si el enemigo hace flip al terminar su ruta + bool should_mirror_{false}; // Indica si el enemigo se dibuja volteado verticalmente }; diff --git a/source/game/entities/item.hpp b/source/game/entities/item.hpp index c64409e..db4d011 100644 --- a/source/game/entities/item.hpp +++ b/source/game/entities/item.hpp @@ -22,7 +22,7 @@ class Item { explicit Item(const Data& item); // Constructor ~Item() = default; // Destructor - void render() const; // Pinta el objeto en pantalla + void render() const; // Pinta el objeto en pantalla void update(float delta_time); // Actualiza las variables del objeto void setPaused(bool paused) { is_paused_ = paused; } // Pausa/despausa el item @@ -31,14 +31,14 @@ class Item { void setColors(Uint8 col1, Uint8 col2); // Asigna los colores del objeto private: - static constexpr float ITEM_SIZE = 8.0F; // Tamaño del item en pixels + static constexpr float ITEM_SIZE = 8.0F; // Tamaño del item en pixels static constexpr float COLOR_CHANGE_INTERVAL = 0.06F; // Intervalo de cambio de color en segundos (4 frames a 66.67fps) std::shared_ptr sprite_; // SSprite del objeto // Variables - std::vector color_; // Vector con los colores del objeto - float time_accumulator_{0.0F}; // Acumulador de tiempo para cambio de color - SDL_FRect collider_{}; // Rectangulo de colisión - bool is_paused_{false}; // Indica si el item está pausado + std::vector color_; // Vector con los colores del objeto + float time_accumulator_{0.0F}; // Acumulador de tiempo para cambio de color + SDL_FRect collider_{}; // Rectangulo de colisión + bool is_paused_{false}; // Indica si el item está pausado }; \ No newline at end of file diff --git a/source/game/gameplay/cheevos.hpp b/source/game/gameplay/cheevos.hpp index 734f046..b9db455 100644 --- a/source/game/gameplay/cheevos.hpp +++ b/source/game/gameplay/cheevos.hpp @@ -8,12 +8,12 @@ class Cheevos { public: // Tipos anidados (públicos porque se usan en la interfaz) struct Achievement { - int id{0}; // Identificador del logro - std::string caption; // Texto con el nombre del logro - std::string description; // Texto que describe el logro - int icon{0}; // Indice del icono a utilizar en la notificación - bool completed{false}; // Indica si se ha obtenido el logro - bool obtainable{true}; // Indica si se puede obtener el logro + int id{0}; // Identificador del logro + std::string caption; // Texto con el nombre del logro + std::string description; // Texto que describe el logro + int icon{0}; // Indice del icono a utilizar en la notificación + bool completed{false}; // Indica si se ha obtenido el logro + bool obtainable{true}; // Indica si se puede obtener el logro }; using Achievements = std::vector; // Type alias para vector de logros @@ -24,10 +24,10 @@ class Cheevos { static auto get() -> Cheevos*; // Acceso al singleton // Gestión de logros - void unlock(int id); // Desbloquea un logro - void setUnobtainable(int id); // Invalida un logro - void clearUnobtainableState(); // Elimina el estado "no obtenible" - void enable(bool value) { enabled_ = value; } // Habilita o deshabilita los logros + void unlock(int id); // Desbloquea un logro + void setUnobtainable(int id); // Invalida un logro + void clearUnobtainableState(); // Elimina el estado "no obtenible" + void enable(bool value) { enabled_ = value; } // Habilita o deshabilita los logros // Consultas [[nodiscard]] auto list() const -> const Achievements& { return cheevos_list_; } // Lista los logros @@ -39,10 +39,10 @@ class Cheevos { static Cheevos* cheevos; // [SINGLETON] Objeto privado // Métodos privados - void init(); // Inicializa los logros + void init(); // Inicializa los logros auto find(int id) -> int; // Busca un logro por id y devuelve el índice - void loadFromFile(); // Carga el estado de los logros desde un fichero - void saveToFile(); // Guarda el estado de los logros en un fichero + void loadFromFile(); // Carga el estado de los logros desde un fichero + void saveToFile(); // Guarda el estado de los logros en un fichero // Constructor y destructor privados [SINGLETON] explicit Cheevos(std::string file); diff --git a/source/game/gameplay/collision_map.cpp b/source/game/gameplay/collision_map.cpp index 04e6dfb..2f2c653 100644 --- a/source/game/gameplay/collision_map.cpp +++ b/source/game/gameplay/collision_map.cpp @@ -5,13 +5,13 @@ #ifdef _DEBUG #include "core/system/debug.hpp" // Para Debug #endif -#include "utils/defines.hpp" // Para Collision +#include "utils/defines.hpp" // Para Collision // Constructor CollisionMap::CollisionMap(std::vector tile_map, int tile_set_width, int conveyor_belt_direction) - : tile_map_(std::move(tile_map)) - , tile_set_width_(tile_set_width) - , conveyor_belt_direction_(conveyor_belt_direction) { + : tile_map_(std::move(tile_map)), + tile_set_width_(tile_set_width), + conveyor_belt_direction_(conveyor_belt_direction) { // Inicializa todas las superficies de colisión initializeSurfaces(); } diff --git a/source/game/gameplay/collision_map.hpp b/source/game/gameplay/collision_map.hpp index 3ec64d9..3fd5a16 100644 --- a/source/game/gameplay/collision_map.hpp +++ b/source/game/gameplay/collision_map.hpp @@ -55,19 +55,19 @@ class CollisionMap { auto checkBottomSurfaces(const SDL_FRect& rect) -> int; // Colisión con suelos (retorna Y) // --- Queries de colisión con superficies automáticas (conveyor belts) --- - auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Colisión con conveyor belts (retorna Y) - auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Colisión punto con conveyor belts + auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Colisión con conveyor belts (retorna Y) + auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Colisión punto con conveyor belts // --- Queries de colisión con rampas --- - auto checkLeftSlopes(const LineVertical& line) -> int; // Colisión línea con rampas izquierdas (retorna Y) - auto checkLeftSlopes(const SDL_FPoint& p) -> bool; // Colisión punto con rampas izquierdas - auto checkRightSlopes(const LineVertical& line) -> int; // Colisión línea con rampas derechas (retorna Y) - auto checkRightSlopes(const SDL_FPoint& p) -> bool; // Colisión punto con rampas derechas + auto checkLeftSlopes(const LineVertical& line) -> int; // Colisión línea con rampas izquierdas (retorna Y) + auto checkLeftSlopes(const SDL_FPoint& p) -> bool; // Colisión punto con rampas izquierdas + auto checkRightSlopes(const LineVertical& line) -> int; // Colisión línea con rampas derechas (retorna Y) + auto checkRightSlopes(const SDL_FPoint& p) -> bool; // Colisión punto con rampas derechas [[nodiscard]] auto getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal*; // Obtiene puntero a slope en un punto // --- Métodos estáticos --- - static auto getTileSize() -> int { return TILE_SIZE; } // Tamaño del tile en pixels - static auto getSlopeHeight(SDL_FPoint p, Tile slope) -> int; // Altura de rampa en un punto + static auto getTileSize() -> int { return TILE_SIZE; } // Tamaño del tile en pixels + static auto getSlopeHeight(SDL_FPoint p, Tile slope) -> int; // Altura de rampa en un punto // --- Getters --- [[nodiscard]] auto getConveyorBeltDirection() const -> int { return conveyor_belt_direction_; } @@ -83,14 +83,14 @@ class CollisionMap { private: // --- Constantes --- - static constexpr int TILE_SIZE = 8; // Tamaño del tile en pixels - static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles - static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles + static constexpr int TILE_SIZE = 8; // Tamaño del tile en pixels + static constexpr int MAP_WIDTH = 32; // Ancho del mapa en tiles + static constexpr int MAP_HEIGHT = 16; // Alto del mapa en tiles // --- Datos de la habitación --- - std::vector tile_map_; // Índices de tiles de la habitación - int tile_set_width_; // Ancho del tileset en tiles - int conveyor_belt_direction_; // Dirección de conveyor belts + std::vector tile_map_; // Índices de tiles de la habitación + int tile_set_width_; // Ancho del tileset en tiles + int conveyor_belt_direction_; // Dirección de conveyor belts // --- Geometría de colisión --- std::vector bottom_floors_; // Superficies inferiores (suelos) @@ -111,11 +111,11 @@ class CollisionMap { // Construcción de geometría static void buildHorizontalLines(const std::vector& tiles, std::vector& lines, bool is_bottom_surface); - void setBottomSurfaces(); // Calcula superficies inferiores - void setTopSurfaces(); // Calcula superficies superiores - void setLeftSurfaces(); // Calcula paredes izquierdas - void setRightSurfaces(); // Calcula paredes derechas - void setLeftSlopes(); // Calcula rampas izquierdas - void setRightSlopes(); // Calcula rampas derechas - void setAutoSurfaces(); // Calcula conveyor belts + void setBottomSurfaces(); // Calcula superficies inferiores + void setTopSurfaces(); // Calcula superficies superiores + void setLeftSurfaces(); // Calcula paredes izquierdas + void setRightSurfaces(); // Calcula paredes derechas + void setLeftSlopes(); // Calcula rampas izquierdas + void setRightSlopes(); // Calcula rampas derechas + void setAutoSurfaces(); // Calcula conveyor belts }; diff --git a/source/game/gameplay/enemy_manager.cpp b/source/game/gameplay/enemy_manager.cpp index a1ed5ae..2963350 100644 --- a/source/game/gameplay/enemy_manager.cpp +++ b/source/game/gameplay/enemy_manager.cpp @@ -2,8 +2,8 @@ #include // Para std::ranges::any_of -#include "utils/utils.hpp" // Para checkCollision #include "game/entities/enemy.hpp" // Para Enemy +#include "utils/utils.hpp" // Para checkCollision // Añade un enemigo a la colección void EnemyManager::addEnemy(std::shared_ptr enemy) { diff --git a/source/game/gameplay/enemy_manager.hpp b/source/game/gameplay/enemy_manager.hpp index 7f8ebbe..d915f4a 100644 --- a/source/game/gameplay/enemy_manager.hpp +++ b/source/game/gameplay/enemy_manager.hpp @@ -29,9 +29,9 @@ class EnemyManager { // Gestión de enemigos void addEnemy(std::shared_ptr enemy); // Añade un enemigo a la colección - void clear(); // Elimina todos los enemigos - void removeLastEnemy(); // Elimina el último enemigo de la colección - [[nodiscard]] auto isEmpty() const -> bool; // Comprueba si no hay enemigos + void clear(); // Elimina todos los enemigos + void removeLastEnemy(); // Elimina el último enemigo de la colección + [[nodiscard]] auto isEmpty() const -> bool; // Comprueba si no hay enemigos // Actualización y renderizado void update(float delta_time); // Actualiza todos los enemigos diff --git a/source/game/gameplay/item_manager.cpp b/source/game/gameplay/item_manager.cpp index 45d067c..ebbe075 100644 --- a/source/game/gameplay/item_manager.cpp +++ b/source/game/gameplay/item_manager.cpp @@ -1,16 +1,16 @@ #include "item_manager.hpp" -#include "core/audio/audio.hpp" // Para Audio -#include "utils/utils.hpp" // Para checkCollision -#include "game/entities/item.hpp" // Para Item -#include "item_tracker.hpp" // Para ItemTracker -#include "scoreboard.hpp" // Para Scoreboard::Data -#include "game/options.hpp" // Para Options +#include "core/audio/audio.hpp" // Para Audio +#include "game/entities/item.hpp" // Para Item +#include "game/options.hpp" // Para Options +#include "item_tracker.hpp" // Para ItemTracker +#include "scoreboard.hpp" // Para Scoreboard::Data +#include "utils/utils.hpp" // Para checkCollision // Constructor ItemManager::ItemManager(std::string room_name, std::shared_ptr scoreboard_data) - : room_name_(std::move(room_name)) - , data_(std::move(scoreboard_data)) { + : room_name_(std::move(room_name)), + data_(std::move(scoreboard_data)) { } // Añade un item a la colección diff --git a/source/game/gameplay/item_manager.hpp b/source/game/gameplay/item_manager.hpp index ed1abc5..8dcfb9b 100644 --- a/source/game/gameplay/item_manager.hpp +++ b/source/game/gameplay/item_manager.hpp @@ -38,7 +38,7 @@ class ItemManager { // Gestión de items void addItem(std::shared_ptr item); // Añade un item a la colección - void clear(); // Elimina todos los items + void clear(); // Elimina todos los items // Actualización y renderizado void update(float delta_time); // Actualiza todos los items @@ -63,7 +63,7 @@ class ItemManager { auto checkCollision(SDL_FRect& rect) -> bool; private: - std::vector> items_; // Colección de items - std::string room_name_; // Nombre de la habitación - std::shared_ptr data_; // Datos del scoreboard + std::vector> items_; // Colección de items + std::string room_name_; // Nombre de la habitación + std::shared_ptr data_; // Datos del scoreboard }; diff --git a/source/game/gameplay/item_tracker.hpp b/source/game/gameplay/item_tracker.hpp index c00ec44..f0d4b76 100644 --- a/source/game/gameplay/item_tracker.hpp +++ b/source/game/gameplay/item_tracker.hpp @@ -37,7 +37,7 @@ class ItemTracker { static ItemTracker* item_tracker; // [SINGLETON] Objeto privado // Métodos privados - auto findByName(const std::string& name) -> int; // Busca una entrada en la lista por nombre + auto findByName(const std::string& name) -> int; // Busca una entrada en la lista por nombre auto findByPos(int index, SDL_FPoint pos) -> int; // Busca una entrada en la lista por posición // Constructor y destructor privados [SINGLETON] diff --git a/source/game/gameplay/room.hpp b/source/game/gameplay/room.hpp index bb52f39..18055e8 100644 --- a/source/game/gameplay/room.hpp +++ b/source/game/gameplay/room.hpp @@ -6,12 +6,12 @@ #include // Para string #include // Para vector -#include "game/entities/enemy.hpp" // Para EnemyData -#include "game/entities/item.hpp" // Para ItemData +#include "game/entities/enemy.hpp" // Para EnemyData +#include "game/entities/item.hpp" // Para ItemData #include "game/gameplay/scoreboard.hpp" // Para Scoreboard::Data -#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical -class SurfaceSprite; // lines 12-12 -class Surface; // lines 13-13 +#include "utils/utils.hpp" // Para LineHorizontal, LineDiagonal, LineVertical +class SurfaceSprite; // lines 12-12 +class Surface; // lines 13-13 class EnemyManager; class ItemManager; class CollisionMap; @@ -38,21 +38,21 @@ class Room { }; struct Data { - std::string number; // Numero de la habitación - std::string name; // Nombre de la habitación - std::string bg_color; // Color de fondo de la habitación - std::string border_color; // Color del borde de la pantalla - std::string item_color1; // Color 1 para los items de la habitación - std::string item_color2; // Color 2 para los items de la habitación - std::string upper_room; // Identificador de la habitación que se encuentra arriba - std::string lower_room; // Identificador de la habitación que se encuentra abajo - std::string left_room; // Identificador de la habitación que se encuentra a la izquierda - std::string right_room; // Identificador de la habitación que se encuentra a la derecha - std::string tile_set_file; // Imagen con los gráficos para la habitación - int conveyor_belt_direction{0}; // Sentido en el que arrastran las superficies automáticas de la habitación - std::vector tile_map; // Índice de los tiles a dibujar en la habitación (embebido desde YAML) - std::vector enemies; // Listado con los enemigos de la habitación - std::vector items; // Listado con los items que hay en la habitación + std::string number; // Numero de la habitación + std::string name; // Nombre de la habitación + std::string bg_color; // Color de fondo de la habitación + std::string border_color; // Color del borde de la pantalla + std::string item_color1; // Color 1 para los items de la habitación + std::string item_color2; // Color 2 para los items de la habitación + std::string upper_room; // Identificador de la habitación que se encuentra arriba + std::string lower_room; // Identificador de la habitación que se encuentra abajo + std::string left_room; // Identificador de la habitación que se encuentra a la izquierda + std::string right_room; // Identificador de la habitación que se encuentra a la derecha + std::string tile_set_file; // Imagen con los gráficos para la habitación + int conveyor_belt_direction{0}; // Sentido en el que arrastran las superficies automáticas de la habitación + std::vector tile_map; // Índice de los tiles a dibujar en la habitación (embebido desde YAML) + std::vector enemies; // Listado con los enemigos de la habitación + std::vector items; // Listado con los items que hay en la habitación }; // Constructor y destructor @@ -60,37 +60,37 @@ class Room { ~Room(); // Definido en .cpp para poder usar unique_ptr con forward declarations // --- Funciones --- - [[nodiscard]] auto getName() const -> const std::string& { return name_; } // Devuelve el nombre de la habitación - [[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); } // Devuelve el color de la habitación - [[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); } // Devuelve el color del borde - void renderMap(); // Dibuja el mapa en pantalla - void renderEnemies(); // Dibuja los enemigos en pantalla - void renderItems(); // Dibuja los objetos en pantalla + [[nodiscard]] auto getName() const -> const std::string& { return name_; } // Devuelve el nombre de la habitación + [[nodiscard]] auto getBGColor() const -> Uint8 { return stringToColor(bg_color_); } // Devuelve el color de la habitación + [[nodiscard]] auto getBorderColor() const -> Uint8 { return stringToColor(border_color_); } // Devuelve el color del borde + void renderMap(); // Dibuja el mapa en pantalla + void renderEnemies(); // Dibuja los enemigos en pantalla + void renderItems(); // Dibuja los objetos en pantalla #ifdef _DEBUG - void redrawMap(); // Redibuja el mapa (para actualizar modo debug) + void redrawMap(); // Redibuja el mapa (para actualizar modo debug) #endif - void update(float delta_time); // Actualiza las variables y objetos de la habitación - auto getRoom(Border border) -> std::string; // Devuelve la cadena del fichero de la habitación contigua segun el borde - auto getTile(SDL_FPoint point) -> Tile; // Devuelve el tipo de tile que hay en ese pixel - auto getTile(int index) -> Tile; // Devuelve el tipo de tile en un índice del tilemap - auto enemyCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un enemigo a partir de un rectangulo - auto itemCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un objeto a partir de un rectangulo - static auto getTileSize() -> int { return TILE_SIZE; } // Obten el tamaño del tile - static auto getSlopeHeight(SDL_FPoint p, Tile slope) -> int; // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile - auto checkRightSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones - auto checkLeftSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones - auto checkTopSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones - auto checkBottomSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones - auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones - auto checkTopSurfaces(const SDL_FPoint& p) -> bool; // Comprueba las colisiones - auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Comprueba las colisiones - auto checkLeftSlopes(const LineVertical& line) -> int; // Comprueba las colisiones - auto checkLeftSlopes(const SDL_FPoint& p) -> bool; // Comprueba las colisiones - auto checkRightSlopes(const LineVertical& line) -> int; // Comprueba las colisiones - auto checkRightSlopes(const SDL_FPoint& p) -> bool; // Comprueba las colisiones - [[nodiscard]] auto getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal*; // Obtiene puntero a slope en un punto - void setPaused(bool value); // Pone el mapa en modo pausa - [[nodiscard]] auto getConveyorBeltDirection() const -> int { return conveyor_belt_direction_; } // Obten la direccion de las superficies automaticas + void update(float delta_time); // Actualiza las variables y objetos de la habitación + auto getRoom(Border border) -> std::string; // Devuelve la cadena del fichero de la habitación contigua segun el borde + auto getTile(SDL_FPoint point) -> Tile; // Devuelve el tipo de tile que hay en ese pixel + auto getTile(int index) -> Tile; // Devuelve el tipo de tile en un índice del tilemap + auto enemyCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un enemigo a partir de un rectangulo + auto itemCollision(SDL_FRect& rect) -> bool; // Indica si hay colision con un objeto a partir de un rectangulo + static auto getTileSize() -> int { return TILE_SIZE; } // Obten el tamaño del tile + static auto getSlopeHeight(SDL_FPoint p, Tile slope) -> int; // Obten la coordenada de la cuesta a partir de un punto perteneciente a ese tile + auto checkRightSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones + auto checkLeftSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones + auto checkTopSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones + auto checkBottomSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones + auto checkAutoSurfaces(const SDL_FRect& rect) -> int; // Comprueba las colisiones + auto checkTopSurfaces(const SDL_FPoint& p) -> bool; // Comprueba las colisiones + auto checkConveyorBelts(const SDL_FPoint& p) -> bool; // Comprueba las colisiones + auto checkLeftSlopes(const LineVertical& line) -> int; // Comprueba las colisiones + auto checkLeftSlopes(const SDL_FPoint& p) -> bool; // Comprueba las colisiones + auto checkRightSlopes(const LineVertical& line) -> int; // Comprueba las colisiones + auto checkRightSlopes(const SDL_FPoint& p) -> bool; // Comprueba las colisiones + [[nodiscard]] auto getSlopeAtPoint(const SDL_FPoint& p) const -> const LineDiagonal*; // Obtiene puntero a slope en un punto + void setPaused(bool value); // Pone el mapa en modo pausa + [[nodiscard]] auto getConveyorBeltDirection() const -> int { return conveyor_belt_direction_; } // Obten la direccion de las superficies automaticas // Método de carga de archivos YAML (delegado a RoomLoader) static auto loadYAML(const std::string& file_path, bool verbose = false) -> Data; // Carga habitación desde archivo YAML unificado @@ -110,21 +110,21 @@ class Room { std::shared_ptr data_; // Puntero a los datos del marcador // --- Variables --- - std::string number_; // Numero de la habitación - std::string name_; // Nombre de la habitación - std::string bg_color_; // Color de fondo de la habitación - std::string border_color_; // Color del borde de la pantalla - std::string item_color1_; // Color 1 para los items de la habitación - std::string item_color2_; // Color 2 para los items de la habitación - std::string upper_room_; // Identificador de la habitación que se encuentra arriba - std::string lower_room_; // Identificador de la habitación que se encuentra abajp - std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda - std::string right_room_; // Identificador de la habitación que se encuentra a la derecha - std::string tile_set_file_; // Imagen con los graficos para la habitación - std::vector tile_map_; // Indice de los tiles a dibujar en la habitación (embebido desde YAML) - int conveyor_belt_direction_{0}; // Sentido en el que arrastran las superficies automáticas de la habitación - bool is_paused_{false}; // Indica si el mapa esta en modo pausa - int tile_set_width_{0}; // Ancho del tileset en tiles + std::string number_; // Numero de la habitación + std::string name_; // Nombre de la habitación + std::string bg_color_; // Color de fondo de la habitación + std::string border_color_; // Color del borde de la pantalla + std::string item_color1_; // Color 1 para los items de la habitación + std::string item_color2_; // Color 2 para los items de la habitación + std::string upper_room_; // Identificador de la habitación que se encuentra arriba + std::string lower_room_; // Identificador de la habitación que se encuentra abajp + std::string left_room_; // Identificador de la habitación que se encuentra a la izquierda + std::string right_room_; // Identificador de la habitación que se encuentra a la derecha + std::string tile_set_file_; // Imagen con los graficos para la habitación + std::vector tile_map_; // Indice de los tiles a dibujar en la habitación (embebido desde YAML) + int conveyor_belt_direction_{0}; // Sentido en el que arrastran las superficies automáticas de la habitación + bool is_paused_{false}; // Indica si el mapa esta en modo pausa + int tile_set_width_{0}; // Ancho del tileset en tiles // --- Funciones --- void initializeRoom(const Data& room); // Inicializa los valores diff --git a/source/game/gameplay/room_loader.cpp b/source/game/gameplay/room_loader.cpp index 4830268..9126656 100644 --- a/source/game/gameplay/room_loader.cpp +++ b/source/game/gameplay/room_loader.cpp @@ -2,9 +2,9 @@ #include // Para exception #include // Para cout, cerr -#include "external/fkyaml_node.hpp" // Para fkyaml::node #include "core/resources/resource_helper.hpp" // Para Resource::Helper +#include "external/fkyaml_node.hpp" // Para fkyaml::node #include "utils/defines.hpp" // Para Tile::SIZE #include "utils/utils.hpp" // Para stringToColor diff --git a/source/game/gameplay/stats.hpp b/source/game/gameplay/stats.hpp index 232a2cb..51fe842 100644 --- a/source/game/gameplay/stats.hpp +++ b/source/game/gameplay/stats.hpp @@ -18,10 +18,10 @@ class Stats { // Variables std::vector dictionary_; // Lista con la equivalencia nombre-numero de habitacion - std::vector buffer_list_; // Lista con las estadisticas temporales por habitación - std::vector list_; // Lista con las estadisticas completas por habitación - std::string buffer_path_; // Fichero con las estadísticas temporales - std::string file_path_; // Fichero con las estadísticas completas + std::vector buffer_list_; // Lista con las estadisticas temporales por habitación + std::vector list_; // Lista con las estadisticas completas por habitación + std::string buffer_path_; // Fichero con las estadísticas temporales + std::string file_path_; // Fichero con las estadísticas completas // Busca una entrada en la lista por nombre static auto findByName(const std::string& name, const std::vector& list) -> int; diff --git a/source/game/scene_manager.hpp b/source/game/scene_manager.hpp index 62e79ae..9ee627a 100644 --- a/source/game/scene_manager.hpp +++ b/source/game/scene_manager.hpp @@ -34,7 +34,7 @@ enum class Options { // --- Variables de estado globales --- #ifdef _DEBUG -inline Scene current = Scene::GAME; // Escena actual +inline Scene current = Scene::GAME; // Escena actual inline Options options = Options::LOGO_TO_LOADING_SCREEN; // Opciones de la escena actual #else inline Scene current = Scene::LOGO; // Escena actual diff --git a/source/game/scenes/ending.cpp b/source/game/scenes/ending.cpp index 736fc8a..9622141 100644 --- a/source/game/scenes/ending.cpp +++ b/source/game/scenes/ending.cpp @@ -25,23 +25,13 @@ Ending::Ending() SceneManager::current = SceneManager::Scene::ENDING; SceneManager::options = SceneManager::Options::NONE; - // Inicializa los textos - iniTexts(); + iniTexts(); // Inicializa los textos + iniPics(); // Inicializa las imagenes + iniScenes(); // Inicializa las escenas - // Inicializa las imagenes - iniPics(); - - // Inicializa las escenas - iniScenes(); - - // Cambia el color del borde - Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); - - // Crea la textura para cubrir el texto - cover_surface_ = std::make_shared(Options::game.width, Options::game.height + 8); - - // Rellena la textura para la cortinilla - fillCoverTexture(); + Screen::get()->setBorderColor(static_cast(PaletteColor::BLACK)); // Cambia el color del borde + cover_surface_ = std::make_shared(Options::game.width, Options::game.height + 8); // Crea la textura para cubrir el texto + fillCoverTexture(); // Rellena la textura para la cortinilla } // Actualiza el objeto @@ -446,55 +436,55 @@ void Ending::updateSpriteCovers() { const float PIXELS_REVEALED = TIME_SINCE_TRIGGER * TEXT_REVEAL_SPEED; // Obtiene el sprite - auto SPRITE_TEXT = sprite_texts_.at(ti.index); + auto sprite_text = sprite_texts_.at(ti.index); // Obtener altura inicial de la superficie - const float INITIAL_HEIGHT = SPRITE_TEXT.image_surface->getHeight(); - const float Y_INITIAL = SPRITE_TEXT.image_sprite->getY(); + const float INITIAL_HEIGHT = sprite_text.image_surface->getHeight(); + const float Y_INITIAL = sprite_text.image_sprite->getY(); // Fase 1: Revelar malla decorativa (8 píxeles) if (PIXELS_REVEALED < 8.0F) { - SPRITE_TEXT.cover_clip_desp = static_cast(8.0F - PIXELS_REVEALED); - SPRITE_TEXT.cover_clip_height = static_cast(INITIAL_HEIGHT); - SPRITE_TEXT.cover_sprite->setY(Y_INITIAL); + sprite_text.cover_clip_desp = static_cast(8.0F - PIXELS_REVEALED); + sprite_text.cover_clip_height = static_cast(INITIAL_HEIGHT); + sprite_text.cover_sprite->setY(Y_INITIAL); } // Fase 2: Revelar contenido else { - SPRITE_TEXT.cover_clip_desp = 0; + sprite_text.cover_clip_desp = 0; const int CONTENT_PIXELS = PIXELS_REVEALED - 8.0F; - SPRITE_TEXT.cover_clip_height = std::max(0, static_cast(INITIAL_HEIGHT - CONTENT_PIXELS)); - SPRITE_TEXT.cover_sprite->setY(Y_INITIAL + static_cast(CONTENT_PIXELS)); + sprite_text.cover_clip_height = std::max(0, static_cast(INITIAL_HEIGHT - CONTENT_PIXELS)); + sprite_text.cover_sprite->setY(Y_INITIAL + static_cast(CONTENT_PIXELS)); } - SPRITE_TEXT.cover_sprite->setClip( + sprite_text.cover_sprite->setClip( 0, - SPRITE_TEXT.cover_clip_desp, - SPRITE_TEXT.cover_sprite->getWidth(), - SPRITE_TEXT.cover_clip_height); + sprite_text.cover_clip_desp, + sprite_text.cover_sprite->getWidth(), + sprite_text.cover_clip_height); } } // Actualiza la cortinilla de las imágenes (revelación continua desde el inicio de la escena) - auto SPRITE_PICS = sprite_pics_.at(current_scene_); + auto sprite_pics = sprite_pics_.at(current_scene_); const float PIXELS_REVEALED = state_time_ * IMAGE_REVEAL_SPEED; - const float INITIAL_HEIGHT = SPRITE_PICS.image_surface->getHeight(); - const float Y_INITIAL = SPRITE_PICS.image_sprite->getY(); + const float INITIAL_HEIGHT = sprite_pics.image_surface->getHeight(); + const float Y_INITIAL = sprite_pics.image_sprite->getY(); // Fase 1: Revelar malla decorativa (8 píxeles) if (PIXELS_REVEALED < 8.0F) { - SPRITE_PICS.cover_clip_desp = static_cast(8.0F - PIXELS_REVEALED); - SPRITE_PICS.cover_clip_height = static_cast(INITIAL_HEIGHT); - SPRITE_PICS.cover_sprite->setY(Y_INITIAL); + sprite_pics.cover_clip_desp = static_cast(8.0F - PIXELS_REVEALED); + sprite_pics.cover_clip_height = static_cast(INITIAL_HEIGHT); + sprite_pics.cover_sprite->setY(Y_INITIAL); } // Fase 2: Revelar contenido else { - SPRITE_PICS.cover_clip_desp = 0; + sprite_pics.cover_clip_desp = 0; const int CONTENT_PIXELS = PIXELS_REVEALED - 8.0F; - SPRITE_PICS.cover_clip_height = std::max(0, static_cast(INITIAL_HEIGHT - CONTENT_PIXELS)); - SPRITE_PICS.cover_sprite->setY(Y_INITIAL + static_cast(CONTENT_PIXELS)); + sprite_pics.cover_clip_height = std::max(0, static_cast(INITIAL_HEIGHT - CONTENT_PIXELS)); + sprite_pics.cover_sprite->setY(Y_INITIAL + static_cast(CONTENT_PIXELS)); } - SPRITE_PICS.cover_sprite->setClip(0, SPRITE_PICS.cover_clip_desp, SPRITE_PICS.cover_sprite->getWidth(), SPRITE_PICS.cover_clip_height); + sprite_pics.cover_sprite->setClip(0, sprite_pics.cover_clip_desp, sprite_pics.cover_sprite->getWidth(), sprite_pics.cover_clip_height); } // Comprueba si se ha de cambiar de escena diff --git a/source/game/scenes/ending.hpp b/source/game/scenes/ending.hpp index 6386c21..b758b24 100644 --- a/source/game/scenes/ending.hpp +++ b/source/game/scenes/ending.hpp @@ -87,16 +87,16 @@ class Ending { // --- Variables miembro --- // Objetos y punteros a recursos - std::shared_ptr cover_surface_; // Surface para cubrir el texto - std::unique_ptr delta_timer_; // Timer para time-based update - std::vector sprite_texts_; // Vector con los sprites de texto con su cortinilla - std::vector sprite_pics_; // Vector con los sprites de imágenes con su cortinilla - std::vector scenes_; // Vector con los textos e imágenes de cada escena + std::shared_ptr cover_surface_; // Surface para cubrir el texto + std::unique_ptr delta_timer_; // Timer para time-based update + std::vector sprite_texts_; // Vector con los sprites de texto con su cortinilla + std::vector sprite_pics_; // Vector con los sprites de imágenes con su cortinilla + std::vector scenes_; // Vector con los textos e imágenes de cada escena // Variables de estado - State state_{State::WARMING_UP}; // Estado actual - float state_time_{0.0F}; // Tiempo acumulado en el estado actual - float total_time_{0.0F}; // Tiempo total acumulado desde el inicio - float fadeout_time_{0.0F}; // Tiempo acumulado para el fade-out - int current_scene_{0}; // Escena actual (0-4) + State state_{State::WARMING_UP}; // Estado actual + float state_time_{0.0F}; // Tiempo acumulado en el estado actual + float total_time_{0.0F}; // Tiempo total acumulado desde el inicio + float fadeout_time_{0.0F}; // Tiempo acumulado para el fade-out + int current_scene_{0}; // Escena actual (0-4) }; \ No newline at end of file diff --git a/source/game/scenes/game.cpp b/source/game/scenes/game.cpp index 4900ec4..ae3094e 100644 --- a/source/game/scenes/game.cpp +++ b/source/game/scenes/game.cpp @@ -82,13 +82,21 @@ void Game::handleEvents() { void Game::handleInput() { Input::get()->update(); + // Inputs globales siempre funcionan if (Input::get()->checkAction(InputAction::TOGGLE_MUSIC, Input::DO_NOT_ALLOW_REPEAT)) { board_->music = !board_->music; board_->music ? Audio::get()->resumeMusic() : Audio::get()->pauseMusic(); Notifier::get()->show({"MUSIC " + std::string(board_->music ? "ENABLED" : "DISABLED")}); } - else if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) { + // Durante fade/postfade, solo procesar inputs globales + if (state_ != State::PLAYING) { + GlobalInputs::handle(); + return; + } + + // Input de pausa solo en estado PLAYING + if (Input::get()->checkAction(InputAction::PAUSE, Input::DO_NOT_ALLOW_REPEAT)) { togglePause(); Notifier::get()->show({std::string(paused_ ? "GAME PAUSED" : "GAME RUNNING")}); } @@ -124,28 +132,18 @@ void Game::update() { Debug::get()->clear(); #endif - // Actualiza los objetos - room_->update(DELTA_TIME); - switch (mode_) { - case Mode::GAME: - player_->update(DELTA_TIME); - checkPlayerIsOnBorder(); - checkPlayerAndItems(); - checkPlayerAndEnemies(); - checkIfPlayerIsAlive(); - checkGameOver(); - checkEndGame(); - checkRestoringJail(DELTA_TIME); - checkSomeCheevos(); + // Dispatch por estado + switch (state_) { + case State::PLAYING: + updatePlaying(DELTA_TIME); break; - - case Mode::DEMO: - demoCheckRoomChange(DELTA_TIME); + case State::FADE_TO_ENDING: + updateFadeToEnding(DELTA_TIME); + break; + case State::POST_FADE_ENDING: + updatePostFadeEnding(DELTA_TIME); break; } - scoreboard_->update(DELTA_TIME); - keepMusicPlaying(); - updateBlackScreen(DELTA_TIME); Audio::update(); // Actualiza el objeto Audio Screen::get()->update(DELTA_TIME); // Actualiza el objeto Screen @@ -155,6 +153,73 @@ void Game::update() { #endif } +// Actualiza el juego en estado PLAYING +void Game::updatePlaying(float delta_time) { + // Actualiza los objetos + room_->update(delta_time); + switch (mode_) { + case Mode::GAME: + player_->update(delta_time); + checkPlayerIsOnBorder(); + checkPlayerAndItems(); + checkPlayerAndEnemies(); + checkIfPlayerIsAlive(); + checkGameOver(); + checkEndGame(); + checkRestoringJail(delta_time); + checkSomeCheevos(); + break; + + case Mode::DEMO: + demoCheckRoomChange(delta_time); + break; + } + scoreboard_->update(delta_time); + keepMusicPlaying(); + updateBlackScreen(delta_time); +} + +// Actualiza el juego en estado FADE_TO_ENDING +void Game::updateFadeToEnding(float delta_time) { + // Actualiza room, enemies, items (todo sigue funcionando) + room_->update(delta_time); + + // NO actualizar player (congelar movimiento) + // player_->update(delta_time); -- COMENTADO INTENCIONALMENTE + + // Actualiza scoreboard + scoreboard_->update(delta_time); + keepMusicPlaying(); + + // Aplica el fade progresivo + fade_accumulator_ += delta_time; + if (fade_accumulator_ >= FADE_STEP_INTERVAL) { + fade_accumulator_ = 0.0F; + if (Screen::get()->getRendererSurface()->fadeSubPalette()) { + // Fade completado, transicionar a POST_FADE + transitionToState(State::POST_FADE_ENDING); + } + } +} + +// Actualiza el juego en estado POST_FADE_ENDING +void Game::updatePostFadeEnding(float delta_time) { + // Pantalla negra estática, acumular tiempo + state_time_ += delta_time; + + // Después del delay, cambiar a la escena de ending + if (state_time_ >= POST_FADE_DELAY) { + SceneManager::current = SceneManager::Scene::ENDING; + } +} + +// Cambia al estado especificado y resetea los timers +void Game::transitionToState(State new_state) { + state_ = new_state; + state_time_ = 0.0F; + fade_accumulator_ = 0.0F; +} + // Pinta los objetos en pantalla void Game::render() { // Prepara para dibujar el frame @@ -434,7 +499,9 @@ auto Game::checkEndGame() -> bool { // Comprueba los logros de completar el juego checkEndGameCheevos(); - SceneManager::current = SceneManager::Scene::ENDING; + // Iniciar transición de fade en vez de cambio inmediato de escena + transitionToState(State::FADE_TO_ENDING); + Audio::get()->fadeOutMusic(1000); // Fade out de música en 1 segundo return true; } diff --git a/source/game/scenes/game.hpp b/source/game/scenes/game.hpp index b187afe..ecc8762 100644 --- a/source/game/scenes/game.hpp +++ b/source/game/scenes/game.hpp @@ -23,6 +23,12 @@ class Game { GAME }; + enum class State { + PLAYING, // Normal gameplay + FADE_TO_ENDING, // Fade out transition + POST_FADE_ENDING, // Black screen delay before ending + }; + // --- Constructor y Destructor --- explicit Game(Mode mode); ~Game(); @@ -36,12 +42,14 @@ class Game { static constexpr float GAME_OVER_THRESHOLD = 0.255F; // Tiempo antes del game over en segundos (17 frames a 66.67fps) static constexpr float DEMO_ROOM_DURATION = 6.0F; // Duración de cada habitación en modo demo en segundos (400 frames) static constexpr float JAIL_RESTORE_INTERVAL = 1.5F; // Intervalo de restauración de vidas en la Jail en segundos (100 frames) + static constexpr float FADE_STEP_INTERVAL = 0.05F; // Intervalo entre pasos de fade en segundos + static constexpr float POST_FADE_DELAY = 1.0F; // Duración de la pantalla negra después del fade // --- Estructuras --- struct DemoData { - float time_accumulator{0.0F}; // Acumulador de tiempo para el modo demo - int room_index{0}; // Índice para el vector de habitaciones - std::vector rooms; // Listado con los mapas de la demo + float time_accumulator{0.0F}; // Acumulador de tiempo para el modo demo + int room_index{0}; // Índice para el vector de habitaciones + std::vector rooms; // Listado con los mapas de la demo }; // --- Métodos --- @@ -49,6 +57,10 @@ class Game { void render(); // Pinta los objetos en pantalla void handleEvents(); // Comprueba los eventos de la cola void renderRoomName(); // Escribe el nombre de la pantalla + void transitionToState(State new_state); // Cambia al estado especificado y resetea los timers + void updatePlaying(float delta_time); // Actualiza el juego en estado PLAYING + void updateFadeToEnding(float delta_time); // Actualiza el juego en estado FADE_TO_ENDING + void updatePostFadeEnding(float delta_time); // Actualiza el juego en estado POST_FADE_ENDING auto changeRoom(const std::string& room_path) -> bool; // Cambia de habitación void handleInput(); // Comprueba el teclado void checkPlayerIsOnBorder(); // Comprueba si el jugador esta en el borde de la pantalla y actua @@ -92,11 +104,14 @@ class Game { // Variables de estado del juego Mode mode_; // Modo del juego + State state_{State::PLAYING}; // Estado actual de la escena DeltaTimer delta_timer_; // Timer para calcular delta time std::string current_room_; // Fichero de la habitación actual Player::SpawnData spawn_data_; // Lugar de la habitación donde aparece el jugador int total_items_; // Cantidad total de items que hay en el mapeado del juego bool paused_{false}; // Indica si el juego se encuentra en pausa + float state_time_{0.0F}; // Tiempo acumulado en el estado actual + float fade_accumulator_{0.0F}; // Acumulador de tiempo para el fade // Variables de demo mode DemoData demo_; // Variables para el modo demo diff --git a/source/game/scenes/game_over.hpp b/source/game/scenes/game_over.hpp index 52804cf..5b2f1ac 100644 --- a/source/game/scenes/game_over.hpp +++ b/source/game/scenes/game_over.hpp @@ -60,10 +60,10 @@ class GameOver { std::shared_ptr delta_timer_; // Timer para time-based logic // Variables de estado de la escena - State state_{State::WAITING}; // Estado actual de la escena - float elapsed_time_{0.0F}; // Tiempo transcurrido en el estado actual + State state_{State::WAITING}; // Estado actual de la escena + float elapsed_time_{0.0F}; // Tiempo transcurrido en el estado actual // Variables de efectos visuales - std::vector colors_; // Vector con los colores para el fade - Uint8 color_{0}; // Color actual para texto y sprites + std::vector colors_; // Vector con los colores para el fade + Uint8 color_{0}; // Color actual para texto y sprites }; \ No newline at end of file diff --git a/source/game/scenes/loading_screen.hpp b/source/game/scenes/loading_screen.hpp index 88a3e8a..2ad2234 100644 --- a/source/game/scenes/loading_screen.hpp +++ b/source/game/scenes/loading_screen.hpp @@ -61,7 +61,7 @@ class LoadingScreen { // --- Constantes de tiempo (en segundos) --- static constexpr float SILENT1_DURATION = 2.0F; // Pausa inicial static constexpr float HEADER1_DURATION = 4.0F; // Cabecera - static constexpr float DATA1_DURATION = 0.18F; // Datos + static constexpr float DATA1_DURATION = 0.18F; // Datos static constexpr float SILENT2_DURATION = 1.6F; // Segunda pausa static constexpr float HEADER2_DURATION = 2.0F; // Cabecera pantalla static constexpr float LOADING_MONO_DURATION = 16.0F; // Duración total de la carga monocromática @@ -107,17 +107,17 @@ class LoadingScreen { std::unique_ptr delta_timer_; // Timer para delta time // Variables de estado de la secuencia - State state_{State::SILENT1}; // Estado actual de la secuencia - float state_time_{0.0F}; // Tiempo acumulado en el estado actual - Border current_border_type_{Border::NONE}; // Tipo de borde actual + State state_{State::SILENT1}; // Estado actual de la secuencia + float state_time_{0.0F}; // Tiempo acumulado en el estado actual + Border current_border_type_{Border::NONE}; // Tipo de borde actual // Arrays y estructuras auxiliares - std::array line_index_; // El orden en el que se procesan las 192 líneas de la pantalla de carga - SDL_FRect load_rect_{0.0F, 0.0F, 0.0F, 1.0F}; // Rectángulo para dibujar la pantalla de carga - Carrier carrier_; // Estructura para los efectos de la carga de cabeceras - Noise noise_; // Variaciones de ruido durante los silencios + std::array line_index_; // El orden en el que se procesan las 192 líneas de la pantalla de carga + SDL_FRect load_rect_{0.0F, 0.0F, 0.0F, 1.0F}; // Rectángulo para dibujar la pantalla de carga + Carrier carrier_; // Estructura para los efectos de la carga de cabeceras + Noise noise_; // Variaciones de ruido durante los silencios // Variables de seguimiento para evitar saltos de pasos/bloques - int last_mono_step_{-1}; // Último paso mono dibujado - int last_color_block_{-1}; // Último bloque color dibujado + int last_mono_step_{-1}; // Último paso mono dibujado + int last_color_block_{-1}; // Último bloque color dibujado }; \ No newline at end of file diff --git a/source/game/scenes/logo.hpp b/source/game/scenes/logo.hpp index e0346c2..9fd4d84 100644 --- a/source/game/scenes/logo.hpp +++ b/source/game/scenes/logo.hpp @@ -44,35 +44,35 @@ class Logo { static constexpr int JAILGAMES_DEST_X = 37; // Posición X de destino para JAILGAMES // --- Métodos --- - void update(); // Actualiza las variables - void render(); // Dibuja en pantalla - static void handleEvents(); // Comprueba el manejador de eventos - static void handleInput(); // Comprueba las entradas - void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based) - void updateTextureColors(); // Gestiona el color de las texturas - void updateState(float delta_time); // Actualiza el estado actual - void transitionToState(State new_state); // Transiciona a un nuevo estado - [[nodiscard]] auto getColorIndex(float progress) const -> int; // Calcula el índice de color según el progreso (0.0-1.0) - static void endSection(); // Termina la sección - void initColors(); // Inicializa el vector de colores - void initSprites(); // Crea los sprites de cada linea + void update(); // Actualiza las variables + void render(); // Dibuja en pantalla + static void handleEvents(); // Comprueba el manejador de eventos + static void handleInput(); // Comprueba las entradas + void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAME (time-based) + void updateTextureColors(); // Gestiona el color de las texturas + void updateState(float delta_time); // Actualiza el estado actual + void transitionToState(State new_state); // Transiciona a un nuevo estado + [[nodiscard]] auto getColorIndex(float progress) const -> int; // Calcula el índice de color según el progreso (0.0-1.0) + static void endSection(); // Termina la sección + void initColors(); // Inicializa el vector de colores + void initSprites(); // Crea los sprites de cada linea // --- Variables miembro --- // Objetos y punteros a recursos - std::shared_ptr jailgames_surface_; // Textura con los graficos "JAILGAMES" - std::shared_ptr since_1998_surface_; // Textura con los graficos "Since 1998" - std::vector> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES - std::vector jailgames_initial_x_; // Posiciones X iniciales de cada línea (para interpolación con easing) - std::shared_ptr since_1998_sprite_; // SSprite para manejar la textura2 - std::unique_ptr delta_timer_; // Timer para delta time + std::shared_ptr jailgames_surface_; // Textura con los graficos "JAILGAMES" + std::shared_ptr since_1998_surface_; // Textura con los graficos "Since 1998" + std::vector> jailgames_sprite_; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES + std::vector jailgames_initial_x_; // Posiciones X iniciales de cada línea (para interpolación con easing) + std::shared_ptr since_1998_sprite_; // SSprite para manejar la textura2 + std::unique_ptr delta_timer_; // Timer para delta time // Variables de estado de colores - std::vector color_; // Vector con los colores para el fade - Uint8 jailgames_color_{0}; // Color para el sprite de "JAILGAMES" - Uint8 since_1998_color_{0}; // Color para el sprite de "Since 1998" + std::vector color_; // Vector con los colores para el fade + Uint8 jailgames_color_{0}; // Color para el sprite de "JAILGAMES" + Uint8 since_1998_color_{0}; // Color para el sprite de "Since 1998" // Variables de estado de la secuencia - State state_{State::INITIAL}; // Estado actual de la secuencia - float state_time_{0.0F}; // Tiempo acumulado en el estado actual - EasingFunction easing_function_; // Función de easing para la animación del logo + State state_{State::INITIAL}; // Estado actual de la secuencia + float state_time_{0.0F}; // Tiempo acumulado en el estado actual + EasingFunction easing_function_; // Función de easing para la animación del logo }; \ No newline at end of file diff --git a/source/game/scenes/title.hpp b/source/game/scenes/title.hpp index 7420554..61bbf74 100644 --- a/source/game/scenes/title.hpp +++ b/source/game/scenes/title.hpp @@ -122,12 +122,12 @@ class Title { SceneManager::Scene exit_scene_{SceneManager::Scene::GAME}; // Escena de destino al salir del título // Variables para redefinir controles - bool is_remapping_keyboard_{false}; // True si estamos redefiniendo teclado - bool is_remapping_joystick_{false}; // True si estamos redefiniendo joystick - int remap_step_{0}; // Paso actual en la redefinicion (0=LEFT, 1=RIGHT, 2=JUMP) - std::array temp_keys_; // Almacenamiento temporal de teclas capturadas - std::array temp_buttons_; // Almacenamiento temporal de botones de gamepad capturados - std::string remap_error_message_; // Mensaje de error si la tecla/boton es invalido - float axis_cooldown_{0.0F}; // Cooldown para evitar múltiples capturas de ejes - bool remap_completed_{false}; // True cuando se completa el remap (mostrar antes de guardar) + bool is_remapping_keyboard_{false}; // True si estamos redefiniendo teclado + bool is_remapping_joystick_{false}; // True si estamos redefiniendo joystick + int remap_step_{0}; // Paso actual en la redefinicion (0=LEFT, 1=RIGHT, 2=JUMP) + std::array temp_keys_; // Almacenamiento temporal de teclas capturadas + std::array temp_buttons_; // Almacenamiento temporal de botones de gamepad capturados + std::string remap_error_message_; // Mensaje de error si la tecla/boton es invalido + float axis_cooldown_{0.0F}; // Cooldown para evitar múltiples capturas de ejes + bool remap_completed_{false}; // True cuando se completa el remap (mostrar antes de guardar) }; \ No newline at end of file diff --git a/source/utils/easing_functions.hpp b/source/utils/easing_functions.hpp index 649a6ba..068aff1 100644 --- a/source/utils/easing_functions.hpp +++ b/source/utils/easing_functions.hpp @@ -248,4 +248,4 @@ inline auto bounceInOut(float t) -> float { return (0.5F * bounceOut((2.0F * t) - 1.0F)) + 0.5F; } -} // namespace Easing +} // namespace Easing diff --git a/source/utils/utils.hpp b/source/utils/utils.hpp index 8d575aa..fb1b06f 100644 --- a/source/utils/utils.hpp +++ b/source/utils/utils.hpp @@ -74,41 +74,41 @@ struct Color { }; // COLISIONES Y GEOMETRÍA -auto distanceSquared(int x1, int y1, int x2, int y2) -> double; // Distancia² entre dos puntos -auto checkCollision(const Circle& a, const Circle& b) -> bool; // Colisión círculo-círculo -auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool; // Colisión círculo-rectángulo -auto checkCollision(const SDL_FRect& a, const SDL_FRect& b) -> bool; // Colisión rectángulo-rectángulo -auto checkCollision(const SDL_FPoint& p, const SDL_FRect& r) -> bool; // Colisión punto-rectángulo -auto checkCollision(const LineHorizontal& l, const SDL_FRect& r) -> bool; // Colisión línea horizontal-rectángulo -auto checkCollision(const LineVertical& l, const SDL_FRect& r) -> bool; // Colisión línea vertical-rectángulo -auto checkCollision(const LineHorizontal& l, const SDL_FPoint& p) -> bool; // Colisión línea horizontal-punto -auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point; // Colisión línea-línea (intersección) +auto distanceSquared(int x1, int y1, int x2, int y2) -> double; // Distancia² entre dos puntos +auto checkCollision(const Circle& a, const Circle& b) -> bool; // Colisión círculo-círculo +auto checkCollision(const Circle& a, const SDL_FRect& rect) -> bool; // Colisión círculo-rectángulo +auto checkCollision(const SDL_FRect& a, const SDL_FRect& b) -> bool; // Colisión rectángulo-rectángulo +auto checkCollision(const SDL_FPoint& p, const SDL_FRect& r) -> bool; // Colisión punto-rectángulo +auto checkCollision(const LineHorizontal& l, const SDL_FRect& r) -> bool; // Colisión línea horizontal-rectángulo +auto checkCollision(const LineVertical& l, const SDL_FRect& r) -> bool; // Colisión línea vertical-rectángulo +auto checkCollision(const LineHorizontal& l, const SDL_FPoint& p) -> bool; // Colisión línea horizontal-punto +auto checkCollision(const Line& l1, const Line& l2) -> SDL_Point; // Colisión línea-línea (intersección) auto checkCollision(const LineDiagonal& l1, const LineVertical& l2) -> SDL_Point; // Colisión diagonal-vertical -auto checkCollision(const SDL_FPoint& p, const LineDiagonal& l) -> bool; // Colisión punto-diagonal -void normalizeLine(LineDiagonal& l); // Normaliza línea diagonal (x1 < x2) +auto checkCollision(const SDL_FPoint& p, const LineDiagonal& l) -> bool; // Colisión punto-diagonal +void normalizeLine(LineDiagonal& l); // Normaliza línea diagonal (x1 < x2) // CONVERSIONES DE TIPOS SDL -auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect; // Convierte SDL_FRect a SDL_Rect -auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point; // Convierte SDL_FPoint a SDL_Point +auto toSDLRect(const SDL_FRect& frect) -> SDL_Rect; // Convierte SDL_FRect a SDL_Rect +auto toSDLPoint(const SDL_FPoint& fpoint) -> SDL_Point; // Convierte SDL_FPoint a SDL_Point // CONVERSIONES DE STRING -auto stringToColor(const std::string& str) -> Uint8; // String a índice de paleta -auto safeStoi(const std::string& value, int default_value = 0) -> int; // String a int seguro (sin excepciones) -auto stringToBool(const std::string& str) -> bool; // String a bool (true/1/yes/on) -auto boolToString(bool value) -> std::string; // Bool a string (1/0) -auto toLower(const std::string& str) -> std::string; // String a minúsculas -auto toUpper(const std::string& str) -> std::string; // String a mayúsculas +auto stringToColor(const std::string& str) -> Uint8; // String a índice de paleta +auto safeStoi(const std::string& value, int default_value = 0) -> int; // String a int seguro (sin excepciones) +auto stringToBool(const std::string& str) -> bool; // String a bool (true/1/yes/on) +auto boolToString(bool value) -> std::string; // Bool a string (1/0) +auto toLower(const std::string& str) -> std::string; // String a minúsculas +auto toUpper(const std::string& str) -> std::string; // String a mayúsculas // OPERACIONES CON STRINGS auto stringInVector(const std::vector& vec, const std::string& str) -> bool; // Busca string en vector -auto spaceBetweenLetters(const std::string& input) -> std::string; // Añade espacios entre letras +auto spaceBetweenLetters(const std::string& input) -> std::string; // Añade espacios entre letras // OPERACIONES CON COLORES -auto colorAreEqual(Color color1, Color color2) -> bool; // Compara dos colores RGB +auto colorAreEqual(Color color1, Color color2) -> bool; // Compara dos colores RGB // OPERACIONES CON FICHEROS -auto getFileName(const std::string& path) -> std::string; // Extrae nombre de fichero de ruta -auto getPath(const std::string& full_path) -> std::string; // Extrae directorio de ruta completa +auto getFileName(const std::string& path) -> std::string; // Extrae nombre de fichero de ruta +auto getPath(const std::string& full_path) -> std::string; // Extrae directorio de ruta completa // RENDERIZADO void fillTextureWithColor(SDL_Renderer* renderer, SDL_Texture* texture, Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Rellena textura