clang-tidy readability

This commit is contained in:
2025-07-20 14:56:00 +02:00
parent f5245273a1
commit ca99f7be34
57 changed files with 623 additions and 557 deletions

View File

@@ -1,6 +1,8 @@
Checks: >
readability-identifier-naming,
modernize-*
readability-*,
modernize-*,
-readability-identifier-length,
-readability-magic-numbers
WarningsAsErrors: '*'
# Solo incluir archivos de tu código fuente

View File

@@ -74,8 +74,8 @@ Background::Background()
// Inicializa objetos
{
constexpr float TOP_CLOUDS_SPEED = 0.1f;
constexpr float BOTTOM_CLOUDS_SPEED = 0.05f;
constexpr float TOP_CLOUDS_SPEED = 0.1F;
constexpr float BOTTOM_CLOUDS_SPEED = 0.05F;
top_clouds_sprite_a_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
top_clouds_sprite_a_->setVelX(-TOP_CLOUDS_SPEED);
@@ -187,7 +187,7 @@ void Background::renderBottomClouds() {
// Compone todos los elementos del fondo en la textura
void Background::fillCanvas() {
// Cambia el destino del renderizador
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, canvas_);
// Dibuja el gradiente de fondo
@@ -234,7 +234,7 @@ void Background::setGradientNumber(int value) {
// Ajusta el valor de la variable
void Background::setTransition(float value) {
transition_ = std::clamp(value, 0.0f, 1.0f);
transition_ = std::clamp(value, 0.0F, 1.0F);
}
// Establece la posición del objeto
@@ -253,7 +253,7 @@ void Background::setColor(Color color) {
attenuate_color_ = color;
// Colorea la textura
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, color_texture_);
SDL_SetRenderDrawColor(renderer_, attenuate_color_.r, attenuate_color_.g, attenuate_color_.b, 255);
@@ -276,10 +276,9 @@ void Background::setAlpha(int alpha) {
void Background::updateAlphaColorTexture() {
if (alpha_color_text_ == alpha_color_text_temp_) {
return;
} else {
alpha_color_text_ > alpha_color_text_temp_ ? ++alpha_color_text_temp_ : --alpha_color_text_temp_;
SDL_SetTextureAlphaMod(color_texture_, alpha_color_text_temp_);
}
alpha_color_text_ > alpha_color_text_temp_ ? ++alpha_color_text_temp_ : --alpha_color_text_temp_;
SDL_SetTextureAlphaMod(color_texture_, alpha_color_text_temp_);
}
// Actualiza las nubes
@@ -359,12 +358,12 @@ void Background::createMoonPath() {
// Establece la posición del sol
void Background::setSunProgression(float progress) {
progress = std::clamp(progress, 0.0f, 1.0f);
progress = std::clamp(progress, 0.0F, 1.0F);
sun_index_ = static_cast<size_t>(progress * (sun_path_.size() - 1));
}
// Establece la posición de la luna
void Background::setMoonProgression(float progress) {
progress = std::clamp(progress, 0.0f, 1.0f);
progress = std::clamp(progress, 0.0F, 1.0F);
moon_index_ = static_cast<size_t>(progress * (moon_path_.size() - 1));
}

View File

@@ -28,7 +28,7 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
switch (type_) {
case BalloonType::BALLOON: {
vy_ = 0;
max_vy_ = 3.0f;
max_vy_ = 3.0F;
const int INDEX = static_cast<int>(size_);
gravity_ = param.balloon.settings.at(INDEX).grav;
@@ -44,8 +44,8 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
}
case BalloonType::FLOATER: {
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0f);
gravity_ = 0.00f;
default_vy_ = max_vy_ = vy_ = fabs(vx_ * 2.0F);
gravity_ = 0.00F;
const int INDEX = static_cast<int>(size_);
h_ = w_ = BALLOON_SIZE[INDEX];
@@ -66,12 +66,12 @@ Balloon::Balloon(float x, float y, BalloonType type, BalloonSize size, float vel
power_ = score_ = menace_ = 0;
vy_ = 0;
max_vy_ = 3.0f;
max_vy_ = 3.0F;
gravity_ = param.balloon.settings.at(INDEX).grav;
default_vy_ = param.balloon.settings.at(INDEX).vel;
sprite_->setRotate(creation_timer <= 0);
sprite_->setRotateAmount(vx_ > 0.0f ? 2.0 : -2.0);
sprite_->setRotateAmount(vx_ > 0.0F ? 2.0 : -2.0);
break;
}
@@ -113,7 +113,7 @@ void Balloon::render() {
// Renderiza la estrella
if (!invulnerable_) {
SDL_FPoint p = {24.0f, 24.0f};
SDL_FPoint p = {24.0F, 24.0F};
sprite_->setRotatingCenter(p);
sprite_->render();
}
@@ -128,7 +128,7 @@ void Balloon::render() {
// Renderizado para el resto de globos
if (isBeingCreated()) {
// Renderizado con transparencia
sprite_->getTexture()->setAlpha(255 - (int)((float)creation_counter_ * (255.0f / (float)creation_counter_ini_)));
sprite_->getTexture()->setAlpha(255 - (int)((float)creation_counter_ * (255.0F / (float)creation_counter_ini_)));
sprite_->render();
sprite_->getTexture()->setAlpha(255);
} else {
@@ -150,8 +150,9 @@ void Balloon::move() {
const float MIN_X = play_area_.x - CLIP;
const float MAX_X = play_area_.x + play_area_.w - w_ + CLIP;
if (x_ < MIN_X || x_ > MAX_X) {
if (bouncing_sound_enabled_)
if (bouncing_sound_enabled_) {
playSound(bouncing_sound_);
}
x_ = std::clamp(x_, MIN_X, MAX_X);
vx_ = -vx_;
// Activa el efecto de rebote o invierte la rotación
@@ -169,8 +170,9 @@ void Balloon::move() {
if (vy_ < 0) {
const int MIN_Y = play_area_.y;
if (y_ < MIN_Y) {
if (bouncing_sound_enabled_)
if (bouncing_sound_enabled_) {
playSound(bouncing_sound_);
}
y_ = MIN_Y;
vy_ = -vy_;
enableBounce();
@@ -180,8 +182,9 @@ void Balloon::move() {
// Colisión en la parte inferior de la zona de juego
const int MAX_Y = play_area_.y + play_area_.h - h_;
if (y_ > MAX_Y) {
if (bouncing_sound_enabled_)
if (bouncing_sound_enabled_) {
playSound(bouncing_sound_);
}
y_ = MAX_Y;
vy_ = -default_vy_;
if (type_ != BalloonType::POWERBALL) {
@@ -204,9 +207,9 @@ void Balloon::move() {
travel_y_ += speed_;
// Si la distancia acumulada en Y es igual a la velocidad, se aplica la gravedad
if (travel_y_ >= 1.0f) {
if (travel_y_ >= 1.0F) {
// Quita el excedente
travel_y_ -= 1.0f;
travel_y_ -= 1.0F;
// Aplica la gravedad al objeto sin pasarse de una velocidad máxima
vy_ += gravity_;
@@ -283,10 +286,11 @@ void Balloon::setAnimation() {
}
// Establece el frame de animación
if (use_reversed_colors_)
if (use_reversed_colors_) {
sprite_->setCurrentAnimation(creating_animation);
else
} else {
sprite_->setCurrentAnimation(isBeingCreated() ? creating_animation : normal_animation);
}
}
// Detiene el globo
@@ -367,19 +371,21 @@ void Balloon::useNormalColor() {
}
// Reproduce sonido
void Balloon::playSound(const std::string &name) {
if (!sound_enabled_)
void Balloon::playSound(const std::string &name) const {
if (!sound_enabled_) {
return;
}
static auto audio_ = Audio::get();
static auto *audio_ = Audio::get();
audio_->playSound(name);
}
// Explota el globo
void Balloon::pop(bool should_sound) {
if (should_sound) {
if (poping_sound_enabled_)
if (poping_sound_enabled_) {
playSound(popping_sound_);
}
}
enabled_ = false;

View File

@@ -39,14 +39,14 @@ enum class BalloonType : Uint8 {
POWERBALL = 2,
};
constexpr float BALLOON_VELX_POSITIVE = 0.7f;
constexpr float BALLOON_VELX_NEGATIVE = -0.7f;
constexpr float BALLOON_VELX_POSITIVE = 0.7F;
constexpr float BALLOON_VELX_NEGATIVE = -0.7F;
constexpr int BALLOON_MOVING_ANIMATION = 0;
constexpr int BALLOON_POP_ANIMATION = 1;
constexpr int BALLOON_BORN_ANIMATION = 2;
constexpr std::array<float, 5> 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;
@@ -97,7 +97,7 @@ class Balloon {
[[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_; }
auto isUsingReversedColor() const -> bool { return use_reversed_colors_; }
[[nodiscard]] auto canBePopped() const -> bool { return !isBeingCreated(); }
// --- Setters ---
@@ -114,21 +114,21 @@ class Balloon {
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 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
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
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;
horizontal_zoom = 1.0f;
verical_zoom = 1.0f;
desp_x = 0.0f;
desp_y = 0.0f;
horizontal_zoom = 1.0F;
verical_zoom = 1.0F;
desp_x = 0.0F;
desp_y = 0.0F;
}
} bouncing_;
@@ -158,7 +158,7 @@ class Balloon {
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 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
@@ -177,5 +177,5 @@ class Balloon {
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
void playSound(const std::string &name) const; // Reproduce sonido
};

View File

@@ -14,7 +14,7 @@ constexpr int NUMBER_OF_STAGES = 10;
struct BalloonFormationParams {
int x = 0; // Posición en el eje X donde crear el globo
int y = 0; // Posición en el eje Y donde crear el globo
float vel_x = 0.0f; // Velocidad inicial en el eje X
float vel_x = 0.0F; // Velocidad inicial en el eje X
BalloonType type = BalloonType::BALLOON; // Tipo de globo
BalloonSize size = BalloonSize::SIZE1; // Tamaño de globo
int creation_counter = 0; // Temporizador para la creación del globo
@@ -36,7 +36,7 @@ struct BalloonFormationUnit {
: number_of_balloons(num_balloons), init(init_params) {}
// Constructor por defecto
BalloonFormationUnit() : number_of_balloons(0), init() {}
BalloonFormationUnit() : number_of_balloons(0) {}
};
using BalloonFormationPool = std::vector<const BalloonFormationUnit *>;

View File

@@ -186,7 +186,7 @@ void BalloonManager::createChildBalloon(const std::shared_ptr<Balloon> &balloon,
// Establece parametros
b->alignTo(X);
b->setVelY(b->getType() == BalloonType::BALLOON ? -2.50f : BALLOON_VELX_NEGATIVE * 2.0f);
b->setVelY(b->getType() == BalloonType::BALLOON ? -2.50F : BALLOON_VELX_NEGATIVE * 2.0F);
// Herencia de estados
if (balloon->isStopped()) {

View File

@@ -41,8 +41,9 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
// Implementación de render (llama al render del sprite_)
void Bullet::render() {
if (bullet_type_ != BulletType::NONE)
if (bullet_type_ != BulletType::NONE) {
sprite_->render();
}
}
// Actualiza el estado del objeto

View File

@@ -25,30 +25,30 @@ enum class BulletMoveStatus : Uint8 {
class Bullet {
public:
// Constantes
static constexpr float WIDTH = 12.0f;
static constexpr float HEIGHT = 12.0f;
static constexpr float WIDTH = 12.0F;
static constexpr float HEIGHT = 12.0F;
// Constructor y Destructor
Bullet(float x, float y, BulletType bullet_type, bool powered, int owner);
~Bullet() = default;
// Constructor y Destructor
Bullet(float x, float y, BulletType bullet_type, bool powered, int owner);
~Bullet() = default;
// Métodos principales
void render(); // Dibuja la bala en pantalla
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
// Métodos principales
void render(); // Dibuja la bala en pantalla
auto update() -> BulletMoveStatus; // Actualiza el estado del objeto
// Estado de la bala
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
void disable(); // Desactiva la bala
// Estado de la bala
[[nodiscard]] auto isEnabled() const -> bool; // Comprueba si está activa
void disable(); // Desactiva la bala
// Getters
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
auto getCollider() -> Circle &; // Devuelve el círculo de colisión
// Getters
[[nodiscard]] auto getOwner() const -> int; // Devuelve el identificador del dueño
auto getCollider() -> Circle &; // Devuelve el círculo de colisión
private:
// Constantes
static constexpr float VEL_Y = -3.0f;
static constexpr float VEL_X_LEFT = -2.0f;
static constexpr float VEL_X_RIGHT = 2.0f;
private:
// Constantes
static constexpr float VEL_Y = -3.0F;
static constexpr float VEL_X_LEFT = -2.0F;
static constexpr float VEL_X_RIGHT = 2.0F;
// Propiedades
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos

View File

@@ -23,7 +23,7 @@ void EnterName::init(const std::string &name) {
else {
name_ = name;
position_ = name_.length();
position_overflow_ = position_ >= NAME_SIZE ? true : false;
position_overflow_ = position_ >= NAME_SIZE;
}
// Inicializa el vector de indices con el nombre y espacios

View File

@@ -35,7 +35,7 @@ void Explosions::add(int x, int y, int size) {
// Vacia el vector de elementos finalizados
void Explosions::freeExplosions() {
if (explosions_.empty() == false) {
if (!explosions_.empty()) {
for (int i = explosions_.size() - 1; i >= 0; --i) {
if (explosions_[i]->animationIsCompleted()) {
explosions_.erase(explosions_.begin() + i);

View File

@@ -86,7 +86,7 @@ void Fade::update() {
case FadeType::CENTER: {
// Dibuja sobre el backbuffer_
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_SetRenderDrawColor(renderer_, r_, g_, b_, a_);
@@ -115,7 +115,7 @@ void Fade::update() {
case FadeType::RANDOM_SQUARE: {
if (counter_ % fade_random_squares_delay_ == 0) {
// Cambia el renderizador al backbuffer_ y modifica sus opciones
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_BlendMode blend_mode;
SDL_GetRenderDrawBlendMode(renderer_, &blend_mode);
@@ -134,7 +134,7 @@ void Fade::update() {
SDL_SetRenderTarget(renderer_, temp);
}
value_ = calculateValue(0, static_cast<int>(num_squares_width_ * num_squares_height_), static_cast<int>(counter_ * fade_random_squares_mult_ / fade_random_squares_delay_));
value_ = calculateValue(0, (num_squares_width_ * num_squares_height_), (counter_ * fade_random_squares_mult_ / fade_random_squares_delay_));
// Comprueba si ha terminado
if (counter_ * fade_random_squares_mult_ / fade_random_squares_delay_ >= num_squares_width_ * num_squares_height_) {
@@ -148,7 +148,7 @@ void Fade::update() {
// Counter debe ir de 0 a 150 <-- comprobar si esto es aún cierto
if (square_.back().h < param.fade.venetian_size) {
// Dibuja sobre el backbuffer_
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_BlendMode blend_mode;
SDL_GetRenderDrawBlendMode(renderer_, &blend_mode);
@@ -223,8 +223,8 @@ void Fade::activate() {
}
case FadeType::CENTER: {
rect1_ = {0, 0, static_cast<float>(param.game.width), 0};
rect2_ = {0, 0, static_cast<float>(param.game.width), 0};
rect1_ = {0, 0, param.game.width, 0};
rect2_ = {0, 0, param.game.width, 0};
a_ = 64;
break;
}
@@ -270,7 +270,7 @@ void Fade::activate() {
// Añade los cuadrados al vector
square_.clear();
rect1_ = {0, 0, static_cast<float>(param.game.width), 0};
rect1_ = {0, 0, param.game.width, 0};
const int MAX = param.game.height / param.fade.venetian_size;
for (int i = 0; i < MAX; ++i) {
@@ -300,7 +300,7 @@ void Fade::setColor(Color color) {
// Limpia el backbuffer
void Fade::cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a) {
// Dibujamos sobre el backbuffer_
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
// Pintamos la textura con el color del fade

View File

@@ -86,5 +86,5 @@ private:
// --- Métodos internos ---
void init(); // Inicializa variables
void cleanBackbuffer(Uint8 r, Uint8 g, Uint8 b, Uint8 a); // Limpia el backbuffer
auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
static auto calculateValue(int min, int max, int current) -> int; // Calcula el valor del fade
};

View File

@@ -45,17 +45,17 @@ void GameLogo::init() {
coffee_crisis_status_ = Status::DISABLED;
arcade_edition_status_ = Status::DISABLED;
shake_.init(1, 2, 8, XP);
zoom_ = 3.0f * ZOOM_FACTOR;
zoom_ = 3.0F * ZOOM_FACTOR;
// Inicializa el bitmap de 'Coffee'
coffee_sprite_->setPosX(XP);
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - DESP);
coffee_sprite_->setWidth(coffee_texture_->getWidth());
coffee_sprite_->setHeight(coffee_texture_->getHeight());
coffee_sprite_->setVelX(0.0f);
coffee_sprite_->setVelY(2.5f);
coffee_sprite_->setAccelX(0.0f);
coffee_sprite_->setAccelY(0.1f);
coffee_sprite_->setVelX(0.0F);
coffee_sprite_->setVelY(2.5F);
coffee_sprite_->setAccelX(0.0F);
coffee_sprite_->setAccelY(0.1F);
coffee_sprite_->setSpriteClip(0, 0, coffee_texture_->getWidth(), coffee_texture_->getHeight());
coffee_sprite_->setEnabled(true);
coffee_sprite_->setFinishedCounter(0);
@@ -67,10 +67,10 @@ void GameLogo::init() {
crisis_sprite_->setPosY(y_ + DESP);
crisis_sprite_->setWidth(crisis_texture_->getWidth());
crisis_sprite_->setHeight(crisis_texture_->getHeight());
crisis_sprite_->setVelX(0.0f);
crisis_sprite_->setVelY(-2.5f);
crisis_sprite_->setAccelX(0.0f);
crisis_sprite_->setAccelY(-0.1f);
crisis_sprite_->setVelX(0.0F);
crisis_sprite_->setVelY(-2.5F);
crisis_sprite_->setAccelX(0.0F);
crisis_sprite_->setAccelY(-0.1F);
crisis_sprite_->setSpriteClip(0, 0, crisis_texture_->getWidth(), crisis_texture_->getHeight());
crisis_sprite_->setEnabled(true);
crisis_sprite_->setFinishedCounter(0);
@@ -169,11 +169,11 @@ void GameLogo::update() {
switch (arcade_edition_status_) {
case Status::MOVING: {
zoom_ -= 0.1f * ZOOM_FACTOR;
zoom_ -= 0.1F * ZOOM_FACTOR;
arcade_edition_sprite_->setZoom(zoom_);
if (zoom_ <= 1.0f) {
if (zoom_ <= 1.0F) {
arcade_edition_status_ = Status::SHAKING;
zoom_ = 1.0f;
zoom_ = 1.0F;
arcade_edition_sprite_->setZoom(zoom_);
shake_.init(1, 2, 8, arcade_edition_sprite_->getX());
Audio::get()->playSound("title.wav");
@@ -224,7 +224,7 @@ auto GameLogo::hasFinished() const -> bool {
}
// Calcula el desplazamiento vertical inicial
auto GameLogo::getInitialVerticalDesp() -> int {
auto GameLogo::getInitialVerticalDesp() const -> int {
const float OFFSET_UP = y_;
const float OFFSET_DOWN = param.game.height - y_;

View File

@@ -69,7 +69,7 @@ private:
// --- Variables de estado ---
float x_; // Posición X del logo
float y_; // Posición Y del logo
float zoom_ = 1.0f; // Zoom aplicado al texto "ARCADE EDITION"
float zoom_ = 1.0F; // Zoom aplicado al texto "ARCADE EDITION"
int post_finished_counter_ = 1; // Contador final tras animaciones
Status coffee_crisis_status_ = Status::DISABLED; // Estado de "COFFEE CRISIS"
@@ -78,5 +78,5 @@ private:
// --- Métodos internos ---
void init(); // Inicializa las variables
auto getInitialVerticalDesp() -> int; // Calcula el desplazamiento vertical inicial
auto getInitialVerticalDesp() const -> int; // Calcula el desplazamiento vertical inicial
};

View File

@@ -99,7 +99,7 @@ void changeLang() {
const std::string CODE = "LANG";
if (Notifier::get()->checkCode(CODE)) {
Options::settings.language = Lang::getNextLangCode(Options::settings.language);
Lang::loadFromFile(getLangFile(static_cast<Lang::Code>(Options::settings.language)));
Lang::loadFromFile(getLangFile(Options::settings.language));
Section::name = Section::Name::RESET;
Section::options = Section::Options::RELOAD;
Notifier::get()->show({Lang::getText("[NOTIFICATIONS] 05") + getLangName(Options::settings.language)});
@@ -182,8 +182,9 @@ auto checkServiceButton() -> bool {
// Comprueba las entradas del menú de servicio
auto checkServiceInputs() -> bool {
if (!ServiceMenu::get()->isEnabled())
if (!ServiceMenu::get()->isEnabled()) {
return false;
}
// Teclado
{
@@ -302,7 +303,7 @@ auto checkInputs() -> bool {
}
// Saltar sección
if (Input::get()->checkAnyButton() && !ServiceMenu::get()->isEnabled()) {
if ((Input::get()->checkAnyButton() != 0) && !ServiceMenu::get()->isEnabled()) {
skipSection();
return true;
}
@@ -362,12 +363,15 @@ auto checkInputs() -> bool {
// Comprueba los inputs que se pueden introducir en cualquier sección del juego
auto check() -> bool {
if (checkServiceButton())
if (checkServiceButton()) {
return true;
if (checkServiceInputs())
}
if (checkServiceInputs()) {
return true;
if (checkInputs())
}
if (checkInputs()) {
return true;
}
return false;
}
} // namespace GlobalInputs

View File

@@ -154,7 +154,7 @@ auto Input::discoverGameControllers() -> bool {
joysticks_.clear();
for (int i = 0; i < num_joysticks_; ++i) {
// Usar el ID del joystick, no el índice
auto joy = SDL_OpenJoystick(joystick_ids[i]);
auto *joy = SDL_OpenJoystick(joystick_ids[i]);
joysticks_.push_back(joy);
// En SDL3, SDL_IsGamepad toma un SDL_JoystickID, no un índice
@@ -178,13 +178,13 @@ auto Input::discoverGameControllers() -> bool {
for (int i = 0; i < num_joysticks_; i++) {
if (SDL_IsGamepad(joystick_ids[i])) {
// Abre el mando usando el ID del joystick
auto pad = SDL_OpenGamepad(joystick_ids[i]);
auto *pad = SDL_OpenGamepad(joystick_ids[i]);
if (pad != nullptr) {
connected_controllers_.push_back(pad);
// Obtener el nombre usando el ID del joystick
const char *name_cstr = SDL_GetGamepadNameForID(joystick_ids[i]);
std::string name = name_cstr ? name_cstr : "Unknown Gamepad";
std::string name = (name_cstr != nullptr) ? name_cstr : "Unknown Gamepad";
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "#%d: %s", i, name.c_str());
controller_names_.push_back(name);
@@ -198,7 +198,7 @@ auto Input::discoverGameControllers() -> bool {
}
// Liberar el array de IDs
if (joystick_ids) {
if (joystick_ids != nullptr) {
SDL_free(joystick_ids);
}
@@ -207,7 +207,7 @@ auto Input::discoverGameControllers() -> bool {
}
// Comprueba si hay algun mando conectado
auto Input::gameControllerFound() -> bool { return num_gamepads_ > 0 ? true : false; }
auto Input::gameControllerFound() const -> bool { return num_gamepads_ > 0; }
// Obten el nombre de un mando de juego
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }
@@ -258,7 +258,7 @@ auto Input::getIndexByName(const std::string &name) const -> int {
}
// Convierte un InputAction a std::string
auto Input::inputToString(InputAction input) const -> std::string {
auto Input::inputToString(InputAction input) -> std::string {
switch (input) {
case InputAction::FIRE_LEFT:
return "input_fire_left";
@@ -276,7 +276,7 @@ auto Input::inputToString(InputAction input) const -> std::string {
}
// Convierte un std::string a InputAction
auto Input::stringToInput(const std::string &name) const -> InputAction {
auto Input::stringToInput(const std::string &name) -> InputAction {
static const std::unordered_map<std::string, InputAction> INPUT_MAP = {
{"input_fire_left", InputAction::FIRE_LEFT},
{"input_fire_center", InputAction::FIRE_CENTER},
@@ -316,19 +316,17 @@ auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat)
if (repeat) {
// Si se permite repetir, simplemente devolvemos el estado actual
return axis_active_now;
} else {
// Si no se permite repetir, aplicamos la lógica de transición
if (axis_active_now && !binding.axis_active) {
// Transición de inactivo a activo
binding.axis_active = true;
return true;
} else if (!axis_active_now && binding.axis_active) {
// Transición de activo a inactivo
binding.axis_active = false;
}
// Mantener el estado actual
return false;
} // Si no se permite repetir, aplicamos la lógica de transición
if (axis_active_now && !binding.axis_active) {
// Transición de inactivo a activo
binding.axis_active = true;
return true;
} else if (!axis_active_now && binding.axis_active) {
// Transición de activo a inactivo
binding.axis_active = false;
}
// Mantener el estado actual
return false;
}
void Input::initSDLGamePad() {
@@ -373,7 +371,7 @@ void Input::update() {
// --- MANDOS ---
for (int c = 0; c < num_gamepads_; ++c) {
for (size_t i = 0; i < controller_bindings_[c].size(); ++i) {
bool button_is_down_now = SDL_GetGamepadButton(connected_controllers_.at(c), controller_bindings_.at(c).at(i).button) != 0;
bool button_is_down_now = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(c), controller_bindings_.at(c).at(i).button)) != 0;
// El estado .is_held del fotograma anterior nos sirve para saber si es un pulso nuevo
controller_bindings_[c][i].just_pressed = button_is_down_now && !controller_bindings_[c][i].is_held;

View File

@@ -87,7 +87,7 @@ class Input {
// --- Métodos de gestión de mandos ---
auto discoverGameControllers() -> bool; // Busca si hay mandos conectados
auto gameControllerFound() -> bool; // Comprueba si hay algún mando conectado
auto gameControllerFound() const -> bool; // Comprueba si hay algún mando conectado
[[nodiscard]] auto getNumControllers() const -> int; // Obtiene el número de mandos conectados
[[nodiscard]] auto getControllerName(int controller_index) const -> std::string; // Obtiene el nombre de un mando de juego
[[nodiscard]] auto getJoyIndex(SDL_JoystickID id) const -> int; // Obtiene el índice del controlador a partir de un event.id
@@ -95,8 +95,8 @@ class Input {
// --- Métodos de consulta y utilidades ---
void printBindings(InputDevice device = InputDevice::KEYBOARD, int controller_index = 0) const; // Muestra por consola los controles asignados
[[nodiscard]] auto getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton; // Obtiene el SDL_GamepadButton asignado a un input
[[nodiscard]] auto inputToString(InputAction input) const -> std::string; // Convierte un InputAction a std::string
[[nodiscard]] auto stringToInput(const std::string &name) const -> InputAction; // Convierte un std::string a InputAction
[[nodiscard]] static auto inputToString(InputAction input) -> std::string; // Convierte un InputAction a std::string
[[nodiscard]] static auto stringToInput(const std::string &name) -> InputAction; // Convierte un std::string a InputAction
[[nodiscard]] auto getIndexByName(const std::string &name) const -> int; // Obtiene el índice a partir del nombre del mando
// --- Métodos de reseteo de estado de entrada ---

View File

@@ -18,9 +18,9 @@ Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_pt
height_ = COFFEE_MACHINE_HEIGHT;
pos_x_ = getCoffeeMachineSpawn(x, width_, play_area_.w);
pos_y_ = y;
vel_x_ = ((rand() % 3) - 1) * 0.5f;
vel_y_ = -0.1f;
accel_y_ = 0.1f;
vel_x_ = ((rand() % 3) - 1) * 0.5F;
vel_y_ = -0.1F;
accel_y_ = 0.1F;
collider_.r = 10;
break;
}
@@ -29,9 +29,9 @@ Item::Item(ItemType type, float x, float y, SDL_FRect &play_area, std::shared_pt
height_ = param.game.item_size;
pos_x_ = x;
pos_y_ = y;
vel_x_ = -1.0f + ((rand() % 5) * 0.5f);
vel_y_ = -4.0f;
accel_y_ = 0.2f;
vel_x_ = -1.0F + ((rand() % 5) * 0.5F);
vel_y_ = -4.0F;
accel_y_ = 0.2F;
collider_.r = width_ / 2;
break;
}
@@ -105,24 +105,24 @@ void Item::move() {
case ItemType::COFFEE_MACHINE:
// La máquina de café es mas pesada y tiene una fisica diferente, ademas hace ruido
floor_collision_ = true;
if (vel_y_ < 1.0f) {
if (vel_y_ < 1.0F) {
// Si la velocidad vertical es baja, detiene el objeto
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
} else {
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
vel_y_ *= -0.20f;
vel_x_ *= 0.75f;
vel_y_ *= -0.20F;
vel_x_ *= 0.75F;
}
break;
default:
// Si no es una máquina de café
if (vel_y_ < 1.0f) {
if (vel_y_ < 1.0F) {
// Si la velocidad vertical es baja, detiene el objeto
vel_y_ = vel_x_ = accel_x_ = accel_y_ = 0;
} else {
// Si la velocidad vertical es alta, el objeto rebota y pierde velocidad
vel_y_ *= -0.5f;
vel_x_ *= 0.75f;
vel_y_ *= -0.5F;
vel_x_ *= 0.75F;
}
break;
}
@@ -182,10 +182,9 @@ auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, i
if (rand() % 2 == 0) {
// Lado izquierdo
return rand() % (exclude_left - LEFT_BOUND) + LEFT_BOUND;
} else {
// Lado derecho
return rand() % (RIGHT_BOUND - exclude_right) + exclude_right;
}
} // Lado derecho
return rand() % (RIGHT_BOUND - exclude_right) + exclude_right;
} else if (can_spawn_left) {
// Solo lado izquierdo disponible
return rand() % (exclude_left - LEFT_BOUND) + LEFT_BOUND;
@@ -200,8 +199,7 @@ auto Item::getCoffeeMachineSpawn(int player_x, int item_width, int area_width, i
if (distance_to_left > distance_to_right) {
return LEFT_BOUND;
} else {
return RIGHT_BOUND - item_width;
}
return RIGHT_BOUND - item_width;
}
}

View File

@@ -74,7 +74,7 @@ private:
int height_; // Alto del objeto
float vel_x_; // Velocidad en el eje X
float vel_y_; // Velocidad en el eje Y
float accel_x_ = 0.0f; // Aceleración en el eje X
float accel_x_ = 0.0F; // Aceleración en el eje X
float accel_y_; // Aceleración en el eje Y
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
ItemType type_; // Tipo de objeto
@@ -100,5 +100,5 @@ private:
void updateTimeToLive();
// Calcula la zona de aparición de la máquina de café
auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
static auto getCoffeeMachineSpawn(int player_x, int item_width, int area_width, int margin = 2) -> int;
};

View File

@@ -27,14 +27,15 @@ auto loadFromFile(const std::string &file_path) -> bool {
texts.clear();
std::ifstream rfile(file_path);
if (!rfile.is_open())
if (!rfile.is_open()) {
return false;
}
try {
json j;
rfile >> j;
for (auto &el : j.items()) {
for (const auto &el : j.items()) {
texts[el.key()] = el.value();
}
} catch (const std::exception &e) {
@@ -48,10 +49,10 @@ auto loadFromFile(const std::string &file_path) -> bool {
// Obtiene el texto por clave
auto getText(const std::string &key) -> std::string {
auto it = texts.find(key);
if (it != texts.end())
if (it != texts.end()) {
return it->second;
else
return "[missing text: " + key + "]";
}
return "[missing text: " + key + "]";
}
// Obtiene el código del siguiente idioma disponible
@@ -68,8 +69,9 @@ auto getNextLangCode(Code lang) -> Code {
// Obtiene un idioma del vector de idiomas a partir de un código
auto getLanguage(Code code) -> Language {
for (const auto &lang : languages) {
if (lang.code == code)
if (lang.code == code) {
return lang;
}
}
// Si no se encuentra, devuelve el primero por defecto
return languages[0];
@@ -78,8 +80,9 @@ auto getLanguage(Code code) -> Language {
// Devuelve el código de un idioma a partir de un nombre
auto getCodeFromName(const std::string &name) -> Code {
for (const auto &lang : languages) {
if (lang.name == name)
if (lang.name == name) {
return lang.code;
}
}
// Si no se encuentra, devuelve el primero por defecto
return languages[0].code;
@@ -88,8 +91,9 @@ auto getCodeFromName(const std::string &name) -> Code {
// Devuelve el nombre de un idioma a partir de un código
auto getNameFromCode(Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
if (lang.code == code) {
return lang.name;
}
}
// Si no se encuentra, devuelve el nombre del primer idioma por defecto
return languages[0].name;
@@ -138,8 +142,9 @@ void updateDifficultyNames() {
// Obtiene una fichero a partir de un lang::Code
auto getLanguageFileName(Lang::Code code) -> std::string {
for (const auto &lang : languages) {
if (lang.code == code)
if (lang.code == code) {
return Asset::get()->get(lang.file_name);
}
}
// Si no se encuentra, devuelve el fichero del primer idioma por defecto
return Asset::get()->get(languages[0].file_name);

View File

@@ -73,9 +73,9 @@ void ManageHiScoreTable::sort() {
auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
clear();
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "rb");
auto *file = SDL_IOFromFile(file_path.c_str(), "rb");
if (file) {
if (file != nullptr) {
table_.clear(); // Limpia la tabla actual
// Lee el número de entradas en la tabla
@@ -119,9 +119,9 @@ auto ManageHiScoreTable::loadFromFile(const std::string &file_path) -> bool {
// Guarda la tabla en un fichero
auto ManageHiScoreTable::saveToFile(const std::string &file_path) -> bool {
auto success = true;
auto file = SDL_IOFromFile(file_path.c_str(), "w+b");
auto *file = SDL_IOFromFile(file_path.c_str(), "w+b");
if (file) {
if (file != nullptr) {
// Guarda el número de entradas en la tabla
int table_size = static_cast<int>(table_.size());
SDL_WriteIO(file, &table_size, sizeof(int));

View File

@@ -16,34 +16,33 @@ MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_FRect pos)
: Sprite(texture, pos),
x_(pos.x),
y_(pos.y),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),
zoom_w_(1.0F),
zoom_h_(1.0F),
flip_(SDL_FLIP_NONE) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture),
rotate_(Rotate()),
zoom_w_(1.0f),
zoom_h_(1.0f),
zoom_w_(1.0F),
zoom_h_(1.0F),
flip_(SDL_FLIP_NONE) { Sprite::clear(); }
// Reinicia todas las variables
void MovingSprite::clear() {
x_ = 0.0f; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y
x_ = 0.0F; // Posición en el eje X
y_ = 0.0F; // Posición en el eje Y
vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
vx_ = 0.0F; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0F; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
ax_ = 0.0F; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0F; // Aceleración en el eje Y. Variación de la velocidad
rotate_ = Rotate(); // Inicializa la estructura
zoom_w_ = 1.0f; // Zoom aplicado a la anchura
zoom_h_ = 1.0f; // Zoom aplicado a la altura
zoom_w_ = 1.0F; // Zoom aplicado a la anchura
zoom_h_ = 1.0F; // Zoom aplicado a la altura
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
@@ -90,8 +89,8 @@ void MovingSprite::setRotate(bool enable) {
// Establece la posición y_ el tamaño del objeto
void MovingSprite::setPos(SDL_FRect rect) {
x_ = static_cast<float>(rect.x);
y_ = static_cast<float>(rect.y);
x_ = rect.x;
y_ = rect.y;
pos_ = rect;
}

View File

@@ -138,8 +138,9 @@ void Notifier::show(std::vector<std::string> texts, int icon, const std::string
// Encuentra la cadena más larga
std::string longest;
for (const auto &text : texts) {
if (text.length() > longest.length())
if (text.length() > longest.length()) {
longest = text;
}
}
// Inicializa variables

View File

@@ -62,7 +62,7 @@ private:
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), rect{0, 0, 0, 0}, code("") {}
: texture(nullptr), sprite(nullptr), rect{0, 0, 0, 0} {}
};
// --- Objetos y punteros ---

View File

@@ -300,18 +300,15 @@ void applyPendingChanges() {
}
void checkPendingChanges() {
if (settings.language != pending_changes.new_language ||
settings.difficulty != pending_changes.new_difficulty) {
pending_changes.has_pending_changes = true;
} else {
pending_changes.has_pending_changes = false;
}
pending_changes.has_pending_changes = settings.language != pending_changes.new_language ||
settings.difficulty != pending_changes.new_difficulty;
}
auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode {
for (const auto &difficulty : difficulties) {
if (difficulty.name == name)
if (difficulty.name == name) {
return difficulty.code;
}
}
// Si no se encuentra, devuelve el primero por defecto
return difficulties[0].code;
@@ -319,8 +316,9 @@ auto getDifficultyCodeFromName(const std::string &name) -> DifficultyCode {
auto getDifficultyNameFromCode(DifficultyCode code) -> std::string {
for (const auto &difficulty : difficulties) {
if (difficulty.code == code)
if (difficulty.code == code) {
return difficulty.name;
}
}
// Si no se encuentra, devuelve el nombre del primero por defecto
return difficulties[0].name;

View File

@@ -50,8 +50,7 @@ struct VideoOptions {
std::string info; // Información sobre el modo de vídeo
// Constructor por defecto con valores iniciales
VideoOptions()
: info() {}
VideoOptions() {}
};
// --- Opciones de música ---
@@ -81,8 +80,8 @@ struct AudioOptions {
// Constructor por defecto
AudioOptions()
: music(),
sound() {}
{}
};
// --- Opciones de configuración ---
@@ -97,8 +96,7 @@ struct SettingsOptions {
// Constructor por defecto con valores iniciales
SettingsOptions()
: last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}),
config_file() {}
: last_hi_score_entry({INVALID_INDEX, INVALID_INDEX}) {}
// Reinicia las últimas entradas de puntuación
void clearLastHiScoreEntries() {
@@ -121,7 +119,7 @@ struct GamepadOptions {
GamepadOptions()
: index(INVALID_INDEX),
player_id(INVALID_INDEX),
name(),
inputs{
InputAction::FIRE_LEFT,
InputAction::FIRE_CENTER,

View File

@@ -63,10 +63,10 @@ void initParam() {
param.background.attenuate_color = Color(255, 255, 255, 0);
// BALLOONS
param.balloon.settings.at(0) = ParamBalloon::Settings(0.09f, 2.60f);
param.balloon.settings.at(1) = ParamBalloon::Settings(0.10f, 3.50f);
param.balloon.settings.at(2) = ParamBalloon::Settings(0.10f, 4.50f);
param.balloon.settings.at(3) = ParamBalloon::Settings(0.10f, 4.95f);
param.balloon.settings.at(0) = ParamBalloon::Settings(0.09F, 2.60F);
param.balloon.settings.at(1) = ParamBalloon::Settings(0.10F, 3.50F);
param.balloon.settings.at(2) = ParamBalloon::Settings(0.10F, 4.50F);
param.balloon.settings.at(3) = ParamBalloon::Settings(0.10F, 4.95F);
param.balloon.color.at(0) = "blue";
param.balloon.color.at(1) = "orange";
@@ -102,7 +102,9 @@ void loadParamsFromFile(const std::string &file_path) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\nReading file: %s", getFileName(file_path).c_str());
std::string line, param1, param2;
std::string line;
std::string param1;
std::string param2;
while (std::getline(file, line)) {
// Elimina comentarios
auto comment_pos = line.find('#');

View File

@@ -51,21 +51,24 @@ void PathSprite::render() {
// Añade un recorrido
void PathSprite::addPath(Path path, bool centered) {
PathCentered path_centered = PathCentered::NONE;
if (centered)
if (centered) {
path_centered = (path.spots.back().x == path.spots.front().x) ? PathCentered::ON_X : PathCentered::ON_Y;
}
switch (path_centered) {
case PathCentered::ON_X: {
const int X = path.spots.back().x - pos_.w / 2;
for (auto &spot : path.spots)
for (auto &spot : path.spots) {
spot.x = X;
}
paths_.emplace_back(path);
break;
}
case PathCentered::ON_Y: {
const int Y = path.spots.back().y - pos_.h / 2;
for (auto &spot : path.spots)
for (auto &spot : path.spots) {
spot.y = Y;
}
paths_.emplace_back(path);
break;
}
@@ -87,7 +90,7 @@ void PathSprite::addPath(std::vector<SDL_FPoint> spots, int waiting_counter) {
// Habilita el objeto
void PathSprite::enable() {
if (paths_.size() == 0 || enabled_) {
if (paths_.empty() || enabled_) {
return;
}
@@ -141,4 +144,4 @@ void PathSprite::goToNextPathOrDie() {
}
// Indica si ha terminado todos los recorridos
auto PathSprite::hasFinished() -> bool { return has_finished_; }
auto PathSprite::hasFinished() const -> bool { return has_finished_; }

View File

@@ -58,7 +58,7 @@ class PathSprite : public Sprite {
// --- Estado y control ---
void enable(); // Habilita el objeto
auto hasFinished() -> bool; // Indica si ha terminado todos los recorridos
[[nodiscard]] auto hasFinished() const -> bool; // Indica si ha terminado todos los recorridos
// --- Getters ---
[[nodiscard]] auto getCurrentPath() const -> int { return current_path_; } // Devuelve el índice del recorrido actual

View File

@@ -58,7 +58,7 @@ void Player::init() {
vel_x_ = 0;
vel_y_ = 0;
score_ = 0;
score_multiplier_ = 1.0f;
score_multiplier_ = 1.0F;
cant_fire_counter_ = 10;
enter_name_->init(last_enter_name_);
@@ -172,7 +172,7 @@ void Player::move() {
// Si el jugador toca el suelo rebota y si tiene poca velocidad, se detiene y cambia de estado
if (player_sprite_->getPosY() > play_area_.h - HEIGHT) {
if (player_sprite_->getVelY() < 2.0f) {
if (player_sprite_->getVelY() < 2.0F) {
// Si la velocidad de rebote es baja, lo detiene y cambia de estado
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
@@ -184,8 +184,8 @@ void Player::move() {
} else {
// Decrementa las velocidades de rebote
player_sprite_->setPosY(play_area_.h - HEIGHT);
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5f);
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75f);
player_sprite_->setVelY(player_sprite_->getVelY() * -0.5F);
player_sprite_->setVelX(player_sprite_->getVelX() * 0.75F);
player_sprite_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
playSound("jump.wav");
}
@@ -218,7 +218,7 @@ void Player::move() {
default:
break;
}
pos_x_ += vel_x_ * 2.0f;
pos_x_ += vel_x_ * 2.0F;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
@@ -295,7 +295,7 @@ void Player::move() {
break;
}
case PlayerState::CREDITS: {
pos_x_ += vel_x_ / 2.0f;
pos_x_ += vel_x_ / 2.0F;
if (vel_x_ > 0) {
// setInputPlaying(InputAction::RIGHT);
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
@@ -503,7 +503,7 @@ void Player::updateScoreboard() {
}
// Cambia el modo del marcador
void Player::setScoreboardMode(ScoreboardMode mode) {
void Player::setScoreboardMode(ScoreboardMode mode) const {
if (!demo_) {
Scoreboard::get()->setMode(getScoreBoardPanel(), mode);
}
@@ -555,9 +555,9 @@ void Player::setPlayingState(PlayerState state) {
// Activa la animación de rodar
player_sprite_->setCurrentAnimation("rolling");
player_sprite_->setAnimationSpeed(4);
player_sprite_->setAccelY(0.2f);
player_sprite_->setVelY(-6.6f);
(rand() % 2 == 0) ? player_sprite_->setVelX(3.3f) : player_sprite_->setVelX(-3.3f);
player_sprite_->setAccelY(0.2F);
player_sprite_->setVelY(-6.6F);
(rand() % 2 == 0) ? player_sprite_->setVelX(3.3F) : player_sprite_->setVelX(-3.3F);
break;
}
case PlayerState::TITLE_ANIMATION: {
@@ -567,15 +567,15 @@ void Player::setPlayingState(PlayerState state) {
break;
}
case PlayerState::TITLE_HIDDEN: {
player_sprite_->setVelX(0.0f);
player_sprite_->setVelY(0.0f);
player_sprite_->setVelX(0.0F);
player_sprite_->setVelY(0.0F);
break;
}
case PlayerState::CONTINUE_TIME_OUT: {
// Activa la animación de morir
player_sprite_->setAccelY(0.2f);
player_sprite_->setVelY(-4.0f);
player_sprite_->setVelX(0.0f);
player_sprite_->setAccelY(0.2F);
player_sprite_->setVelY(-4.0F);
player_sprite_->setVelX(0.0F);
player_sprite_->setCurrentAnimation("rolling");
player_sprite_->setAnimationSpeed(5);
setScoreboardMode(ScoreboardMode::GAME_OVER);
@@ -631,14 +631,14 @@ void Player::setPlayingState(PlayerState state) {
// Aumenta el valor de la variable hasta un máximo
void Player::incScoreMultiplier() {
score_multiplier_ += 0.1f;
score_multiplier_ = std::min(score_multiplier_, 5.0f);
score_multiplier_ += 0.1F;
score_multiplier_ = std::min(score_multiplier_, 5.0F);
}
// Decrementa el valor de la variable hasta un mínimo
void Player::decScoreMultiplier() {
score_multiplier_ -= 0.1f;
score_multiplier_ = std::max(score_multiplier_, 1.0f);
score_multiplier_ -= 0.1F;
score_multiplier_ = std::max(score_multiplier_, 1.0F);
}
// Establece el valor del estado
@@ -649,7 +649,7 @@ void Player::setInvulnerable(bool value) {
// Monitoriza el estado
void Player::updateInvulnerable() {
if (playing_state_ == PlayerState::PLAYING)
if (playing_state_ == PlayerState::PLAYING) {
if (invulnerable_) {
if (invulnerable_counter_ > 0) {
--invulnerable_counter_;
@@ -659,6 +659,7 @@ void Player::updateInvulnerable() {
player_sprite_->getTexture()->setPalette(coffees_);
}
}
}
}
// Establece el valor de la variable
@@ -669,11 +670,12 @@ void Player::setPowerUp() {
// Actualiza el valor de la variable
void Player::updatePowerUp() {
if (playing_state_ == PlayerState::PLAYING)
if (playing_state_ == PlayerState::PLAYING) {
if (power_up_) {
--power_up_counter_;
power_up_ = power_up_counter_ > 0;
}
}
}
// Concede un toque extra al jugador
@@ -693,13 +695,13 @@ void Player::removeExtraHit() {
player_sprite_->getTexture()->setPalette(coffees_);
}
extra_hit_ = coffees_ == 0 ? false : true;
extra_hit_ = coffees_ != 0;
}
// Actualiza el circulo de colisión a la posición del jugador
void Player::shiftColliders() {
collider_.x = static_cast<int>(pos_x_ + (WIDTH / 2));
collider_.y = static_cast<int>(pos_y_ + (HEIGHT / 2));
collider_.y = (pos_y_ + (HEIGHT / 2));
}
// Pone las texturas del jugador
@@ -787,16 +789,23 @@ void Player::shiftSprite() {
power_sprite_->setPosX(getPosX() - power_up_desp_x_);
}
void Player::playSound(const std::string &name) {
if (demo_)
// Hace sonar un sonido
void Player::playSound(const std::string &name) const {
if (demo_) {
return;
}
static auto audio_ = Audio::get();
static auto *audio_ = Audio::get();
audio_->playSound(name);
}
// Indica si se puede dibujar el objeto
auto Player::isRenderable() const -> bool {
return !isWaiting() && !isGameOver() && !isTitleHidden();
};
// Añade una puntuación a la tabla de records
void Player::addScoreToScoreBoard() {
void Player::addScoreToScoreBoard() const {
const auto ENTRY = HiScoreEntry(trim(getLastEnterName()), getScore(), get1CC());
auto manager = std::make_unique<ManageHiScoreTable>(Options::settings.hi_score_table);
Options::settings.last_hi_score_entry.at(getId() - 1) = manager->add(ENTRY);

View File

@@ -61,171 +61,171 @@ enum class PlayerState {
// --- Clase Player ---
class Player {
public:
// --- Constructor y destructor ---
Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
~Player() = default;
public:
// --- Constructor y destructor ---
Player(int id, float x, int y, bool demo, SDL_FRect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
~Player() = default;
// --- Inicialización y ciclo de vida ---
void init(); // Inicializa el jugador
void update(); // Actualiza estado, animación y contadores
void render(); // Dibuja el jugador en pantalla
// --- Inicialización y ciclo de vida ---
void init(); // Inicializa el jugador
void update(); // Actualiza estado, animación y contadores
void render(); // Dibuja el jugador en pantalla
// --- Entrada y control ---
void setInput(InputAction input); // Procesa entrada general
void setInputPlaying(InputAction input); // Procesa entrada en modo jugando
void setInputEnteringName(InputAction input); // Procesa entrada al introducir nombre
// --- Entrada y control ---
void setInput(InputAction input); // Procesa entrada general
void setInputPlaying(InputAction input); // Procesa entrada en modo jugando
void setInputEnteringName(InputAction input); // Procesa entrada al introducir nombre
// --- Movimiento y animación ---
void move(); // Mueve el jugador
void setAnimation(); // Establece la animación según el estado
// --- Movimiento y animación ---
void move(); // Mueve el jugador
void setAnimation(); // Establece la animación según el estado
// --- Texturas y animaciones ---
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
// --- Texturas y animaciones ---
void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture); // Cambia las texturas del jugador
// --- Estados y contadores ---
void updateCooldown(); // Actualiza el cooldown de disparo
// --- Estados y contadores ---
void updateCooldown(); // Actualiza el cooldown de disparo
// --- Puntuación y marcador ---
void addScore(int score); // Añade puntos
void incScoreMultiplier(); // Incrementa el multiplicador
void decScoreMultiplier(); // Decrementa el multiplicador
// --- Puntuación y marcador ---
void addScore(int score); // Añade puntos
void incScoreMultiplier(); // Incrementa el multiplicador
void decScoreMultiplier(); // Decrementa el multiplicador
// --- Estados de juego ---
void setPlayingState(PlayerState state); // Cambia el estado de juego
void setInvulnerable(bool value); // Establece el valor del estado de invulnerabilidad
void setPowerUp(); // Activa el modo PowerUp
void updatePowerUp(); // Actualiza el valor de PowerUp
void giveExtraHit(); // Concede un toque extra al jugador
void removeExtraHit(); // Quita el toque extra al jugador
void decContinueCounter(); // Decrementa el contador de continuar
// --- Estados de juego ---
void setPlayingState(PlayerState state); // Cambia el estado de juego
void setInvulnerable(bool value); // Establece el valor del estado de invulnerabilidad
void setPowerUp(); // Activa el modo PowerUp
void updatePowerUp(); // Actualiza el valor de PowerUp
void giveExtraHit(); // Concede un toque extra al jugador
void removeExtraHit(); // Quita el toque extra al jugador
void decContinueCounter(); // Decrementa el contador de continuar
// --- Getters y comprobaciones de estado ---
[[nodiscard]] auto getRecordNamePos() const -> int; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// --- Getters y comprobaciones de estado ---
[[nodiscard]] auto getRecordNamePos() const -> int; // Obtiene la posición que se está editando del nombre del jugador para la tabla de mejores puntuaciones
// Comprobación de playing_state
[[nodiscard]] auto isLyingOnTheFloorForever() const -> bool { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
[[nodiscard]] auto isCelebrating() const -> bool { return playing_state_ == PlayerState::CELEBRATING; }
[[nodiscard]] auto isContinue() const -> bool { return playing_state_ == PlayerState::CONTINUE; }
[[nodiscard]] auto isDying() const -> bool { return playing_state_ == PlayerState::ROLLING; }
[[nodiscard]] auto isEnteringName() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME; }
[[nodiscard]] auto isShowingName() const -> bool { return playing_state_ == PlayerState::SHOWING_NAME; }
[[nodiscard]] auto isEnteringNameGameCompleted() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
[[nodiscard]] auto isLeavingScreen() const -> bool { return playing_state_ == PlayerState::LEAVING_SCREEN; }
[[nodiscard]] auto isGameOver() const -> bool { return playing_state_ == PlayerState::GAME_OVER; }
[[nodiscard]] auto isPlaying() const -> bool { return playing_state_ == PlayerState::PLAYING; }
[[nodiscard]] auto isWaiting() const -> bool { return playing_state_ == PlayerState::WAITING; }
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == PlayerState::TITLE_HIDDEN; }
// Comprobación de playing_state
[[nodiscard]] auto isLyingOnTheFloorForever() const -> bool { return playing_state_ == PlayerState::LYING_ON_THE_FLOOR_FOREVER; }
[[nodiscard]] auto isCelebrating() const -> bool { return playing_state_ == PlayerState::CELEBRATING; }
[[nodiscard]] auto isContinue() const -> bool { return playing_state_ == PlayerState::CONTINUE; }
[[nodiscard]] auto isDying() const -> bool { return playing_state_ == PlayerState::ROLLING; }
[[nodiscard]] auto isEnteringName() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME; }
[[nodiscard]] auto isShowingName() const -> bool { return playing_state_ == PlayerState::SHOWING_NAME; }
[[nodiscard]] auto isEnteringNameGameCompleted() const -> bool { return playing_state_ == PlayerState::ENTERING_NAME_GAME_COMPLETED; }
[[nodiscard]] auto isLeavingScreen() const -> bool { return playing_state_ == PlayerState::LEAVING_SCREEN; }
[[nodiscard]] auto isGameOver() const -> bool { return playing_state_ == PlayerState::GAME_OVER; }
[[nodiscard]] auto isPlaying() const -> bool { return playing_state_ == PlayerState::PLAYING; }
[[nodiscard]] auto isWaiting() const -> bool { return playing_state_ == PlayerState::WAITING; }
[[nodiscard]] auto isTitleHidden() const -> bool { return playing_state_ == PlayerState::TITLE_HIDDEN; }
// Getters
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
[[nodiscard]] auto isEligibleForHighScore() const -> bool { return score_ > Options::settings.hi_score_table.back().score; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isPowerUp() const -> bool { return power_up_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getScoreMultiplier() const -> float { return score_multiplier_; }
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
[[nodiscard]] auto getController() const -> int { return controller_index_; }
[[nodiscard]] auto getHeight() const -> int { return HEIGHT; }
[[nodiscard]] auto getId() const -> int { return id_; }
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
[[nodiscard]] auto getPosX() const -> int { return static_cast<int>(pos_x_); }
[[nodiscard]] auto getPosY() const -> int { return pos_y_; }
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
[[nodiscard]] auto getScore() const -> int { return score_; }
[[nodiscard]] auto getScoreBoardPanel() const -> int { return scoreboard_panel_; }
[[nodiscard]] auto getWidth() const -> int { return WIDTH; }
[[nodiscard]] auto getPlayingState() const -> PlayerState { return playing_state_; }
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
// Getters
[[nodiscard]] auto canFire() const -> bool { return cant_fire_counter_ <= 0; }
[[nodiscard]] auto hasExtraHit() const -> bool { return extra_hit_; }
[[nodiscard]] auto isCooling() const -> bool { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
[[nodiscard]] auto isRecoiling() const -> bool { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
[[nodiscard]] auto isEligibleForHighScore() const -> bool { return score_ > Options::settings.hi_score_table.back().score; }
[[nodiscard]] auto isInvulnerable() const -> bool { return invulnerable_; }
[[nodiscard]] auto isPowerUp() const -> bool { return power_up_; }
auto getCollider() -> Circle & { return collider_; }
[[nodiscard]] auto getScoreMultiplier() const -> float { return score_multiplier_; }
[[nodiscard]] auto getCoffees() const -> int { return coffees_; }
[[nodiscard]] auto getContinueCounter() const -> int { return continue_counter_; }
[[nodiscard]] auto getController() const -> int { return controller_index_; }
[[nodiscard]] static auto getHeight() -> int { return HEIGHT; }
[[nodiscard]] auto getId() const -> int { return id_; }
[[nodiscard]] auto getInvulnerableCounter() const -> int { return invulnerable_counter_; }
[[nodiscard]] auto getPosX() const -> int { return static_cast<int>(pos_x_); }
[[nodiscard]] auto getPosY() const -> int { return pos_y_; }
[[nodiscard]] auto getPowerUpCounter() const -> int { return power_up_counter_; }
[[nodiscard]] auto getRecordName() const -> std::string { return enter_name_ ? enter_name_->getFinalName() : "xxx"; }
[[nodiscard]] auto getLastEnterName() const -> std::string { return last_enter_name_; }
[[nodiscard]] auto getScore() const -> int { return score_; }
[[nodiscard]] auto getScoreBoardPanel() const -> int { return scoreboard_panel_; }
[[nodiscard]] static auto getWidth() -> int { return WIDTH; }
[[nodiscard]] auto getPlayingState() const -> PlayerState { return playing_state_; }
[[nodiscard]] auto getName() const -> const std::string & { return name_; }
[[nodiscard]] auto get1CC() const -> bool { return game_completed_ && credits_used_ == 1; }
[[nodiscard]] auto getEnterNamePositionOverflow() const -> bool { return enter_name_ ? enter_name_->getPositionOverflow() : false; }
// Setters inline
void setController(int index) { controller_index_ = index; }
void setCantFireCounter(int counter) { recoiling_state_duration_ = cant_fire_counter_ = counter; }
void setFiringState(PlayerState state) { firing_state_ = state; }
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
void setName(const std::string &name) { name_ = name; }
void setPowerUpCounter(int value) { power_up_counter_ = value; }
void setScore(int score) { score_ = score; }
void setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
void setScoreMultiplier(float value) { score_multiplier_ = value; }
void setWalkingState(PlayerState state) { walking_state_ = state; }
void addCredit() { ++credits_used_; }
// Setters inline
void setController(int index) { controller_index_ = index; }
void setCantFireCounter(int counter) { recoiling_state_duration_ = cant_fire_counter_ = counter; }
void setFiringState(PlayerState state) { firing_state_ = state; }
void setInvulnerableCounter(int value) { invulnerable_counter_ = value; }
void setName(const std::string &name) { name_ = name; }
void setPowerUpCounter(int value) { power_up_counter_ = value; }
void setScore(int score) { score_ = score; }
void setScoreBoardPanel(int panel) { scoreboard_panel_ = panel; }
void setScoreMultiplier(float value) { score_multiplier_ = value; }
void setWalkingState(PlayerState state) { walking_state_ = state; }
void addCredit() { ++credits_used_; }
private:
// --- Constantes ---
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable
static constexpr int WIDTH = 30; // Anchura
static constexpr int HEIGHT = 30; // Altura
static constexpr float BASE_SPEED = 1.5f; // Velocidad base del jugador
static constexpr int COOLING_DURATION = 50;
static constexpr int COOLING_COMPLETE = 0;
private:
// --- Constantes ---
static constexpr int POWERUP_COUNTER = 1500; // Duración del estado PowerUp
static constexpr int INVULNERABLE_COUNTER = 200; // Duración del estado invulnerable
static constexpr int WIDTH = 30; // Anchura
static constexpr int HEIGHT = 30; // Altura
static constexpr float BASE_SPEED = 1.5F; // Velocidad base del jugador
static constexpr int COOLING_DURATION = 50;
static constexpr int COOLING_COMPLETE = 0;
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
// --- Objetos y punteros ---
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
// --- Variables de estado ---
int id_; // Número de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_FRect play_area_; // Rectángulo con la zona de juego
float pos_x_ = 0.0f; // Posición en el eje X
int pos_y_ = 0; // Posición en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje X
int vel_y_ = 0.0f; // Cantidad de píxeles a desplazarse en el eje Y
int cant_fire_counter_ = 0; // Contador durante el cual no puede disparar
int recoiling_state_counter_ = 0; // Contador para la animación del estado de retroceso
int recoiling_state_duration_ = 0; // Numero de frames que dura el estado de retroceso
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0f; // Multiplicador de puntos
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
bool demo_ = false; // Para que el jugador sepa si está en el modo demostración
int name_entry_idle_counter_ = 0; // Contador para poner nombre
int name_entry_total_counter_ = 0; // Segundos totales que lleva acumulados poniendo nombre
Uint32 name_entry_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
bool game_completed_ = false; // Indica si ha completado el juego
int credits_used_ = 1; // Indica el número de veces que ha continuado
std::string last_enter_name_; // Último nombre introducido en la tabla de puntuaciones
// --- Variables de estado ---
int id_; // Número de identificación para el jugador. Player1 = 1, Player2 = 2
SDL_FRect play_area_; // Rectángulo con la zona de juego
float pos_x_ = 0.0F; // Posición en el eje X
int pos_y_ = 0; // Posición en el eje Y
float default_pos_x_; // Posición inicial para el jugador
int default_pos_y_; // Posición inicial para el jugador
float vel_x_ = 0.0F; // Cantidad de píxeles a desplazarse en el eje X
int vel_y_ = 0.0F; // Cantidad de píxeles a desplazarse en el eje Y
int cant_fire_counter_ = 0; // Contador durante el cual no puede disparar
int recoiling_state_counter_ = 0; // Contador para la animación del estado de retroceso
int recoiling_state_duration_ = 0; // Numero de frames que dura el estado de retroceso
int cooling_state_counter_ = 0; // Contador para la animación del estado cooling
int score_ = 0; // Puntos del jugador
float score_multiplier_ = 1.0F; // Multiplicador de puntos
PlayerState walking_state_ = PlayerState::WALKING_STOP; // Estado del jugador al moverse
PlayerState firing_state_ = PlayerState::FIRING_NONE; // Estado del jugador al disparar
PlayerState playing_state_ = PlayerState::WAITING; // Estado del jugador en el juego
bool invulnerable_ = true; // Indica si el jugador es invulnerable
int invulnerable_counter_ = INVULNERABLE_COUNTER; // Contador para la invulnerabilidad
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
int coffees_ = 0; // Indica cuántos cafés lleva acumulados
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
int power_up_counter_ = POWERUP_COUNTER; // Temporizador para el modo PowerUp
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
Circle collider_ = Circle(0, 0, 9); // Círculo de colisión del jugador
int continue_counter_ = 10; // Contador para poder continuar
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador
int controller_index_ = 0; // Índice del array de mandos que utilizará para moverse
bool demo_ = false; // Para que el jugador sepa si está en el modo demostración
int name_entry_idle_counter_ = 0; // Contador para poner nombre
int name_entry_total_counter_ = 0; // Segundos totales que lleva acumulados poniendo nombre
Uint32 name_entry_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
Uint32 showing_name_ticks_ = 0; // Tiempo en el que se entra al estado SHOWING_NAME
int step_counter_ = 0; // Cuenta los pasos para los estados en los que camina automáticamente
bool game_completed_ = false; // Indica si ha completado el juego
int credits_used_ = 1; // Indica el número de veces que ha continuado
std::string last_enter_name_; // Último nombre introducido en la tabla de puntuaciones
// --- Métodos internos ---
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
void shiftSprite(); // Recoloca el sprite
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
void updateContinueCounter(); // Actualiza el contador de continue
void updateEnterNameCounter(); // Actualiza el contador de entrar nombre
void updateShowingName(); // Actualiza el estado SHOWING_NAME
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
void updateScoreboard(); // Actualiza el panel del marcador
void setScoreboardMode(ScoreboardMode mode); // Cambia el modo del marcador
void playSound(const std::string &name); // Hace sonar un sonido
[[nodiscard]] auto isRenderable() const -> bool { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
// --- Métodos internos ---
void shiftColliders(); // Actualiza el círculo de colisión a la posición del jugador
void shiftSprite(); // Recoloca el sprite
void updateInvulnerable(); // Monitoriza el estado de invulnerabilidad
void updateContinueCounter(); // Actualiza el contador de continue
void updateEnterNameCounter(); // Actualiza el contador de entrar nombre
void updateShowingName(); // Actualiza el estado SHOWING_NAME
void decNameEntryCounter(); // Decrementa el contador de entrar nombre
void updateScoreboard(); // Actualiza el panel del marcador
void setScoreboardMode(ScoreboardMode mode) const; // Cambia el modo del marcador
void playSound(const std::string &name) const; // Hace sonar un sonido
[[nodiscard]] auto isRenderable() const -> bool; // Indica si se puede dibujar el objeto
void addScoreToScoreBoard() const; // Añade una puntuación a la tabla de records
};

View File

@@ -54,7 +54,7 @@ void Resource::load() {
initProgressBar();
// Muerstra la ventana y desactiva el sincronismo vertical
auto screen = Screen::get();
auto *screen = Screen::get();
auto vsync = screen->getVSync();
screen->setVSync(false);
@@ -337,7 +337,7 @@ void Resource::createText() {
// Vacía el vector de sonidos y libera la memoria asociada
void Resource::clearSounds() {
for (auto &sound : sounds_) {
if (sound.sound) {
if (sound.sound != nullptr) {
JA_DeleteSound(sound.sound);
sound.sound = nullptr;
}
@@ -348,7 +348,7 @@ void Resource::clearSounds() {
// Vacía el vector de músicas y libera la memoria asociada
void Resource::clearMusics() {
for (auto &music : musics_) {
if (music.music) {
if (music.music != nullptr) {
JA_DeleteMusic(music.music);
music.music = nullptr;
}
@@ -378,8 +378,8 @@ void Resource::calculateTotalResources() {
// Muestra el progreso de carga en pantalla (barra y texto)
void Resource::renderProgress() {
// Obtiene la pantalla y el renderer
auto screen = Screen::get();
auto renderer = screen->getRenderer();
auto *screen = Screen::get();
auto *renderer = screen->getRenderer();
// Actualiza la lógica principal de la pantalla (input, etc.)
screen->coreUpdate();
@@ -437,9 +437,9 @@ void Resource::updateLoadingProgress(std::string name) {
// Inicializa los rectangulos que definen la barra de progreso
void Resource::initProgressBar() {
constexpr float X_PADDING = 20.0f;
constexpr float Y_PADDING = 20.0f;
constexpr float BAR_HEIGHT = 10.0f;
constexpr float X_PADDING = 20.0F;
constexpr float Y_PADDING = 20.0F;
constexpr float BAR_HEIGHT = 10.0F;
const float BAR_Y_POSITION = param.game.height - BAR_HEIGHT - Y_PADDING;
const float WIRED_BAR_WIDTH = param.game.width - (X_PADDING * 2);

View File

@@ -136,7 +136,7 @@ class Resource {
// --- Métodos internos para gestionar el progreso ---
void calculateTotalResources(); // Calcula el número de recursos para cargar
void renderProgress(); // Muestra el progreso de carga
void checkEvents(); // Comprueba los eventos durante la carga
static void checkEvents(); // Comprueba los eventos durante la carga
void updateLoadingProgress(std::string name); // Actualiza el progreso de carga
void initProgressBar(); // Inicializa los rectangulos que definen la barra de progreso
void updateProgressBar(); // Actualiza la barra de estado

View File

@@ -57,7 +57,7 @@ Scoreboard::Scoreboard()
recalculateAnchors();
power_meter_sprite_->setPosition(SDL_FRect{
static_cast<float>(slot4_2_.x - 20),
static_cast<float>(slot4_2_.y),
slot4_2_.y,
40,
7});
@@ -76,12 +76,12 @@ Scoreboard::Scoreboard()
}
Scoreboard::~Scoreboard() {
if (background_) {
if (background_ != nullptr) {
SDL_DestroyTexture(background_);
}
for (auto texture : panel_texture_) {
if (texture) {
for (auto *texture : panel_texture_) {
if (texture != nullptr) {
SDL_DestroyTexture(texture);
}
}
@@ -142,7 +142,7 @@ void Scoreboard::setPos(SDL_FRect rect) {
// Rellena los diferentes paneles del marcador
void Scoreboard::fillPanelTextures() {
// Guarda a donde apunta actualmente el renderizador
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
// Genera el contenido de cada panel_
for (size_t i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
@@ -208,12 +208,12 @@ void Scoreboard::fillPanelTextures() {
// POWERMETER
power_meter_sprite_->setSpriteClip(0, 0, 40, 7);
power_meter_sprite_->render();
power_meter_sprite_->setSpriteClip(40, 0, int(power_ * 40.0f), 7);
power_meter_sprite_->setSpriteClip(40, 0, int(power_ * 40.0F), 7);
power_meter_sprite_->render();
// HI-SCORE
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 4"), 1, text_color1_);
const std::string NAME = hi_score_name_ == "" ? "" : hi_score_name_ + " - ";
const std::string NAME = hi_score_name_.empty() ? "" : hi_score_name_ + " - ";
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_4_.x, slot4_4_.y, NAME + updateScoreText(hi_score_), 1, text_color2_);
break;
}
@@ -237,7 +237,7 @@ void Scoreboard::fillPanelTextures() {
// ENTER NAME
{
text_scoreboard_->writeDX(TEXT_CENTER | TEXT_COLOR, slot4_3_.x, slot4_3_.y, Lang::getText("[SCOREBOARD] 11"), 1, text_color1_);
SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5.0f, 7.0f};
SDL_FRect rect = {enter_name_pos_.x, enter_name_pos_.y, 5.0F, 7.0F};
// Recorre todos los slots de letras del nombre
for (size_t j = 0; j < NAME_SIZE; ++j) {
@@ -323,7 +323,7 @@ void Scoreboard::fillBackgroundTexture() {
// Recalcula las anclas de los elementos
void Scoreboard::recalculateAnchors() {
// Recalcula la posición y el tamaño de los paneles
const float PANEL_WIDTH = (float)rect_.w / (float)SCOREBOARD_MAX_PANELS;
const float PANEL_WIDTH = rect_.w / (float)SCOREBOARD_MAX_PANELS;
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) {
panel_[i].pos.x = roundf(PANEL_WIDTH * i);
panel_[i].pos.y = 0;
@@ -365,7 +365,7 @@ void Scoreboard::recalculateAnchors() {
// Crea la textura de fondo
void Scoreboard::createBackgroundTexture() {
// Elimina la textura en caso de existir
if (background_) {
if (background_ != nullptr) {
SDL_DestroyTexture(background_);
}
@@ -377,7 +377,7 @@ void Scoreboard::createBackgroundTexture() {
// Crea las texturas de los paneles
void Scoreboard::createPanelTextures() {
// Elimina las texturas en caso de existir
for (auto texture : panel_texture_) {
for (auto *texture : panel_texture_) {
if (texture != nullptr) {
SDL_DestroyTexture(texture);
}

View File

@@ -88,8 +88,8 @@ class Scoreboard {
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
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
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
@@ -105,7 +105,7 @@ class 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
static 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

View File

@@ -51,7 +51,7 @@ class Screen {
void show() { SDL_ShowWindow(window_); } // Muestra la ventana
void hide() { SDL_HideWindow(window_); } // Oculta la ventana
void getSingletons(); // Obtiene los punteros a los singletones
[[nodiscard]] auto getVSync() const -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
[[nodiscard]] static auto getVSync() -> bool { return Options::video.v_sync; } // Obtiene el valor de V-Sync
[[nodiscard]] auto getText() const -> std::shared_ptr<Text> { return text_; } // Obtiene el puntero al texto de Screen
#ifdef DEBUG
@@ -93,8 +93,8 @@ class Screen {
explicit FlashEffect(bool enabled = false, int lenght = 0, int delay = 0, Color color = Color(0xFF, 0xFF, 0xFF))
: enabled(enabled), lenght(lenght), delay(delay), counter(lenght), color(color) {}
void update() { (enabled && counter > 0) ? counter-- : enabled = false; }
auto isRendarable() -> bool { return enabled && counter < lenght - delay; }
void update() { (enabled && counter > 0) ? counter-- : static_cast<int>(enabled = false); }
auto isRendarable() const -> bool { return enabled && counter < lenght - delay; }
};
// Efecto de sacudida/agitación de pantalla: mueve la imagen para simular un temblor
@@ -119,12 +119,15 @@ class Screen {
original_width = src_rect.w;
// Usar nuevos valores si se proporcionan, sino mantener los actuales
if (new_desp != -1)
if (new_desp != -1) {
desp = new_desp;
if (new_delay != -1)
}
if (new_delay != -1) {
delay = new_delay;
if (new_lenght != -1)
}
if (new_lenght != -1) {
lenght = new_lenght;
}
src_rect.w -= desp;
dst_rect.w = src_rect.w;

View File

@@ -34,7 +34,7 @@ HiScoreTable::HiScoreTable()
background_(std::make_unique<Background>()),
ticks_(0),
view_area_(SDL_FRect{0, 0, static_cast<float>(param.game.width), static_cast<float>(param.game.height)}),
view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}),
fade_mode_(FadeMode::IN),
background_fade_color_(Color(0, 0, 0)) {
// Inicializa el resto
@@ -83,7 +83,7 @@ void HiScoreTable::update() {
// Dibuja los sprites en la textura
void HiScoreTable::fillTexture() {
// Pinta en el backbuffer el texto y los sprites
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
SDL_RenderClear(renderer_);
@@ -112,7 +112,7 @@ void HiScoreTable::render() {
background_->render();
// Establece la ventana del backbuffer
view_area_.y = std::max(0.0f, param.game.height - counter_ + 100);
view_area_.y = std::max(0.0F, param.game.height - counter_ + 100);
// Copia el backbuffer al renderizador
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_);
@@ -218,7 +218,7 @@ void HiScoreTable::createSprites() {
const auto TABLE_POSITION = format(i + 1) + ". ";
const auto SCORE = format(Options::settings.hi_score_table.at(i).score);
const auto NUM_DOTS = ENTRY_LENGHT - Options::settings.hi_score_table.at(i).name.size() - SCORE.size();
const auto ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
const auto *const ONE_CC = Options::settings.hi_score_table.at(i).one_credit_complete ? " }" : "";
std::string dots;
for (int j = 0; j < (int)NUM_DOTS; ++j) {
dots = dots + ".";
@@ -301,16 +301,16 @@ void HiScoreTable::initFade() {
// Inicializa el fondo
void HiScoreTable::initBackground() {
background_->setPos(param.game.game_area.rect);
background_->setCloudsSpeed(-0.1f);
background_->setCloudsSpeed(-0.1F);
const int LUCKY = rand() % 3;
switch (LUCKY) {
case 0: // Fondo verde
{
background_->setGradientNumber(2);
background_->setTransition(0.0f);
background_->setSunProgression(1.0f);
background_->setMoonProgression(0.0f);
background_->setTransition(0.0F);
background_->setSunProgression(1.0F);
background_->setMoonProgression(0.0F);
background_fade_color_ = GREEN_SKY_COLOR;
break;
}
@@ -318,9 +318,9 @@ void HiScoreTable::initBackground() {
case 1: // Fondo naranja
{
background_->setGradientNumber(1);
background_->setTransition(0.0f);
background_->setSunProgression(0.65f);
background_->setMoonProgression(0.0f);
background_->setTransition(0.0F);
background_->setSunProgression(0.65F);
background_->setMoonProgression(0.0F);
background_fade_color_ = PINK_SKY_COLOR;
break;
}
@@ -328,9 +328,9 @@ void HiScoreTable::initBackground() {
case 2: // Fondo azul
{
background_->setGradientNumber(0);
background_->setTransition(0.0f);
background_->setSunProgression(0.0f);
background_->setMoonProgression(0.0f);
background_->setTransition(0.0F);
background_->setSunProgression(0.0F);
background_->setMoonProgression(0.0F);
background_fade_color_ = BLUE_SKY_COLOR;
break;
}

View File

@@ -62,9 +62,9 @@ class HiScoreTable {
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
static void checkEvents(); // Comprueba los eventos
static void checkInput(); // Comprueba las entradas
static auto format(int number) -> std::string; // Convierte un entero a un string con separadores de miles
void fillTexture(); // Dibuja los sprites en la textura
void updateFade(); // Gestiona el fade
void createSprites(); // Crea los sprites con los textos

View File

@@ -113,7 +113,7 @@ void Instructions::fillTexture() {
const int DESP_X = param.game.item_size + 8;
// Modifica el renderizador para pintar en la textura
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, texture_);
// Limpia la textura
@@ -128,9 +128,9 @@ void Instructions::fillTexture() {
constexpr int SPACE_POST_HEADER = 20;
constexpr int SPACE_PRE_HEADER = 28;
const int SPACE_BETWEEN_LINES = text_->getCharacterSize() * 1.5f;
const int SPACE_BETWEEN_LINES = text_->getCharacterSize() * 1.5F;
const int SPACE_BETWEEN_ITEM_LINES = param.game.item_size + item_space_;
const int SPACE_NEW_PARAGRAPH = SPACE_BETWEEN_LINES * 0.5f;
const int SPACE_NEW_PARAGRAPH = SPACE_BETWEEN_LINES * 0.5F;
const int SIZE = (NUM_LINES * SPACE_BETWEEN_LINES) + (NUM_ITEM_LINES * SPACE_BETWEEN_ITEM_LINES) + (NUM_POST_HEADERS * SPACE_POST_HEADER) + (NUM_PRE_HEADERS * SPACE_PRE_HEADER) + (SPACE_NEW_PARAGRAPH);
const int FIRST_LINE = (param.game.height - SIZE) / 2;
@@ -182,7 +182,7 @@ void Instructions::fillTexture() {
// Rellena el backbuffer
void Instructions::fillBackbuffer() {
// Modifica el renderizador para pintar en la textura
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, backbuffer_);
// Limpia la textura
@@ -242,10 +242,11 @@ void Instructions::render() {
tiled_bg_->render();
// Copia la textura y el backbuffer al renderizador
if (view_.y == 0)
if (view_.y == 0) {
renderLines(renderer_, backbuffer_, lines_);
else
} else {
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_);
}
fade_->render();
@@ -283,7 +284,7 @@ auto Instructions::initializeLines(int height) -> std::vector<Line> {
std::vector<Line> lines;
for (int y = 0; y < height; y++) {
int direction = (y % 2 == 0) ? -1 : 1; // Pares a la izquierda, impares a la derecha
lines.emplace_back(y, 0.0f, direction);
lines.emplace_back(y, 0.0F, direction);
}
return lines;
}
@@ -299,7 +300,7 @@ auto Instructions::moveLines(std::vector<Line> &lines, int width, float duration
line.start_time = current_time + line.y * start_delay;
}
float elapsed_time = (current_time - line.start_time) / 1000.0f; // Convertir a segundos
float elapsed_time = (current_time - line.start_time) / 1000.0F; // Convertir a segundos
if (elapsed_time < 0) {
all_lines_off_screen = false; // Si aún no se debe mover esta línea, no están todas fuera de pantalla
continue;
@@ -329,7 +330,7 @@ void Instructions::renderLines(SDL_Renderer *renderer, SDL_Texture *texture, con
// Gestiona la textura con los graficos
void Instructions::updateBackbuffer() {
// Establece la ventana del backbuffer
view_.y = std::max(0.0f, param.game.height - counter_ + 100);
view_.y = std::max(0.0F, param.game.height - counter_ + 100);
// Verifica si view_.y == 0 y gestiona el temporizador
if (view_.y == 0) {
@@ -339,7 +340,7 @@ void Instructions::updateBackbuffer() {
start_delay_time_ = SDL_GetTicks();
} else if (SDL_GetTicks() - start_delay_time_ >= 4000) {
// Han pasado tres segundos, mover líneas
all_lines_off_screen_ = moveLines(lines_, 320, 1.0f, 5);
all_lines_off_screen_ = moveLines(lines_, 320, 1.0F, 5);
}
}

View File

@@ -74,14 +74,14 @@ class Instructions {
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
static void checkEvents(); // Comprueba los eventos
static void checkInput(); // Comprueba las entradas
void fillTexture(); // Rellena la textura de texto
void fillBackbuffer(); // Rellena el backbuffer
void iniSprites(); // Inicializa los sprites de los items
void updateSprites(); // Actualiza los sprites
auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
static auto initializeLines(int height) -> std::vector<Line>; // Inicializa las líneas animadas
static auto moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas
static void renderLines(SDL_Renderer *renderer, SDL_Texture *texture, const std::vector<Line> &lines); // Renderiza las líneas
void updateBackbuffer(); // Gestiona la textura con los gráficos
};

View File

@@ -42,7 +42,7 @@ Intro::Intro()
initTexts();
// Configura el fondo
tiled_bg_->setSpeed(0.3f);
tiled_bg_->setSpeed(0.3F);
tiled_bg_->setColor(bg_color_);
}
@@ -51,55 +51,67 @@ void Intro::checkEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
#ifdef DEBUG
if (event.type == SDL_EVENT_KEY_DOWN && event.key.repeat == 1) {
if (event.type == SDL_EVENT_KEY_DOWN && static_cast<int>(event.key.repeat) == 1) {
static Color color_ = param.intro.bg_color;
switch (event.key.key) {
case SDLK_A:
if (color_.r < 255)
if (color_.r < 255) {
++color_.r;
}
break;
case SDLK_Z:
if (color_.r > 0)
if (color_.r > 0) {
--color_.r;
}
break;
case SDLK_S:
if (color_.g < 255)
if (color_.g < 255) {
++color_.g;
}
break;
case SDLK_X:
if (color_.g > 0)
if (color_.g > 0) {
--color_.g;
}
break;
case SDLK_D:
if (color_.b < 255)
if (color_.b < 255) {
++color_.b;
}
break;
case SDLK_C:
if (color_.b > 0)
if (color_.b > 0) {
--color_.b;
}
break;
case SDLK_F:
if (color_.r < 255)
if (color_.r < 255) {
++color_.r;
if (color_.g < 255)
}
if (color_.g < 255) {
++color_.g;
if (color_.b < 255)
}
if (color_.b < 255) {
++color_.b;
}
break;
case SDLK_V:
if (color_.r > 0)
if (color_.r > 0) {
--color_.r;
if (color_.g > 0)
}
if (color_.g > 0) {
--color_.g;
if (color_.b > 0)
}
if (color_.b > 0) {
--color_.b;
}
break;
default:
@@ -335,7 +347,7 @@ void Intro::initSprites() {
// Constantes
constexpr int TOTAL_SPRITES = TEXTURE_LIST.size();
const float BORDER = 2.0f;
const float BORDER = 2.0F;
auto texture = Resource::get()->getTexture(TEXTURE_LIST.front());
const float CARD_WIDTH = texture->getWidth() + (BORDER * 2);
@@ -351,7 +363,7 @@ void Intro::initSprites() {
card_texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Apuntamos el renderizador a la textura
auto temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
card_texture->setAsRenderTarget(Screen::get()->getRenderer());
// Limpia la textura
@@ -406,7 +418,7 @@ void Intro::initSprites() {
shadow_texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Apuntamos el renderizador a la textura
auto temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
shadow_texture->setAsRenderTarget(Screen::get()->getRenderer());
// Limpia la textura
@@ -572,7 +584,7 @@ void Intro::updatePostState() {
void Intro::renderTextRect() {
static const float HEIGHT = Resource::get()->getText("04b_25_metal")->getCharacterSize();
static SDL_FRect rect_ = {0.0f, param.game.height - param.intro.text_distance_from_bottom - HEIGHT, param.game.width, HEIGHT * 3};
static SDL_FRect rect_ = {0.0F, param.game.height - param.intro.text_distance_from_bottom - HEIGHT, param.game.width, HEIGHT * 3};
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), param.intro.shadow_color.r, param.intro.shadow_color.g, param.intro.shadow_color.b, param.intro.shadow_color.a);
SDL_RenderFillRect(Screen::get()->getRenderer(), &rect_);
}

View File

@@ -59,7 +59,7 @@ class Intro {
void update(); // Actualiza las variables del objeto
void render(); // Dibuja el objeto en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
static void checkInput(); // Comprueba las entradas
void updateScenes(); // Actualiza las escenas de la intro
void initSprites(); // Inicializa las imágenes
void initTexts(); // Inicializa los textos
@@ -67,6 +67,6 @@ class Intro {
void updateTexts(); // Actualiza los textos
void renderSprites(); // Dibuja los sprites
void renderTexts(); // Dibuja los textos
void renderTextRect(); // Dibuja el rectangulo de fondo del texto;
static void renderTextRect(); // Dibuja el rectangulo de fondo del texto;
void updatePostState(); // Actualiza el estado POST
};

View File

@@ -52,8 +52,8 @@ class Logo {
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Dibuja en pantalla
void checkEvents(); // Comprueba el manejador de eventos
void checkInput(); // Comprueba las entradas
static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas
void updateJAILGAMES(); // Gestiona el logo de JAILGAMES
void renderJAILGAMES(); // Renderiza el logo de JAILGAMES
void updateTextureColors(); // Gestiona el color de las texturas

View File

@@ -28,8 +28,8 @@ void SmartSprite::checkMove() {
setPosX(dest_x_);
// Lo detiene
setVelX(0.0f);
setAccelX(0.0f);
setVelX(0.0F);
setAccelX(0.0F);
}
}
// Comprueba si se desplaza en el eje X hacia la izquierda
@@ -40,8 +40,8 @@ void SmartSprite::checkMove() {
setPosX(dest_x_);
// Lo detiene
setVelX(0.0f);
setAccelX(0.0f);
setVelX(0.0F);
setAccelX(0.0F);
}
}
@@ -53,8 +53,8 @@ void SmartSprite::checkMove() {
setPosY(dest_y_);
// Lo detiene
setVelY(0.0f);
setAccelY(0.0f);
setVelY(0.0F);
setAccelY(0.0F);
}
}
// Comprueba si se desplaza en el eje Y hacia arriba
@@ -65,8 +65,8 @@ void SmartSprite::checkMove() {
setPosY(dest_y_);
// Lo detiene
setVelY(0.0f);
setAccelY(0.0f);
setVelY(0.0F);
setAccelY(0.0F);
}
}
}

View File

@@ -45,8 +45,9 @@ auto loadTextFile(const std::string &file_path) -> std::shared_ptr<TextFile> {
auto line_read = 0;
while (std::getline(file, buffer)) {
// Almacena solo las lineas impares
if (line_read % 2 == 1)
if (line_read % 2 == 1) {
tf->offset[index++].w = std::stoi(buffer);
}
// Limpia el buffer
buffer.clear();
@@ -116,8 +117,9 @@ Text::Text(std::shared_ptr<Texture> texture, std::shared_ptr<TextFile> text_file
void Text::write(int x, int y, const std::string &text, int kerning, int lenght) {
int shift = 0;
if (lenght == -1)
if (lenght == -1) {
lenght = text.length();
}
sprite_->setY(y);
for (int i = 0; i < lenght; ++i) {
@@ -135,18 +137,18 @@ void Text::write2X(int x, int y, const std::string &text, int kerning) {
for (size_t i = 0; i < text.length(); ++i) {
auto index = static_cast<size_t>(text[i]);
SDL_FRect rect = {static_cast<float>(offset_[index].x), static_cast<float>(offset_[index].y), static_cast<float>(box_width_), static_cast<float>(box_height_)};
sprite_->getTexture()->render(x + shift, y, &rect, 2.0f, 2.0f);
sprite_->getTexture()->render(x + shift, y, &rect, 2.0F, 2.0F);
shift += (offset_[index].w + kerning) * 2;
}
}
// Escribe el texto en una textura
auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto *renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = lenght(text, kerning) * zoom;
auto height = box_height_ * zoom;
auto temp = SDL_GetRenderTarget(renderer);
auto *temp = SDL_GetRenderTarget(renderer);
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
texture->setBlendMode(SDL_BLENDMODE_BLEND);
texture->setAsRenderTarget(renderer);
@@ -160,11 +162,11 @@ auto Text::writeToTexture(const std::string &text, int zoom, int kerning) -> std
// Escribe el texto con extras en una textura
auto Text::writeDXToTexture(Uint8 flags, const std::string &text, int kerning, Color text_color, Uint8 shadow_distance, Color shadow_color, int lenght) -> std::shared_ptr<Texture> {
auto renderer = Screen::get()->getRenderer();
auto *renderer = Screen::get()->getRenderer();
auto texture = std::make_shared<Texture>(renderer);
auto width = Text::lenght(text, kerning) + shadow_distance;
auto height = box_height_ + shadow_distance;
auto temp = SDL_GetRenderTarget(renderer);
auto *temp = SDL_GetRenderTarget(renderer);
texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
texture->setBlendMode(SDL_BLENDMODE_BLEND);
texture->setAsRenderTarget(renderer);
@@ -232,8 +234,9 @@ void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerni
// Obtiene la longitud en pixels de una cadena
auto Text::lenght(const std::string &text, int kerning) const -> int {
int shift = 0;
for (size_t i = 0; i < text.length(); ++i)
for (size_t i = 0; i < text.length(); ++i) {
shift += (offset_[static_cast<int>(text[i])].w + kerning);
}
// Descuenta el kerning del último caracter
return shift - kerning;
@@ -251,7 +254,7 @@ void Text::setFixedWidth(bool value) {
// Establece una paleta
void Text::setPalette(int number) {
auto temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
auto *temp = SDL_GetRenderTarget(Screen::get()->getRenderer());
SDL_SetRenderTarget(Screen::get()->getRenderer(), nullptr);
sprite_->getTexture()->setPalette(number);
SDL_SetRenderTarget(Screen::get()->getRenderer(), temp);

View File

@@ -55,18 +55,20 @@ Texture::~Texture() {
// Carga una imagen desde un fichero
auto Texture::loadFromFile(const std::string &file_path) -> bool {
if (file_path.empty())
if (file_path.empty()) {
return false;
}
int req_format = STBI_rgb_alpha;
int width, height, orig_format;
int width;
int height;
int orig_format;
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
if (!data) {
if (data == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", getFileName(file_path).c_str());
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} else {
printWithDots("Texture : ", getFileName(file_path), "[ LOADED ]");
}
printWithDots("Texture : ", getFileName(file_path), "[ LOADED ]");
int pitch;
SDL_PixelFormat pixel_format;
@@ -82,7 +84,7 @@ auto Texture::loadFromFile(const std::string &file_path) -> bool {
SDL_Texture *new_texture = nullptr;
// Carga la imagen desde una ruta específica
auto loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void *>(data), pitch);
auto *loaded_surface = SDL_CreateSurfaceFrom(width, height, pixel_format, static_cast<void *>(data), pitch);
if (loaded_surface == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load image %s", file_path.c_str());
} else {
@@ -110,7 +112,7 @@ auto Texture::loadFromFile(const std::string &file_path) -> bool {
auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_TextureAccess access) -> bool {
// Crea una textura sin inicializar
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) {
if (texture_ == nullptr) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create blank texture! SDL Error: %s", SDL_GetError());
} else {
width_ = width;
@@ -123,7 +125,7 @@ auto Texture::createBlank(int width, int height, SDL_PixelFormat format, SDL_Tex
// Libera la memoria de la textura
void Texture::unloadTexture() {
// Libera la textura
if (texture_) {
if (texture_ != nullptr) {
SDL_DestroyTexture(texture_);
texture_ = nullptr;
width_ = 0;
@@ -161,7 +163,7 @@ void Texture::render(int x, int y, SDL_FRect *clip, float zoom_w, float zoom_h,
}
// Calcula el zoom y las coordenadas
if (zoom_h != 1.0f || zoom_w != 1.0f) {
if (zoom_h != 1.0F || zoom_w != 1.0F) {
render_quad.x = render_quad.x + (render_quad.w / 2);
render_quad.y = render_quad.y + (render_quad.h / 2);
render_quad.w = render_quad.w * zoom_w;
@@ -180,12 +182,12 @@ void Texture::setAsRenderTarget(SDL_Renderer *renderer) {
}
// Obtiene el ancho de la imagen
auto Texture::getWidth() -> int {
auto Texture::getWidth() const -> int {
return width_;
}
// Obtiene el alto de la imagen
auto Texture::getHeight() -> int {
auto Texture::getHeight() const -> int {
return height_;
}
@@ -231,7 +233,8 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surfa
// Crear un objeto Gif y llamar a la función loadGif
GIF::Gif gif;
Uint16 w = 0, h = 0;
Uint16 w = 0;
Uint16 h = 0;
std::vector<Uint8> raw_pixels = gif.loadGif(buffer.data(), w, h);
if (raw_pixels.empty()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: No se pudo cargar el GIF %s", file_path.c_str());
@@ -256,7 +259,7 @@ auto Texture::loadSurface(const std::string &file_path) -> std::shared_ptr<Surfa
// Vuelca la surface en la textura
void Texture::flipSurface() {
// Limpia la textura
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, texture_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
SDL_RenderClear(renderer_);
@@ -286,9 +289,8 @@ auto Texture::loadPaletteFromFile(const std::string &file_path) -> Palette {
if (!file) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: Fichero no encontrado %s", file_path.c_str());
throw std::runtime_error("Fichero no encontrado: " + file_path);
} else {
printWithDots("Palette : ", getFileName(file_path), "[ LOADED ]");
}
printWithDots("Palette : ", getFileName(file_path), "[ LOADED ]");
// Obtener el tamaño del archivo y leerlo en un buffer
std::streamsize size = file.tellg();
@@ -364,7 +366,9 @@ auto Texture::readPalFile(const std::string &file_path) -> Palette {
// Procesar las líneas restantes con valores RGB
std::istringstream ss(line);
int r, g, b;
int r;
int g;
int b;
if (ss >> r >> g >> b) {
// Construir el color RGBA (A = 255 por defecto)
Uint32 color = (r << 24) | (g << 16) | (b << 8) | 255;

View File

@@ -53,8 +53,8 @@ class Texture {
void setPalette(size_t palette); // Cambia la paleta de la textura
// --- Getters ---
auto getWidth() -> int; // Obtiene el ancho de la imagen
auto getHeight() -> int; // Obtiene el alto de la imagen
[[nodiscard]] auto getWidth() const -> int; // Obtiene el ancho de la imagen
[[nodiscard]] auto getHeight() const -> int; // Obtiene el alto de la imagen
auto getSDLTexture() -> SDL_Texture *; // Obtiene la textura SDL
auto getRenderer() -> SDL_Renderer *; // Obtiene el renderizador
@@ -74,8 +74,8 @@ class Texture {
// --- Métodos internos ---
auto loadSurface(const std::string &file_name) -> std::shared_ptr<Surface>; // Crea una surface desde un fichero .gif
void flipSurface(); // Vuelca la surface en la textura
auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
static auto loadPaletteFromFile(const std::string &file_name) -> Palette; // Carga una paleta desde un fichero
void unloadTexture(); // Libera la memoria de la textura
void unloadSurface(); // Libera la surface actual
auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
static auto readPalFile(const std::string &file_path) -> Palette; // Carga una paleta desde un archivo .pal
};

View File

@@ -27,7 +27,7 @@ TiledBG::TiledBG(SDL_FRect pos, TiledBGMode mode)
switch (mode_) {
case TiledBGMode::STATIC:
window_ = {0, 0, pos_.w, pos_.h};
speed_ = 0.0f;
speed_ = 0.0F;
break;
case TiledBGMode::DIAGONAL:
window_ = {0, 0, pos_.w, pos_.h};
@@ -57,7 +57,7 @@ void TiledBG::fillTexture() {
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH, TILE_HEIGHT});
// Prepara para dibujar sobre la textura
auto temp = SDL_GetRenderTarget(renderer_);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, canvas_);
// Rellena la textura con el tile
@@ -114,17 +114,17 @@ void TiledBG::updateStop() {
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
if (window_.x >= TILE_WIDTH - UMBRAL) {
speed_ /= 1.05f; // Reduce gradualmente la velocidad
speed_ /= 1.05F; // Reduce gradualmente la velocidad
// Asegura que no baje demasiado
if (speed_ < 0.1f) {
speed_ = 0.1f;
if (speed_ < 0.1F) {
speed_ = 0.1F;
}
}
// Si estamos en 0, detener
if (window_.x == 0) {
speed_ = 0.0f;
speed_ = 0.0F;
stopping_ = false; // Desactivamos el estado de "stopping"
}
}

View File

@@ -36,7 +36,7 @@ class TiledBG {
void setColor(Color color) { SDL_SetTextureColorMod(canvas_, color.r, color.g, color.b); } // Cambia el color de la textura
// --- Getters ---
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0f; } // Indica si está parado
[[nodiscard]] auto isStopped() const -> bool { return speed_ == 0.0F; } // Indica si está parado
private:
// --- Constantes ---
@@ -52,8 +52,8 @@ private:
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
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
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
// --- Métodos internos ---

View File

@@ -123,8 +123,9 @@ class ListOption : public MenuOption {
return value_list_.empty() ? "" : value_list_[list_index_];
}
void adjustValue(bool adjust_up) override {
if (value_list_.empty())
if (value_list_.empty()) {
return;
}
size_t size = value_list_.size();
list_index_ = (adjust_up) ? (list_index_ + 1) % size
: (list_index_ + size - 1) % size;
@@ -164,8 +165,9 @@ class ActionOption : public MenuOption {
[[nodiscard]] auto getBehavior() const -> Behavior override { return Behavior::SELECT; }
void executeAction() override {
if (action_)
if (action_) {
action_();
}
}
private:

View File

@@ -103,10 +103,10 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
auto MenuRenderer::calculateNewRect(const ServiceMenu *menu_state) -> SDL_FRect {
width_ = getMenuWidthForGroup(menu_state->getCurrentGroup());
const auto &display_options = menu_state->getDisplayOptions();
lower_height_ = ((display_options.size() > 0 ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
lower_height_ = ((!display_options.empty() ? display_options.size() - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
height_ = upper_height_ + lower_height_;
return {(param.game.width - width_) / 2.0f, (param.game.height - height_) / 2.0f, (float)width_, (float)height_};
return {(param.game.width - width_) / 2.0F, (param.game.height - height_) / 2.0F, (float)width_, (float)height_};
}
void MenuRenderer::resize(const ServiceMenu *menu_state) {
@@ -131,11 +131,12 @@ void MenuRenderer::setSize(const ServiceMenu *menu_state) {
}
void MenuRenderer::updateResizeAnimation() {
if (!resizing_)
if (!resizing_) {
return;
}
++resize_anim_step_;
float t = static_cast<float>(resize_anim_step_) / resize_anim_steps_;
if (t >= 1.0f) {
if (t >= 1.0F) {
rect_ = setRect(rect_anim_to_);
resizing_ = false;
return;
@@ -150,15 +151,17 @@ void MenuRenderer::updateResizeAnimation() {
}
void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<MenuOption>> &all_options, const ServiceMenu *menu_state) {
for (int &w : group_menu_widths_)
for (int &w : group_menu_widths_) {
w = ServiceMenu::MIN_WIDTH;
}
for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0;
int max_value_width = 0;
for (const auto &option : all_options) {
if (option->getGroup() != sg)
if (option->getGroup() != sg) {
continue;
}
max_option_width = std::max(max_option_width, element_text_->lenght(option->getCaption(), -2));
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
max_value_width = std::max(max_value_width, option->getMaxValueWidth(element_text_.get()));
@@ -185,7 +188,7 @@ void MenuRenderer::updateColorCounter() {
}
}
auto MenuRenderer::getAnimatedSelectedColor() -> Color {
auto MenuRenderer::getAnimatedSelectedColor() const -> Color {
static auto color_cycle_ = generateMirroredCycle(param.service_menu.selected_color, ColorCycleStyle::HUE_WAVE);
return color_cycle_.at(color_counter_ % color_cycle_.size());
}

View File

@@ -67,7 +67,7 @@ class MenuRenderer {
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;
auto getAnimatedSelectedColor() const -> Color;
void updateColorCounter();
auto setRect(SDL_FRect rect) -> SDL_FRect;
};

View File

@@ -40,20 +40,22 @@ void ServiceMenu::toggle() {
}
void ServiceMenu::render() {
if (!enabled_)
if (!enabled_) {
return;
}
renderer_->render(this);
// El mensaje de reinicio se dibuja por encima, así que lo gestionamos aquí
const float MSG_X = param.game.game_area.center_x;
const float MSG_Y = renderer_->getRect().y + 39.0f;
const float MSG_Y = renderer_->getRect().y + 39.0F;
restart_message_ui_->setPosition(MSG_X, MSG_Y);
restart_message_ui_->render();
}
void ServiceMenu::update() {
if (!enabled_)
if (!enabled_) {
return;
}
renderer_->update(this);
@@ -77,22 +79,25 @@ void ServiceMenu::reset() {
// --- Lógica de Navegación ---
void ServiceMenu::setSelectorUp() {
if (display_options_.empty())
if (display_options_.empty()) {
return;
}
selected_ = (selected_ > 0) ? selected_ - 1 : display_options_.size() - 1;
playMoveSound();
}
void ServiceMenu::setSelectorDown() {
if (display_options_.empty())
if (display_options_.empty()) {
return;
}
selected_ = (selected_ + 1) % display_options_.size();
playMoveSound();
}
void ServiceMenu::adjustOption(bool adjust_up) {
if (display_options_.empty())
if (display_options_.empty()) {
return;
}
auto &selected_option = display_options_.at(selected_);
if (selected_option->getBehavior() == MenuOption::Behavior::ADJUST) {
selected_option->adjustValue(adjust_up);
@@ -102,18 +107,20 @@ void ServiceMenu::adjustOption(bool adjust_up) {
}
void ServiceMenu::selectOption() {
if (display_options_.empty())
if (display_options_.empty()) {
return;
if (current_settings_group_ == SettingsGroup::MAIN)
}
if (current_settings_group_ == SettingsGroup::MAIN) {
main_menu_selected_ = selected_;
}
auto *selected_option = display_options_.at(selected_);
if (!selected_option) {
if (selected_option == nullptr) {
// This shouldn't happen in normal operation, but protects against null pointer
return;
}
if (auto folder = dynamic_cast<FolderOption *>(selected_option)) {
if (auto *folder = dynamic_cast<FolderOption *>(selected_option)) {
previous_settings_group_ = current_settings_group_;
current_settings_group_ = folder->getTargetGroup();
selected_ = 0;
@@ -166,12 +173,15 @@ void ServiceMenu::updateMenu() {
}
void ServiceMenu::applySettings() {
if (current_settings_group_ == SettingsGroup::VIDEO)
if (current_settings_group_ == SettingsGroup::VIDEO) {
applyVideoSettings();
if (current_settings_group_ == SettingsGroup::AUDIO)
}
if (current_settings_group_ == SettingsGroup::AUDIO) {
applyAudioSettings();
if (current_settings_group_ == SettingsGroup::SETTINGS)
}
if (current_settings_group_ == SettingsGroup::SETTINGS) {
applySettingsSettings();
}
// Actualiza los valores de las opciones
updateOptionPairs();
@@ -262,7 +272,7 @@ void ServiceMenu::initializeOptions() {
// Sincroniza los valores de las opciones tipo lista
void ServiceMenu::adjustListValues() {
for (auto &option : options_) {
if (auto list_option = dynamic_cast<ListOption *>(option.get())) {
if (auto *list_option = dynamic_cast<ListOption *>(option.get())) {
list_option->sync();
}
}
@@ -275,7 +285,7 @@ void ServiceMenu::playSelectSound() { Audio::get()->playSound("service_menu_sele
void ServiceMenu::playBackSound() { Audio::get()->playSound("service_menu_select.wav", Audio::Group::INTERFACE); }
// Devuelve el nombre del grupo como string para el título
auto ServiceMenu::settingsGroupToString(SettingsGroup group) const -> std::string {
auto ServiceMenu::settingsGroupToString(SettingsGroup group) -> std::string {
switch (group) {
case SettingsGroup::MAIN:
return Lang::getText("[SERVICE_MENU] TITLE");
@@ -295,15 +305,17 @@ auto ServiceMenu::settingsGroupToString(SettingsGroup group) const -> std::strin
// Establece el estado de oculto de ciertas opciones
void ServiceMenu::setHiddenOptions() {
{
auto option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"));
if (option)
auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] WINDOW_SIZE"));
if (option != nullptr) {
option->setHidden(Options::video.fullscreen);
}
}
{
auto option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN"));
if (option)
auto *option = getOptionByCaption(Lang::getText("[SERVICE_MENU] SHUTDOWN"));
if (option != nullptr) {
option->setHidden(!Options::settings.shutdown_enabled);
}
}
updateMenu(); // El menú debe refrescarse si algo se oculta

View File

@@ -89,15 +89,15 @@ private:
void updateMenu();
void applySettings();
void applyVideoSettings();
void applyAudioSettings();
static void applyAudioSettings();
void applySettingsSettings();
[[nodiscard]] auto getOptionByCaption(const std::string &caption) const -> MenuOption *;
void adjustListValues();
void playMoveSound();
void playAdjustSound();
void playSelectSound();
void playBackSound();
[[nodiscard]] auto settingsGroupToString(SettingsGroup group) const -> std::string;
static void playMoveSound();
static void playAdjustSound();
static void playSelectSound();
static void playBackSound();
[[nodiscard]] static auto settingsGroupToString(SettingsGroup group) -> std::string;
void setHiddenOptions();
// --- Constructores y destructor privados (singleton) ---

View File

@@ -11,11 +11,12 @@ UIMessage::UIMessage(std::shared_ptr<Text> text_renderer, std::string message_te
// Muestra el mensaje en la posición base_x, base_y con animación de entrada desde arriba
void UIMessage::show() {
if (visible_ && target_y_ == 0.0f)
if (visible_ && target_y_ == 0.0F) {
return; // Ya está visible y quieto
}
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
target_y_ = 0.0f; // La posición final es la base
target_y_ = 0.0F; // La posición final es la base
y_offset_ = start_y_;
anim_step_ = 0;
animating_ = true;
@@ -24,8 +25,9 @@ void UIMessage::show() {
// Oculta el mensaje con animación de salida hacia arriba
void UIMessage::hide() {
if (!visible_)
if (!visible_) {
return;
}
start_y_ = y_offset_; // Comienza desde la posición actual
target_y_ = DESP; // Termina 8 píxeles arriba de la base
@@ -58,8 +60,9 @@ void UIMessage::updateAnimation() {
if (anim_step_ >= ANIMATION_STEPS) {
y_offset_ = target_y_;
animating_ = false;
if (target_y_ < 0.0f)
if (target_y_ < 0.0F) {
visible_ = false;
}
}
}

View File

@@ -40,16 +40,16 @@ class UIMessage {
// --- Estado ---
bool visible_ = false; // Indica si el mensaje está visible
bool animating_ = false; // Indica si el mensaje está en proceso de animación
float base_x_ = 0.0f; // Posición X base donde se muestra el mensaje
float base_y_ = 0.0f; // Posición Y base donde se muestra el mensaje
float y_offset_ = 0.0f; // Desplazamiento vertical actual del mensaje (para animación)
float base_x_ = 0.0F; // Posición X base donde se muestra el mensaje
float base_y_ = 0.0F; // Posición Y base donde se muestra el mensaje
float y_offset_ = 0.0F; // Desplazamiento vertical actual del mensaje (para animación)
// --- Animación ---
float start_y_ = 0.0f; // Posición Y inicial de la animación
float target_y_ = 0.0f; // Posición Y objetivo de la animación
float start_y_ = 0.0F; // Posición Y inicial de la animación
float target_y_ = 0.0F; // Posición Y objetivo de la animación
int anim_step_ = 0; // Paso actual de la animación
static constexpr int ANIMATION_STEPS = 8; // Número total de pasos de la animación
static constexpr float DESP = -8.0f; // Distancia a desplazarse
static constexpr float DESP = -8.0F; // Distancia a desplazarse
// Actualiza la interpolación de la animación (ease out/in cubic)
void updateAnimation();

View File

@@ -46,7 +46,7 @@ class Writer {
int pos_x_ = 0; // Posición en el eje X donde empezar a escribir el texto
int pos_y_ = 0; // Posición en el eje Y donde empezar a escribir el texto
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
std::string caption_ = std::string(); // El texto para escribir
std::string caption_; // El texto para escribir
int speed_ = 0; // Velocidad de escritura
int writing_counter_ = 0; // Temporizador de escritura para cada caracter
int index_ = 0; // Posición del texto que se está escribiendo