clang-tidy modernize

This commit is contained in:
2025-07-20 14:10:54 +02:00
parent 1f0184fde2
commit f5245273a1
22 changed files with 514 additions and 481 deletions

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_FPoint, SDL_Texture, SDL_Renderer
#include <array>
#include <cstddef> // Para size_t
#include <memory> // Para unique_ptr, shared_ptr
#include <vector> // Para vector
@@ -27,87 +28,87 @@ class Texture;
*/
class Background {
public:
// Constructor y Destructor
Background();
~Background();
public:
// Constructor y Destructor
Background();
~Background();
// Actualización y renderizado
void update(); // Actualiza la lógica del objeto
void render(); // Dibuja el objeto
// Actualización y renderizado
void update(); // Actualiza la lógica del objeto
void render(); // Dibuja el objeto
// Configuración de posición
void setPos(SDL_FRect pos); // Establece la posición del objeto
// Configuración de posición
void setPos(SDL_FRect pos); // Establece la posición del objeto
// Configuración de animaciones y efectos
void setCloudsSpeed(float value); // Ajusta la velocidad de desplazamiento de las nubes
void setGradientNumber(int value); // Establece el degradado de fondo a usar
void setTransition(float value); // Ajusta la transición entre texturas de fondo
// Configuración de animaciones y efectos
void setCloudsSpeed(float value); // Ajusta la velocidad de desplazamiento de las nubes
void setGradientNumber(int value); // Establece el degradado de fondo a usar
void setTransition(float value); // Ajusta la transición entre texturas de fondo
// Configuración de efectos visuales
void setColor(Color color); // Establece el color de atenuación
void setAlpha(int alpha); // Ajusta la transparencia del fondo
// Configuración de efectos visuales
void setColor(Color color); // Establece el color de atenuación
void setAlpha(int alpha); // Ajusta la transparencia del fondo
// Configuración del sol y la luna
void setSunProgression(float progress); // Establece la posición del sol
void setMoonProgression(float progress); // Establece la posición de la luna
// Configuración del sol y la luna
void setSunProgression(float progress); // Establece la posición del sol
void setMoonProgression(float progress); // Establece la posición de la luna
private:
// Objetos y punteros
SDL_Renderer *renderer_; // Renderizador de la ventana
private:
// Objetos y punteros
SDL_Renderer *renderer_; // Renderizador de la ventana
// Texturas
std::shared_ptr<Texture> buildings_texture_;
std::shared_ptr<Texture> top_clouds_texture_;
std::shared_ptr<Texture> bottom_clouds_texture_;
std::shared_ptr<Texture> grass_texture_;
std::shared_ptr<Texture> gradients_texture_;
std::shared_ptr<Texture> sun_texture_;
std::shared_ptr<Texture> moon_texture_;
// Texturas
std::shared_ptr<Texture> buildings_texture_;
std::shared_ptr<Texture> top_clouds_texture_;
std::shared_ptr<Texture> bottom_clouds_texture_;
std::shared_ptr<Texture> grass_texture_;
std::shared_ptr<Texture> gradients_texture_;
std::shared_ptr<Texture> sun_texture_;
std::shared_ptr<Texture> moon_texture_;
// Sprites
std::unique_ptr<MovingSprite> top_clouds_sprite_a_;
std::unique_ptr<MovingSprite> top_clouds_sprite_b_;
std::unique_ptr<MovingSprite> bottom_clouds_sprite_a_;
std::unique_ptr<MovingSprite> bottom_clouds_sprite_b_;
std::unique_ptr<Sprite> buildings_sprite_;
std::unique_ptr<Sprite> gradient_sprite_;
std::unique_ptr<Sprite> grass_sprite_;
std::unique_ptr<Sprite> sun_sprite_;
std::unique_ptr<Sprite> moon_sprite_;
// Sprites
std::unique_ptr<MovingSprite> top_clouds_sprite_a_;
std::unique_ptr<MovingSprite> top_clouds_sprite_b_;
std::unique_ptr<MovingSprite> bottom_clouds_sprite_a_;
std::unique_ptr<MovingSprite> bottom_clouds_sprite_b_;
std::unique_ptr<Sprite> buildings_sprite_;
std::unique_ptr<Sprite> gradient_sprite_;
std::unique_ptr<Sprite> grass_sprite_;
std::unique_ptr<Sprite> sun_sprite_;
std::unique_ptr<Sprite> moon_sprite_;
// Buffers de renderizado
SDL_Texture *canvas_; // Textura para componer el fondo
SDL_Texture *color_texture_; // Textura para atenuar el fondo
// Buffers de renderizado
SDL_Texture *canvas_; // Textura para componer el fondo
SDL_Texture *color_texture_; // Textura para atenuar el fondo
// Variables de control
SDL_FRect gradient_rect_[4];
SDL_FRect top_clouds_rect_[4];
SDL_FRect bottom_clouds_rect_[4];
int gradient_number_ = 0;
int alpha_ = 0;
float clouds_speed_ = 0;
float transition_ = 0;
int counter_ = 0;
SDL_FRect rect_;
SDL_FRect src_rect_;
SDL_FRect dst_rect_;
int base_;
Color attenuate_color_;
int alpha_color_text_;
int alpha_color_text_temp_;
std::vector<SDL_FPoint> sun_path_;
std::vector<SDL_FPoint> moon_path_;
size_t sun_index_ = 0;
size_t moon_index_ = 0;
// Variables de control
std::array<SDL_FRect, 4> gradient_rect_;
std::array<SDL_FRect, 4> top_clouds_rect_;
std::array<SDL_FRect, 4> bottom_clouds_rect_;
int gradient_number_ = 0;
int alpha_ = 0;
float clouds_speed_ = 0;
float transition_ = 0;
int counter_ = 0;
SDL_FRect rect_;
SDL_FRect src_rect_;
SDL_FRect dst_rect_;
int base_;
Color attenuate_color_;
int alpha_color_text_;
int alpha_color_text_temp_;
std::vector<SDL_FPoint> sun_path_;
std::vector<SDL_FPoint> moon_path_;
size_t sun_index_ = 0;
size_t moon_index_ = 0;
// Métodos internos
void renderGradient(); // Dibuja el gradiente de fondo
void renderTopClouds(); // Dibuja las nubes superiores
void renderBottomClouds(); // Dibuja las nubes inferiores
void fillCanvas(); // Compone todos los elementos en la textura
void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación
void updateClouds(); // Actualiza el movimiento de las nubes
void createSunPath(); // Precalcula el recorrido del sol
void createMoonPath(); // Precalcula el recorrido de la luna
// Métodos internos
void renderGradient(); // Dibuja el gradiente de fondo
void renderTopClouds(); // Dibuja las nubes superiores
void renderBottomClouds(); // Dibuja las nubes inferiores
void fillCanvas(); // Compone todos los elementos en la textura
void updateAlphaColorTexture(); // Actualiza el alpha de la textura de atenuación
void updateClouds(); // Actualiza el movimiento de las nubes
void createSunPath(); // Precalcula el recorrido del sol
void createMoonPath(); // Precalcula el recorrido de la luna
};

View File

@@ -319,8 +319,8 @@ void Balloon::shiftSprite() {
// Establece el nivel de zoom del sprite
void Balloon::zoomSprite() {
sprite_->setZoomW(bouncing_.zoom_w);
sprite_->setZoomH(bouncing_.zoom_h);
sprite_->setZoomW(bouncing_.horizontal_zoom);
sprite_->setZoomH(bouncing_.verical_zoom);
}
// Activa el efecto
@@ -341,8 +341,8 @@ void Balloon::disableBounce() {
void Balloon::updateBounce() {
if (bouncing_.enabled) {
const int INDEX = bouncing_.counter / bouncing_.speed;
bouncing_.zoom_w = bouncing_.w[INDEX];
bouncing_.zoom_h = bouncing_.h[INDEX];
bouncing_.horizontal_zoom = bouncing_.horizontal_zoom_values[INDEX];
bouncing_.verical_zoom = bouncing_.vertical_zoom_values[INDEX];
zoomSprite();

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para Uint8, Uint16, SDL_FRect, Uint32
#include <array>
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para basic_string, string
#include <vector> // Para vector
@@ -14,12 +15,16 @@ class Texture;
// --- Constantes relacionadas con globos ---
constexpr int MAX_BOUNCE = 10; // Cantidad de elementos del vector de deformación
constexpr int BALLOON_SCORE[] = {50, 100, 200, 400};
constexpr int BALLOON_POWER[] = {1, 3, 7, 15};
constexpr int BALLOON_MENACE[] = {1, 2, 4, 8};
constexpr int BALLOON_SIZE[] = {10, 16, 26, 48, 49};
const std::string BALLOON_BOUNCING_SOUND[] = {"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"};
const std::string BALLOON_POPPING_SOUND[] = {"balloon1.wav", "balloon2.wav", "balloon3.wav", "balloon4.wav"};
constexpr std::array<int, 4> BALLOON_SCORE = {50, 100, 200, 400};
constexpr std::array<int, 4> BALLOON_POWER = {1, 3, 7, 15};
constexpr std::array<int, 4> BALLOON_MENACE = {1, 2, 4, 8};
constexpr std::array<int, 5> BALLOON_SIZE = {10, 16, 26, 48, 49};
const std::array<std::string, 4> BALLOON_BOUNCING_SOUND = {
"bubble1.wav", "bubble2.wav", "bubble3.wav", "bubble4.wav"};
const std::array<std::string, 4> BALLOON_POPPING_SOUND = {
"balloon1.wav", "balloon2.wav", "balloon3.wav", "balloon4.wav"};
enum class BalloonSize : Uint8 {
SIZE1 = 0,
@@ -41,136 +46,136 @@ constexpr int BALLOON_MOVING_ANIMATION = 0;
constexpr int BALLOON_POP_ANIMATION = 1;
constexpr int BALLOON_BORN_ANIMATION = 2;
constexpr float BALLOON_SPEED[] = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f};
constexpr std::array<float, 5> BALLOON_SPEED = {0.60f, 0.70f, 0.80f, 0.90f, 1.00f};
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
constexpr int POWERBALL_COUNTER = 8;
// --- Clase Balloon ---
class Balloon {
public:
// --- Constructores y destructor ---
Balloon(
float x,
float y,
BalloonType type,
BalloonSize size,
float vel_x,
float speed,
Uint16 creation_timer,
SDL_FRect play_area,
std::shared_ptr<Texture> texture,
const std::vector<std::string> &animation);
~Balloon() = default;
public:
// --- Constructores y destructor ---
Balloon(
float x,
float y,
BalloonType type,
BalloonSize size,
float vel_x,
float speed,
Uint16 creation_timer,
SDL_FRect play_area,
std::shared_ptr<Texture> texture,
const std::vector<std::string> &animation);
~Balloon() = default;
// --- Métodos principales ---
void alignTo(int x); // Centra el globo en la posición X
void render(); // Pinta el globo en la pantalla
void move(); // Actualiza la posición y estados del globo
void update(); // Actualiza el globo (posición, animación, contadores)
void stop(); // Detiene el globo
void start(); // Pone el globo en movimiento
void pop(bool should_sound = false); // Explota el globo
// --- Métodos principales ---
void alignTo(int x); // Centra el globo en la posición X
void render(); // Pinta el globo en la pantalla
void move(); // Actualiza la posición y estados del globo
void update(); // Actualiza el globo (posición, animación, contadores)
void stop(); // Detiene el globo
void start(); // Pone el globo en movimiento
void pop(bool should_sound = false); // Explota el globo
// --- Métodos de color ---
void useReverseColor(); // Pone el color alternativo en el globo
void useNormalColor(); // Pone el color normal en el globo
// --- Métodos de color ---
void useReverseColor(); // Pone el color alternativo en el globo
void useNormalColor(); // Pone el color normal en el globo
// --- Getters ---
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getWidth() const -> int { return w_; }
[[nodiscard]] auto getHeight() const -> int { return h_; }
[[nodiscard]] auto getSize() const -> BalloonSize { return size_; }
[[nodiscard]] auto getType() const -> BalloonType { return type_; }
[[nodiscard]] auto getScore() const -> Uint16 { return score_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; }
[[nodiscard]] auto getPower() const -> Uint8 { return power_; }
[[nodiscard]] auto isStopped() const -> bool { return stopped_; }
[[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
auto isUsingReversedColor() -> bool { return use_reversed_colors_; }
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
// --- Getters ---
[[nodiscard]] auto getPosX() const -> float { return x_; }
[[nodiscard]] auto getPosY() const -> float { return y_; }
[[nodiscard]] auto getWidth() const -> int { return w_; }
[[nodiscard]] auto getHeight() const -> int { return h_; }
[[nodiscard]] auto getSize() const -> BalloonSize { return size_; }
[[nodiscard]] auto getType() const -> BalloonType { return type_; }
[[nodiscard]] auto getScore() const -> Uint16 { return score_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getMenace() const -> Uint8 { return isEnabled() ? menace_ : 0; }
[[nodiscard]] auto getPower() const -> Uint8 { return power_; }
[[nodiscard]] auto isStopped() const -> bool { return stopped_; }
[[nodiscard]] auto isPowerBall() const -> bool { return type_ == BalloonType::POWERBALL; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isBeingCreated() const -> bool { return being_created_; }
[[nodiscard]] auto isEnabled() const -> bool { return enabled_; }
auto isUsingReversedColor() -> bool { return use_reversed_colors_; }
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
// --- Setters ---
void setVelY(float vel_y) { vy_ = vel_y; }
void setSpeed(float speed) { speed_ = speed; }
void setInvulnerable(bool value) { invulnerable_ = value; }
void setBouncingSound(bool value) { bouncing_sound_enabled_ = value; }
void setPoppingSound(bool value) { poping_sound_enabled_ = value; }
void setSound(bool value) { sound_enabled_ = value; }
// --- Setters ---
void setVelY(float vel_y) { vy_ = vel_y; }
void setSpeed(float speed) { speed_ = speed; }
void setInvulnerable(bool value) { invulnerable_ = value; }
void setBouncingSound(bool value) { bouncing_sound_enabled_ = value; }
void setPoppingSound(bool value) { poping_sound_enabled_ = value; }
void setSound(bool value) { sound_enabled_ = value; }
private:
// --- Estructura para el efecto de rebote ---
struct Bouncing {
bool enabled = false; // Si el efecto está activo
Uint8 counter = 0; // Contador para el efecto
Uint8 speed = 2; // Velocidad del efecto
float zoom_w = 1.0f; // Zoom en anchura
float zoom_h = 1.0f; // Zoom en altura
float desp_x = 0.0f; // Desplazamiento X antes de pintar
float desp_y = 0.0f; // Desplazamiento Y antes de pintar
private:
// --- Estructura para el efecto de rebote ---
struct Bouncing {
bool enabled = false; // Si el efecto está activo
Uint8 counter = 0; // Contador para el efecto
Uint8 speed = 2; // Velocidad del efecto
float horizontal_zoom = 1.0f; // Zoom en anchura
float verical_zoom = 1.0f; // Zoom en altura
float desp_x = 0.0f; // Desplazamiento X antes de pintar
float desp_y = 0.0f; // Desplazamiento Y antes de pintar
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
std::array<float, MAX_BOUNCE> horizontal_zoom_values = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
std::array<float, MAX_BOUNCE> vertical_zoom_values = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
Bouncing() = default;
void reset() {
counter = 0;
zoom_w = 1.0f;
zoom_h = 1.0f;
desp_x = 0.0f;
desp_y = 0.0f;
}
} bouncing_;
Bouncing() = default;
void reset() {
counter = 0;
horizontal_zoom = 1.0f;
verical_zoom = 1.0f;
desp_x = 0.0f;
desp_y = 0.0f;
}
} bouncing_;
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
// --- Variables de estado y físicas ---
float x_; // Posición X
float y_; // Posición Y
float w_; // Ancho
float h_; // Alto
float vx_; // Velocidad X
float vy_; // Velocidad Y
float gravity_; // Aceleración en Y
float default_vy_; // Velocidad inicial al rebotar
float max_vy_; // Máxima velocidad en Y
bool being_created_; // Si el globo se está creando
bool enabled_ = true; // Si el globo está activo
bool invulnerable_; // Si el globo es invulnerable
bool stopped_; // Si el globo está parado
bool use_reversed_colors_ = false; // Si se usa el color alternativo
Circle collider_; // Círculo de colisión
Uint16 creation_counter_; // Temporizador de creación
Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación
Uint16 score_; // Puntos al destruir el globo
BalloonType type_; // Tipo de globo
BalloonSize size_; // Tamaño de globo
Uint8 menace_; // Amenaza que genera el globo
Uint32 counter_ = 0; // Contador interno
float travel_y_ = 1.0f; // Distancia a recorrer en Y antes de aplicar gravedad
float speed_; // Velocidad del globo
Uint8 power_; // Poder que alberga el globo
SDL_FRect play_area_; // Zona de movimiento del globo
std::string bouncing_sound_; // Archivo de sonido al rebotar
std::string popping_sound_; // Archivo de sonido al explotar
bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar
bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
// --- Variables de estado y físicas ---
float x_; // Posición X
float y_; // Posición Y
float w_; // Ancho
float h_; // Alto
float vx_; // Velocidad X
float vy_; // Velocidad Y
float gravity_; // Aceleración en Y
float default_vy_; // Velocidad inicial al rebotar
float max_vy_; // Máxima velocidad en Y
bool being_created_; // Si el globo se está creando
bool enabled_ = true; // Si el globo está activo
bool invulnerable_; // Si el globo es invulnerable
bool stopped_; // Si el globo está parado
bool use_reversed_colors_ = false; // Si se usa el color alternativo
Circle collider_; // Círculo de colisión
Uint16 creation_counter_; // Temporizador de creación
Uint16 creation_counter_ini_; // Valor inicial del temporizador de creación
Uint16 score_; // Puntos al destruir el globo
BalloonType type_; // Tipo de globo
BalloonSize size_; // Tamaño de globo
Uint8 menace_; // Amenaza que genera el globo
Uint32 counter_ = 0; // Contador interno
float travel_y_ = 1.0f; // Distancia a recorrer en Y antes de aplicar gravedad
float speed_; // Velocidad del globo
Uint8 power_; // Poder que alberga el globo
SDL_FRect play_area_; // Zona de movimiento del globo
std::string bouncing_sound_; // Archivo de sonido al rebotar
std::string popping_sound_; // Archivo de sonido al explotar
bool bouncing_sound_enabled_ = false; // Si debe sonar el globo al rebotar
bool poping_sound_enabled_ = true; // Si debe sonar el globo al explotar
bool sound_enabled_ = true; // Indica si los globos deben hacer algun sonido
// --- Métodos internos ---
void shiftColliders(); // Alinea el círculo de colisión
void shiftSprite(); // Alinea el sprite
void zoomSprite(); // Establece el nivel de zoom del sprite
void enableBounce(); // Activa el efecto de rebote
void disableBounce(); // Detiene el efecto de rebote
void updateBounce(); // Aplica el efecto de rebote
void updateState(); // Actualiza los estados del globo
void setAnimation(); // Establece la animación correspondiente
void playSound(const std::string &name); // Reproduce sonido
// --- Métodos internos ---
void shiftColliders(); // Alinea el círculo de colisión
void shiftSprite(); // Alinea el sprite
void zoomSprite(); // Establece el nivel de zoom del sprite
void enableBounce(); // Activa el efecto de rebote
void disableBounce(); // Detiene el efecto de rebote
void updateBounce(); // Aplica el efecto de rebote
void updateState(); // Actualiza los estados del globo
void setAnimation(); // Establece la animación correspondiente
void playSound(const std::string &name); // Reproduce sonido
};

View File

@@ -1,8 +1,9 @@
#include "balloon_manager.h"
#include <algorithm> // Para remove_if
#include <cstdlib> // Para rand
#include <numeric> // Para accumulate
#include <array>
#include <cstdlib> // Para rand
#include <numeric> // Para accumulate
#include "balloon.h" // Para Balloon, BALLOON_SCORE, BALLOON_VELX...
#include "balloon_formations.h" // Para BalloonFormationParams, BalloonForma...
@@ -209,8 +210,8 @@ void BalloonManager::createPowerBall() {
const float RIGHT = param.game.play_area.rect.w - BALLOON_SIZE[4];
const int LUCK = rand() % VALUES;
const float POS_X[VALUES] = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT};
const float VEL_X[VALUES] = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE};
const std::array<float, VALUES> POS_X = {LEFT, LEFT, CENTER, CENTER, RIGHT, RIGHT};
const std::array<float, VALUES> VEL_X = {BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_POSITIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE, BALLOON_VELX_NEGATIVE};
balloons_.emplace_back(std::make_unique<Balloon>(POS_X[LUCK], POS_Y, BalloonType::POWERBALL, BalloonSize::SIZE4, VEL_X[LUCK], balloon_speed_, CREATION_TIME, play_area_, balloon_textures_[4], balloon_animations_[4]));
balloons_.back()->setInvulnerable(true);

View File

@@ -11,6 +11,7 @@
#include <cstdlib> // Para exit, EXIT_FAILURE, size_t, srand
#include <ctime> // Para time
#include <memory> // Para make_unique, unique_ptr
#include <span>
#include <stdexcept> // Para runtime_error
#include <string> // Para operator+, basic_string, allocator
#include <vector> // Para vector
@@ -41,7 +42,7 @@
#endif
// Constructor
Director::Director(int argc, const char *argv[]) {
Director::Director(int argc, std::span<char *> argv) {
#ifdef RECORDING
Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P;
@@ -434,7 +435,7 @@ void Director::setFileList() {
}
// Comprueba los parametros del programa
void Director::checkProgramArguments(int argc, const char *argv[]) {
void Director::checkProgramArguments(int argc, std::span<char *> argv) {
// Establece la ruta del programa
executable_path_ = getPath(argv[0]);

View File

@@ -1,6 +1,7 @@
#pragma once
#include <string> // Para manejar cadenas de texto
#include <span>
namespace Lang {
enum class Code : int;
@@ -9,7 +10,7 @@ enum class Code : int;
class Director {
public:
// --- Constructor y destructor ---
Director(int argc, const char *argv[]);
Director(int argc, std::span<char*> argv);
~Director();
// --- Bucle principal ---
@@ -32,7 +33,7 @@ private:
// --- Gestión de entrada y archivos ---
void bindInputs(); // Asigna botones y teclas al sistema de entrada
void setFileList(); // Crea el índice de archivos disponibles
void checkProgramArguments(int argc, const char *argv[]); // Verifica los parámetros del programa
void checkProgramArguments(int argc, std::span<char*> argv); // Verifica los parámetros del programa // NOLINT(modernize-avoid-c-arrays)
// --- Secciones del programa ---
void runLogo(); // Ejecuta la pantalla con el logo

View File

@@ -1 +1,4 @@
# source/external/.clang-tidy
Checks: '-*'
WarningsAsErrors: ''
HeaderFilterRegex: ''

View File

@@ -11,9 +11,9 @@ Actualizando a la versión "Arcade Edition" en 08/05/2024
#include "director.h" // Para Director
auto main(int argc, char *argv[]) -> int {
auto main(int argc, char* argv[]) -> int {
// Crea el objeto Director
auto director = std::make_unique<Director>(argc, const_cast<const char **>(argv));
auto director = std::make_unique<Director>(argc, std::span<char*>(argv, argc));
// Bucle principal
return director->run();

View File

@@ -22,22 +22,22 @@ enum class DifficultyCode {
// --- Estructura que representa un nivel de dificultad
struct Difficulty {
DifficultyCode code; // Código que identifica la dificultad
std::string name; // Nombre que identifica la dificultad
DifficultyCode code; // Código que identifica la dificultad
std::string name; // Nombre que identifica la dificultad
Difficulty(DifficultyCode c, std::string n)
: code(c), name(std::move(n)) {}
Difficulty(DifficultyCode c, std::string n)
: code(c), name(std::move(n)) {}
};
// --- Opciones de ventana ---
struct WindowOptions {
std::string caption; // Texto que aparece en la barra de título de la ventana
int size{2}; // Valor por el que se multiplica el tamaño de la ventana
int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla
std::string caption; // Texto que aparece en la barra de título de la ventana
int size{2}; // Valor por el que se multiplica el tamaño de la ventana
int max_size{2}; // Tamaño máximo para que la ventana no sea mayor que la pantalla
// Constructor por defecto con valores iniciales
WindowOptions()
: caption("Coffee Crisis Arcade Edition") {}
// Constructor por defecto con valores iniciales
WindowOptions()
: caption("Coffee Crisis Arcade Edition") {}
};
// --- Opciones de vídeo ---
@@ -60,9 +60,7 @@ struct MusicOptions {
int volume{100}; // Volumen de la música
// Constructor por defecto
MusicOptions()
{}
MusicOptions() = default;
};
// --- Opciones de sonido ---
@@ -71,22 +69,20 @@ struct SoundOptions {
int volume{100}; // Volumen de los sonidos
// Constructor por defecto
SoundOptions()
{}
SoundOptions() = default;
};
// --- Opciones de audio ---
struct AudioOptions {
MusicOptions music; // Opciones para la música
SoundOptions sound; // Opciones para los efectos de sonido
bool enabled{true}; // Indica si el audio está activo o no
int volume{100}; // Volumen general del audio
MusicOptions music; // Opciones para la música
SoundOptions sound; // Opciones para los efectos de sonido
bool enabled{true}; // Indica si el audio está activo o no
int volume{100}; // Volumen general del audio
// Constructor por defecto
AudioOptions()
: music(),
sound() {}
// Constructor por defecto
AudioOptions()
: music(),
sound() {}
};
// --- Opciones de configuración ---
@@ -108,38 +104,36 @@ struct SettingsOptions {
void clearLastHiScoreEntries() {
last_hi_score_entry[0] = INVALID_INDEX;
last_hi_score_entry[1] = INVALID_INDEX;
}
}
};
// --- Opciones de mando ---
struct GamepadOptions {
int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando
InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo
bool plugged{false}; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
int index; // Índice en el vector de mandos
int player_id; // Jugador asociado al mando
InputDevice type{InputDevice::CONTROLLER}; // Indica si se usará teclado, mando o ambos
std::string name; // Nombre del dispositivo
bool plugged{false}; // Indica si el mando está conectado
std::vector<InputAction> inputs; // Listado de acciones asignadas
std::vector<SDL_GamepadButton> buttons; // Listado de botones asignados a cada acción
// Constructor por defecto
GamepadOptions()
: index(INVALID_INDEX),
player_id(INVALID_INDEX),
name(),
inputs{
InputAction::FIRE_LEFT,
InputAction::FIRE_CENTER,
InputAction::FIRE_RIGHT,
InputAction::START,
InputAction::SERVICE},
buttons{
SDL_GAMEPAD_BUTTON_WEST,
SDL_GAMEPAD_BUTTON_NORTH,
SDL_GAMEPAD_BUTTON_EAST,
SDL_GAMEPAD_BUTTON_START,
SDL_GAMEPAD_BUTTON_BACK} {}
// Constructor por defecto
GamepadOptions()
: index(INVALID_INDEX),
player_id(INVALID_INDEX),
name(),
inputs{
InputAction::FIRE_LEFT,
InputAction::FIRE_CENTER,
InputAction::FIRE_RIGHT,
InputAction::START,
InputAction::SERVICE},
buttons{
SDL_GAMEPAD_BUTTON_WEST,
SDL_GAMEPAD_BUTTON_NORTH,
SDL_GAMEPAD_BUTTON_EAST,
SDL_GAMEPAD_BUTTON_START,
SDL_GAMEPAD_BUTTON_BACK} {}
};
// --- Opciones pendientes de aplicar ---
@@ -149,9 +143,7 @@ struct PendingChanges {
bool has_pending_changes{false}; // Indica si hay cambios pendientes
// Constructor por defecto con valores iniciales
PendingChanges()
{}
PendingChanges() = default;
};
// --- Variables globales ---
@@ -164,15 +156,15 @@ extern PendingChanges pending_changes; // Opciones que se aplican al c
extern std::vector<Difficulty> difficulties; // Lista de los diferentes tipos de dificultad
// --- Funciones de configuración ---
void init(); // Inicializa las opciones del programa
auto loadFromFile() -> bool; // Carga el fichero de configuración
auto saveToFile() -> bool; // Guarda el fichero de configuración
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
void swapKeyboard(); // Intercambia el teclado de jugador
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
void checkPendingChanges(); // Verifica si hay cambios pendientes
void init(); // Inicializa las opciones del programa
auto loadFromFile() -> bool; // Carga el fichero de configuración
auto saveToFile() -> bool; // Guarda el fichero de configuración
void setKeyboardToPlayer(int player_id); // Asigna el teclado al jugador
void swapKeyboard(); // Intercambia el teclado de jugador
void swapControllers(); // Intercambia los jugadores asignados a los dos primeros mandos
auto getPlayerWhoUsesKeyboard() -> int; // Averigua quién está usando el teclado
void applyPendingChanges(); // Aplica los cambios pendientes copiando los valores a sus variables
void checkPendingChanges(); // Verifica si hay cambios pendientes
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode; // Obtiene el código de dificultad a partir del nombre
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string; // Obtiene el nombre de la dificultad a partir del código
} // namespace Options

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_FPoint, SDL_GetTicks, SDL_FRect, SDL_Texture, SDL_Renderer, Uint64
#include <array>
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para basic_string, string
@@ -35,87 +36,88 @@ enum class ScoreboardMode : int {
// --- Structs ---
struct Panel {
ScoreboardMode mode; // Modo en el que se encuentra el panel
SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador
ScoreboardMode mode; // Modo en el que se encuentra el panel
SDL_FRect pos; // Posición donde dibujar el panel dentro del marcador
};
// --- Clase Scoreboard ---
class Scoreboard {
public:
// --- Métodos de singleton ---
static void init(); // Crea el objeto Scoreboard
static void destroy(); // Libera el objeto Scoreboard
static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard
public:
// --- Métodos de singleton ---
static void init(); // Crea el objeto Scoreboard
static void destroy(); // Libera el objeto Scoreboard
static auto get() -> Scoreboard *; // Obtiene el puntero al objeto Scoreboard
// --- Métodos principales ---
void update(); // Actualiza la lógica del marcador
void render(); // Pinta el marcador
// --- Métodos principales ---
void update(); // Actualiza la lógica del marcador
void render(); // Pinta el marcador
// --- Setters ---
void setColor(Color color); // Establece el color del marcador
void setPos(SDL_FRect rect); // Establece la posición y tamaño del marcador
void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
void setHiScore(int hi_score) { hi_score_ = hi_score; }
void setHiScoreName(const std::string &name) { hi_score_name_ = name; }
void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; }
void setMult(int panel, float mult) { mult_[panel] = mult; }
void setName(int panel, const std::string &name) { name_[panel] = name; }
void setPower(float power) { power_ = power; }
void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; }
void setScore(int panel, int score) { score_[panel] = score; }
void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; }
void setStage(int stage) { stage_ = stage; }
// --- Setters ---
void setColor(Color color); // Establece el color del marcador
void setPos(SDL_FRect rect); // Establece la posición y tamaño del marcador
void setContinue(int panel, int continue_counter) { continue_counter_[panel] = continue_counter; }
void setHiScore(int hi_score) { hi_score_ = hi_score; }
void setHiScoreName(const std::string &name) { hi_score_name_ = name; }
void setMode(int index, ScoreboardMode mode) { panel_[index].mode = mode; }
void setMult(int panel, float mult) { mult_[panel] = mult; }
void setName(int panel, const std::string &name) { name_[panel] = name; }
void setPower(float power) { power_ = power; }
void setRecordName(int panel, const std::string &record_name) { record_name_[panel] = record_name; }
void setScore(int panel, int score) { score_[panel] = score; }
void setSelectorPos(int panel, int pos) { selector_pos_[panel] = pos; }
void setStage(int stage) { stage_ = stage; }
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
private:
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// --- Variables de estado ---
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Variables de estado ---
std::array<std::string, SCOREBOARD_MAX_PANELS> name_ = {}; // Nombre de cada jugador
std::array<std::string, SCOREBOARD_MAX_PANELS> record_name_ = {}; // Nombre introducido para la tabla de records
std::array<size_t, SCOREBOARD_MAX_PANELS> selector_pos_ = {}; // Posición del selector de letra para introducir el nombre
std::array<int, SCOREBOARD_MAX_PANELS> score_ = {}; // Puntuación de los jugadores
std::array<float, SCOREBOARD_MAX_PANELS> mult_ = {}; // Multiplicador de los jugadores
std::array<int, SCOREBOARD_MAX_PANELS> continue_counter_ = {}; // Tiempo para continuar de los jugadores
std::array<Panel, SCOREBOARD_MAX_PANELS> panel_ = {}; // Lista con todos los paneles del marcador
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
auto updateScoreText(int num) -> std::string; // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Singleton ---
static Scoreboard *instance;
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Singleton ---
static Scoreboard *instance;
};

View File

@@ -70,7 +70,7 @@ class Screen {
int frame_count{0}; // Número acumulado de frames en el intervalo.
int last_value{0}; // Número de frames calculado en el último segundo.
FPS() {}
FPS() = default;
void increment() { frame_count++; }
auto calculate(Uint32 current_ticks) -> int {
if (current_ticks - ticks >= 1000) {

View File

@@ -8,6 +8,7 @@
#include <cmath> // Para abs
#include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, string
#include <string_view>
#include <vector> // Para vector
#include "audio.h" // Para Audio
@@ -30,7 +31,8 @@
#include "utils.h" // Para Color, Zone, SHADOW_TEXT_COLOR, NO_TEXT...
// Textos
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
// Constructor
Credits::Credits()
@@ -218,7 +220,7 @@ void Credits::fillTextTexture() {
// Texto con el copyright
y += mini_logo_sprite->getHeight() + 3;
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXT_COPYRIGHT, 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
text->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, std::string(TEXT_COPYRIGHT), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
// Resetea el renderizador
SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr);

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget
#include <array>
#include <algorithm> // Para find_if, clamp, find, min
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
@@ -1404,7 +1405,7 @@ void Game::initDemo(int player_id) {
{
constexpr auto NUM_DEMOS = 3;
const auto DEMO = rand() % NUM_DEMOS;
const int STAGES[NUM_DEMOS] = {0, 3, 5};
constexpr std::array<int, NUM_DEMOS> STAGES = {0, 3, 5};
Stage::number = STAGES[DEMO];
}
@@ -1695,7 +1696,7 @@ void Game::checkAndUpdateBalloonSpeed() {
return;
const float PERCENT = static_cast<float>(Stage::power) / Stage::get(Stage::number).power_to_complete;
const float THRESHOLDS[] = {0.2f, 0.4f, 0.6f, 0.8f};
constexpr std::array<float, 4> THRESHOLDS = {0.2f, 0.4f, 0.6f, 0.8f};
for (size_t i = 0; i < std::size(THRESHOLDS); ++i) {
if (balloon_manager_->getBalloonSpeed() == BALLOON_SPEED[i] && PERCENT > THRESHOLDS[i]) {

View File

@@ -433,7 +433,7 @@ void Title::renderCopyright() {
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
param.game.game_area.center_x,
anchor_.copyright_text,
TEXT_COPYRIGHT,
std::string(TEXT_COPYRIGHT),
1,
NO_TEXT_COLOR,
1,

View File

@@ -4,6 +4,7 @@
#include <memory> // Para unique_ptr, shared_ptr
#include <vector>
#include <string_view>
#include "section.h" // Para Options
@@ -16,7 +17,8 @@ class Text;
class TiledBG;
// Textos
constexpr const char TEXT_COPYRIGHT[] = "@2020,2025 JailDesigner";
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
// Parámetros
constexpr bool ALLOW_TITLE_ANIMATION_SKIP = false;

View File

@@ -4,6 +4,7 @@
#include <SDL3/SDL.h> // Para SDL_FlipMode, SDL_GetTicks
#include <algorithm> // Para max
#include <array>
#include <cmath> // Para abs
#include <cstdlib> // Para rand, abs
#include <string> // Para basic_string
@@ -41,49 +42,62 @@ void Tabe::render() {
// Mueve el objeto
void Tabe::move() {
const int X = static_cast<int>(x_);
speed_ += accel_;
x_ += speed_;
fly_distance_ -= std::abs(X - static_cast<int>(x_));
const int X = static_cast<int>(x_);
speed_ += accel_;
x_ += speed_;
fly_distance_ -= std::abs(X - static_cast<int>(x_));
// Comprueba si sale por los bordes
const float MIN_X = param.game.game_area.rect.x - WIDTH;
const float MAX_X = param.game.game_area.rect.x + param.game.game_area.rect.w;
switch (destiny_) {
case TabeDirection::TO_THE_LEFT: {
if (x_ < MIN_X) {
disable();
}
if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH && direction_ == TabeDirection::TO_THE_RIGHT) {
setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80);
x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH;
}
break;
}
// Comprueba si sale por los bordes
const float MIN_X = param.game.game_area.rect.x - WIDTH;
const float MAX_X = param.game.game_area.rect.x + param.game.game_area.rect.w;
switch (destiny_) {
case TabeDirection::TO_THE_LEFT: {
if (x_ < MIN_X) {
disable();
}
if (x_ > param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH && direction_ == TabeDirection::TO_THE_RIGHT) {
setRandomFlyPath(TabeDirection::TO_THE_LEFT, 80);
x_ = param.game.game_area.rect.x + param.game.game_area.rect.w - WIDTH;
}
break;
}
case TabeDirection::TO_THE_RIGHT: {
if (x_ > MAX_X) {
disable();
}
if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) {
setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80);
x_ = param.game.game_area.rect.x;
}
break;
}
default:
break;
case TabeDirection::TO_THE_RIGHT: {
if (x_ > MAX_X) {
disable();
}
if (x_ < param.game.game_area.rect.x && direction_ == TabeDirection::TO_THE_LEFT) {
setRandomFlyPath(TabeDirection::TO_THE_RIGHT, 80);
x_ = param.game.game_area.rect.x;
}
break;
}
default:
break;
}
if (fly_distance_ <= 0) {
if (waiting_counter_ > 0) {
accel_ = speed_ = 0.0F;
--waiting_counter_;
accel_ = speed_ = 0.0F;
--waiting_counter_;
} else {
constexpr int CHOICES = 4;
const TabeDirection LEFT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT};
const TabeDirection RIGHT[CHOICES] = {TabeDirection::TO_THE_LEFT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT, TabeDirection::TO_THE_RIGHT};
const TabeDirection DIRECTION = destiny_ == TabeDirection::TO_THE_LEFT ? LEFT[rand() % CHOICES] : RIGHT[rand() % CHOICES];
const std::array<TabeDirection, CHOICES> LEFT = {
TabeDirection::TO_THE_LEFT,
TabeDirection::TO_THE_LEFT,
TabeDirection::TO_THE_LEFT,
TabeDirection::TO_THE_RIGHT};
const std::array<TabeDirection, CHOICES> RIGHT = {
TabeDirection::TO_THE_LEFT,
TabeDirection::TO_THE_RIGHT,
TabeDirection::TO_THE_RIGHT,
TabeDirection::TO_THE_RIGHT};
const TabeDirection DIRECTION = destiny_ == TabeDirection::TO_THE_LEFT
? LEFT[rand() % CHOICES]
: RIGHT[rand() % CHOICES];
setRandomFlyPath(DIRECTION, 20 + rand() % 40);
}
}
@@ -123,10 +137,10 @@ void Tabe::setRandomFlyPath(TabeDirection direction, int lenght) {
switch (direction) {
case TabeDirection::TO_THE_LEFT: {
speed_ = -1.0F * SPEED;
accel_ = -1.0F * (1 + rand() % 10) / 30.0F;
sprite_->setFlip(SDL_FLIP_NONE);
break;
speed_ = -1.0F * SPEED;
accel_ = -1.0F * (1 + rand() % 10) / 30.0F;
sprite_->setFlip(SDL_FLIP_NONE);
break;
}
case TabeDirection::TO_THE_RIGHT: {
@@ -175,11 +189,11 @@ void Tabe::updateState() {
// Intenta obtener el bonus
auto Tabe::tryToGetBonus() -> bool {
if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) {
has_bonus_ = false;
return true;
}
return false;
if (has_bonus_ && rand() % std::max(1, 15 - number_of_hits_) == 0) {
has_bonus_ = false;
return true;
}
return false;
}
// Actualiza el temporizador

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para Uint8
#include <array>
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string
@@ -18,13 +19,13 @@ constexpr int TEXT_STROKE = 8;
// --- Estructuras auxiliares ---
struct TextOffset {
int x, y, w;
int x, y, w;
};
struct TextFile {
int box_width; // Anchura de la caja de cada caracter en el png
int box_height; // Altura de la caja de cada caracter en el png
TextOffset offset[128]; // Vector con las posiciones y ancho de cada letra
int box_width; // Anchura de la caja de cada caracter en el png
int box_height; // Altura de la caja de cada caracter en el png
std::array<TextOffset, 128> offset = {}; // Vector con las posiciones y ancho de cada letra
};
// Llena una estructura TextFile desde un fichero
@@ -32,41 +33,42 @@ auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile>;
// --- Clase Text: pinta texto en pantalla a partir de un bitmap ---
class Text {
public:
// --- Constructores y destructor ---
Text(std::shared_ptr<Texture> texture, const std::string &text_file);
Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
~Text() = default;
public:
// --- Constructores y destructor ---
Text(std::shared_ptr<Texture> texture, const std::string &text_file);
Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file);
~Text() = default;
// --- Métodos de escritura en pantalla ---
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño
// --- Métodos de escritura en pantalla ---
void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto en pantalla
void write2X(int x, int y, const std::string &text, int kerning = 1); // Escribe el texto al doble de tamaño
// --- Escritura en textura ---
auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Texture>; // Escribe el texto en una textura
auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1) -> std::shared_ptr<Texture>; // Escribe el texto con extras en una textura
// --- Escritura en textura ---
auto writeToTexture(const std::string &text, int zoom = 1, int kerning = 1) -> std::shared_ptr<Texture>; // Escribe el texto en una textura
auto writeDXToTexture(Uint8 flags, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1) -> std::shared_ptr<Texture>; // Escribe el texto con extras en una textura
// --- Métodos de escritura avanzada ---
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras
// --- Métodos de escritura avanzada ---
void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1); // Escribe el texto con colores
void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); // Escribe el texto con sombra
void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x
void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color text_color = Color(), Uint8 shadow_distance = 1, Color shadow_color = Color(), int lenght = -1); // Escribe texto con extras
// --- Utilidades ---
[[nodiscard]] auto lenght(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual
// --- Utilidades ---
[[nodiscard]] auto lenght(const std::string &text, int kerning = 1) const -> int; // Obtiene la longitud en pixels de una cadena
[[nodiscard]] auto getCharacterSize() const -> int; // Devuelve el tamaño de caracter actual
// --- Configuración ---
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
void setPalette(int number); // Establece una paleta
// --- Configuración ---
void setFixedWidth(bool value); // Establece si se usa un tamaño fijo de letra
void setPalette(int number); // Establece una paleta
private:
// --- Objetos y punteros ---
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los gráficos para el texto
private:
// --- Objetos y punteros ---
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los gráficos para el texto
// --- Variables ---
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
int box_height_ = 0; // Altura de la caja de cada caracter en el png
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra
// --- Variables ---
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
int box_height_ = 0; // Altura de la caja de cada caracter en el png
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
std::array<TextOffset, 128> offset_ = {};
; // Vector con las posiciones y ancho de cada letra
};

View File

@@ -240,7 +240,7 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surfa
// Si el constructor de Surface espera un std::shared_ptr<Uint8[]>:
size_t pixel_count = raw_pixels.size();
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>());
auto pixels = std::shared_ptr<Uint8[]>(new Uint8[pixel_count], std::default_delete<Uint8[]>()); // NOLINT(modernize-avoid-c-arrays)
std::memcpy(pixels.get(), raw_pixels.data(), pixel_count);
auto surface = std::make_shared<Surface>(w, h, pixels);

View File

@@ -16,11 +16,11 @@ using Palette = std::array<Uint32, 256>;
// Definición de Surface para imágenes con paleta
struct Surface {
std::shared_ptr<Uint8[]> data;
std::shared_ptr<Uint8[]> data; // NOLINT(modernize-avoid-c-arrays)
Uint16 w, h;
// Constructor
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels)
Surface(Uint16 width, Uint16 height, std::shared_ptr<Uint8[]> pixels) // NOLINT(modernize-avoid-c-arrays)
: data(std::move(pixels)), w(width), h(height) {}
};

View File

@@ -1,6 +1,7 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_SetTextureColorMod, SDL_Renderer, SDL_Texture
#include <array>
#include "utils.h" // Para Color
@@ -50,7 +51,7 @@ private:
SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados
std::array<double, 360> sin_; // Vector con los valores del seno precalculados
float desp_ = 0.0f; // Desplazamiento aplicado
float speed_ = 1.0f; // Incremento que se añade al desplazamiento a cada bucle
bool stopping_ = false; // Indica si se está deteniendo

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> // Para SDL_FRect, Uint32
#include <array>
#include <cstddef> // Para size_t
#include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector
@@ -14,59 +15,59 @@ class MenuOption;
class Text;
class MenuRenderer {
public:
MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text);
public:
MenuRenderer(const ServiceMenu *menu_state, std::shared_ptr<Text> element_text, std::shared_ptr<Text> title_text);
// Métodos principales de la vista
void render(const ServiceMenu *menu_state);
void update(const ServiceMenu *menu_state);
// Métodos principales de la vista
void render(const ServiceMenu *menu_state);
void update(const ServiceMenu *menu_state);
// Método para notificar al renderer que el layout puede haber cambiado
void onLayoutChanged(const ServiceMenu *menu_state);
void setLayout(const ServiceMenu *menu_state);
// Método para notificar al renderer que el layout puede haber cambiado
void onLayoutChanged(const ServiceMenu *menu_state);
void setLayout(const ServiceMenu *menu_state);
// Getters
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
// Getters
[[nodiscard]] auto getRect() const -> const SDL_FRect & { return rect_; }
private:
// --- Referencias a los renderizadores de texto ---
std::shared_ptr<Text> element_text_;
std::shared_ptr<Text> title_text_;
private:
// --- Referencias a los renderizadores de texto ---
std::shared_ptr<Text> element_text_;
std::shared_ptr<Text> title_text_;
// --- Variables de estado de la vista (layout y animación) ---
SDL_FRect rect_{};
SDL_FRect border_rect_{};
size_t width_ = 0;
size_t height_ = 0;
size_t options_height_ = 0;
size_t options_padding_ = 0;
size_t options_y_ = 0;
size_t title_height_ = 0;
size_t title_padding_ = 0;
size_t upper_height_ = 0;
size_t lower_height_ = 0;
size_t lower_padding_ = 0;
Uint32 color_counter_ = 0;
// --- Variables de estado de la vista (layout y animación) ---
SDL_FRect rect_{};
SDL_FRect border_rect_{};
size_t width_ = 0;
size_t height_ = 0;
size_t options_height_ = 0;
size_t options_padding_ = 0;
size_t options_y_ = 0;
size_t title_height_ = 0;
size_t title_padding_ = 0;
size_t upper_height_ = 0;
size_t lower_height_ = 0;
size_t lower_padding_ = 0;
Uint32 color_counter_ = 0;
// --- Variables para animación de resize ---
SDL_FRect rect_anim_from_{};
SDL_FRect rect_anim_to_{};
int resize_anim_step_ = 0;
int resize_anim_steps_ = 8;
bool resizing_ = false;
// --- Variables para animación de resize ---
SDL_FRect rect_anim_from_{};
SDL_FRect rect_anim_to_{};
int resize_anim_step_ = 0;
int resize_anim_steps_ = 8;
bool resizing_ = false;
// --- Anchos precalculados ---
int group_menu_widths_[5]{};
// --- Anchos precalculados ---
std::array<int, 5> group_menu_widths_ = {};
// --- Métodos privados de la vista ---
void setAnchors(const ServiceMenu *menu_state);
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void updateResizeAnimation();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
auto getAnimatedSelectedColor() -> Color;
void updateColorCounter();
auto setRect(SDL_FRect rect) -> SDL_FRect;
// --- Métodos privados de la vista ---
void setAnchors(const ServiceMenu *menu_state);
auto calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect;
void resize(const ServiceMenu *menu_state);
void setSize(const ServiceMenu *menu_state);
void updateResizeAnimation();
void precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state);
[[nodiscard]] auto getMenuWidthForGroup(ServiceMenu::SettingsGroup group) const -> int;
auto getAnimatedSelectedColor() -> Color;
void updateColorCounter();
auto setRect(SDL_FRect rect) -> SDL_FRect;
};

View File

@@ -31,10 +31,14 @@ class ServiceMenu {
static constexpr size_t MIN_WIDTH = 240;
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
// --- Métodos de singleton ---
static void init();
static void destroy();
static auto get() -> ServiceMenu *;
ServiceMenu(const ServiceMenu &) = delete;
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
// --- Métodos principales ---
void toggle();
void render();
void update();
@@ -96,10 +100,10 @@ private:
[[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string;
void setHiddenOptions();
// --- Singleton ---
// --- Constructores y destructor privados (singleton) ---
ServiceMenu();
~ServiceMenu() = default;
ServiceMenu(const ServiceMenu &) = delete;
auto operator=(const ServiceMenu &) -> ServiceMenu & = delete;
// --- Instancia singleton ---
static ServiceMenu *instance;
};