clang-tidy

This commit is contained in:
2025-07-20 12:16:25 +02:00
parent a7ef29b750
commit bfda842d3c
43 changed files with 512 additions and 504 deletions

View File

@@ -9,16 +9,16 @@
#include "utils.h" // Para getFileName
// Singleton
Asset *Asset::instance_ = nullptr;
Asset *Asset::instance = nullptr;
// Inicializa la instancia única del singleton
void Asset::init(const std::string &executable_path) { Asset::instance_ = new Asset(executable_path); }
void Asset::init(const std::string &executable_path) { Asset::instance = new Asset(executable_path); }
// Libera la instancia
void Asset::destroy() { delete Asset::instance_; }
void Asset::destroy() { delete Asset::instance; }
// Obtiene la instancia
auto Asset::get() -> Asset * { return Asset::instance_; }
auto Asset::get() -> Asset * { return Asset::instance; }
// Añade un elemento a la lista
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute) {

View File

@@ -41,8 +41,8 @@ class Asset { // Gestor de recursos (singleton)
AssetType type; // Tipo de recurso
bool required; // Indica si el fichero es obligatorio
AssetItem(std::string filePath, AssetType assetType, bool isRequired)
: file(std::move(filePath)), type(assetType), required(isRequired) {} // Constructor
AssetItem(std::string file_path, AssetType asset_type, bool is_required)
: file(std::move(file_path)), type(asset_type), required(is_required) {} // Constructor
};
// --- Variables internas ---
@@ -60,5 +60,5 @@ class Asset { // Gestor de recursos (singleton)
~Asset() = default; // Destructor
// --- Singleton ---
static Asset *instance_; // Instancia singleton
static Asset *instance; // Instancia singleton
};

View File

@@ -9,16 +9,16 @@
#include "resource.h" // Para Resource
// Singleton
Audio *Audio::instance_ = nullptr;
Audio *Audio::instance = nullptr;
// Inicializa la instancia única del singleton
void Audio::init() { Audio::instance_ = new Audio(); }
void Audio::init() { Audio::instance = new Audio(); }
// Libera la instancia
void Audio::destroy() { delete Audio::instance_; }
void Audio::destroy() { delete Audio::instance; }
// Obtiene la instancia
auto Audio::get() -> Audio * { return Audio::instance_; }
auto Audio::get() -> Audio * { return Audio::instance; }
// Constructor
Audio::Audio() { initSDLAudio(); }

View File

@@ -90,5 +90,5 @@ class Audio {
~Audio(); // Destructor privado
// --- Singleton ---
static Audio *instance_;
static Audio *instance;
};

View File

@@ -321,7 +321,11 @@ void Background::createSunPath() {
constexpr float RADIUS = 120;
// Generar puntos de la curva desde 90 a 180 grados
for (double theta = M_PI / 2; theta <= M_PI; theta += 0.01) {
constexpr double STEP = 0.01;
const int NUM_STEPS = static_cast<int>((M_PI - M_PI / 2) / STEP) + 1;
for (int i = 0; i < NUM_STEPS; ++i) {
double theta = M_PI / 2 + i * STEP;
float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
sun_path_.push_back({x, y});
@@ -342,7 +346,11 @@ void Background::createMoonPath() {
constexpr float RADIUS = 140;
// Generar puntos de la curva desde 0 a 90 grados
for (double theta = 0; theta <= M_PI / 2; theta += 0.01) {
constexpr double STEP = 0.01;
const int NUM_STEPS = static_cast<int>((M_PI / 2 - 0) / STEP) + 1;
for (int i = 0; i < NUM_STEPS; ++i) {
double theta = 0 + i * STEP;
float x = CENTER_X + (RADIUS * cos(theta));
float y = CENTER_Y - (RADIUS * sin(theta));
moon_path_.push_back({x, y});

View File

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

View File

@@ -109,10 +109,10 @@ class Balloon {
bool enabled = false; // Si el efecto está activo
Uint8 counter = 0; // Contador para el efecto
Uint8 speed = 2; // Velocidad del efecto
float zoomW = 1.0f; // Zoom en anchura
float zoomH = 1.0f; // Zoom en altura
float despX = 0.0f; // Desplazamiento X antes de pintar
float despY = 0.0f; // Desplazamiento Y antes de pintar
float zoom_w = 1.0f; // Zoom en anchura
float zoom_h = 1.0f; // Zoom en altura
float desp_x = 0.0f; // Desplazamiento X antes de pintar
float desp_y = 0.0f; // Desplazamiento Y antes de pintar
float w[MAX_BOUNCE] = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Zoom ancho
float h[MAX_BOUNCE] = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Zoom alto
@@ -120,10 +120,10 @@ class Balloon {
Bouncing() = default;
void reset() {
counter = 0;
zoomW = 1.0f;
zoomH = 1.0f;
despX = 0.0f;
despY = 0.0f;
zoom_w = 1.0f;
zoom_h = 1.0f;
desp_x = 0.0f;
desp_y = 0.0f;
}
} bouncing_;

View File

@@ -13,8 +13,8 @@ Bullet::Bullet(float x, float y, BulletType bullet_type, bool powered, int owner
pos_y_(y),
bullet_type_(bullet_type),
owner_(owner) {
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT_
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT_
vel_x_ = (bullet_type_ == BulletType::LEFT) ? VEL_X_LEFT
: (bullet_type_ == BulletType::RIGHT) ? VEL_X_RIGHT
: 0;
std::string powered_type = powered ? "powered_" : "normal_";
@@ -59,7 +59,7 @@ BulletMoveStatus Bullet::move() {
return BulletMoveStatus::OUT;
}
pos_y_ += VEL_Y_;
pos_y_ += VEL_Y;
if (pos_y_ < param.game.play_area.rect.y - HEIGHT) {
disable();
return BulletMoveStatus::OUT;

View File

@@ -46,23 +46,23 @@ class Bullet {
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;
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
// Propiedades
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los gráficos
float pos_x_; // Posición en el eje X
float pos_y_; // Posición en el eje Y
float vel_x_; // Velocidad en el eje X
float pos_x_; // Posición en el eje X
float pos_y_; // Posición en el eje Y
float vel_x_; // Velocidad en el eje X
BulletType bullet_type_; // Tipo de bala
int owner_; // Identificador del dueño
Circle collider_; // Círculo de colisión
BulletType bullet_type_; // Tipo de bala
int owner_; // Identificador del dueño
Circle collider_; // Círculo de colisión
// Métodos internos
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
// Métodos internos
void shiftColliders(); // Ajusta el círculo de colisión
void shiftSprite(); // Ajusta el sprite
BulletMoveStatus move(); // Mueve la bala y devuelve su estado
};

1
source/external/.clang-tidy vendored Normal file
View File

@@ -0,0 +1 @@
Checks: '-*'

View File

@@ -9,16 +9,16 @@
#include <utility> // Para pair
// Singleton
Input *Input::instance_ = nullptr;
Input *Input::instance = nullptr;
// Inicializa la instancia única del singleton
void Input::init(const std::string &game_controller_db_path) { Input::instance_ = new Input(game_controller_db_path); }
void Input::init(const std::string &game_controller_db_path) { Input::instance = new Input(game_controller_db_path); }
// Libera la instancia
void Input::destroy() { delete Input::instance_; }
void Input::destroy() { delete Input::instance; }
// Obtiene la instancia
Input *Input::get() { return Input::instance_; }
Input *Input::get() { return Input::instance; }
// Constructor
Input::Input(const std::string &game_controller_db_path)

View File

@@ -146,5 +146,5 @@ class Input {
~Input() = default; // Destructor privado
// --- Singleton ---
static Input *instance_;
static Input *instance;
};

View File

@@ -14,16 +14,16 @@
#include "texture.h" // Para Texture
// Singleton
Notifier *Notifier::instance_ = nullptr;
Notifier *Notifier::instance = nullptr;
// Inicializa la instancia única del singleton
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance_ = new Notifier(icon_file, text); }
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text) { Notifier::instance = new Notifier(icon_file, text); }
// Libera la instancia
void Notifier::destroy() { delete Notifier::instance_; }
void Notifier::destroy() { delete Notifier::instance; }
// Obtiene la instancia
Notifier *Notifier::get() { return Notifier::instance_; }
Notifier *Notifier::get() { return Notifier::instance; }
// Constructor
Notifier::Notifier(std::string icon_file, std::shared_ptr<Text> text)

View File

@@ -32,37 +32,37 @@ class Notifier {
private:
// --- Singleton ---
static Notifier *instance_;
static Notifier *instance;
// --- Tipos internos ---
enum class NotificationStatus {
RISING,
STAY,
VANISHING,
FINISHED,
};
// --- Tipos internos ---
enum class NotificationStatus {
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationShape {
ROUNDED,
SQUARED,
};
enum class NotificationShape {
ROUNDED,
SQUARED,
};
// --- Estructura Notification ---
struct Notification {
std::shared_ptr<Texture> texture; // Textura de la notificación
std::shared_ptr<Sprite> sprite; // Sprite asociado
std::vector<std::string> texts; // Textos a mostrar
int counter; // Contador de tiempo
NotificationStatus state; // Estado de la notificación
NotificationShape shape; // Forma de la notificación
SDL_FRect rect; // Rectángulo de la notificación
int y; // Posición vertical
int travel_dist; // Distancia a recorrer
std::string code; // Código identificador de la notificación
// --- Estructura Notification ---
struct Notification {
std::shared_ptr<Texture> texture; // Textura de la notificación
std::shared_ptr<Sprite> sprite; // Sprite asociado
std::vector<std::string> texts; // Textos a mostrar
int counter; // Contador de tiempo
NotificationStatus state; // Estado de la notificación
NotificationShape shape; // Forma de la notificación
SDL_FRect rect; // Rectángulo de la notificación
int y; // Posición vertical
int travel_dist; // Distancia a recorrer
std::string code; // Código identificador de la notificación
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), counter(0), state(NotificationStatus::RISING), shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
// Constructor
explicit Notification()
: texture(nullptr), sprite(nullptr), texts(), counter(0), state(NotificationStatus::RISING), shape(NotificationShape::SQUARED), rect{0, 0, 0, 0}, y(0), travel_dist(0), code("") {}
};
// --- Objetos y punteros ---

View File

@@ -37,7 +37,7 @@ struct Path {
};
// Devuelve un vector con los puntos que conforman la ruta
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easingFunction);
std::vector<SDL_FPoint> createPath(float start, float end, PathType type, float fixed_pos, int steps, const std::function<double(double)> &easing_function);
// --- Clase PathSprite: Sprite que sigue uno o varios recorridos ---
class PathSprite : public Sprite {
@@ -54,7 +54,7 @@ class PathSprite : public Sprite {
// --- Gestión de recorridos ---
void addPath(Path path, bool centered = false); // Añade un recorrido (Path)
void addPath(std::vector<SDL_FPoint> spots, int waiting_counter = 0); // Añade un recorrido a partir de puntos
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easingFunction, int waiting_counter = 0); // Añade un recorrido generado
void addPath(int start, int end, PathType type, int fixed_pos, int steps, const std::function<double(double)> &easing_function, int waiting_counter = 0); // Añade un recorrido generado
// --- Estado y control ---
void enable(); // Habilita el objeto

View File

@@ -46,7 +46,7 @@ void Player::init() {
firing_state_ = PlayerState::FIRING_NONE;
playing_state_ = PlayerState::WAITING;
power_up_ = false;
power_up_counter_ = POWERUP_COUNTER_;
power_up_counter_ = POWERUP_COUNTER;
extra_hit_ = false;
coffees_ = 0;
continue_ticks_ = 0;
@@ -91,12 +91,12 @@ void Player::setInput(InputAction input) {
void Player::setInputPlaying(InputAction input) {
switch (input) {
case InputAction::LEFT: {
vel_x_ = -BASE_SPEED_;
vel_x_ = -BASE_SPEED;
setWalkingState(PlayerState::WALKING_LEFT);
break;
}
case InputAction::RIGHT: {
vel_x_ = BASE_SPEED_;
vel_x_ = BASE_SPEED;
setWalkingState(PlayerState::WALKING_RIGHT);
break;
}
@@ -153,7 +153,7 @@ void Player::move() {
// Si el jugador abandona el area de juego por los laterales, restaura su posición
const float MIN_X = play_area_.x - 5;
const float MAX_X = play_area_.w + 5 - WIDTH_;
const float MAX_X = play_area_.w + 5 - WIDTH;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -163,7 +163,7 @@ void Player::move() {
// Si el jugador abandona el area de juego por los laterales lo hace rebotar
const int X = player_sprite_->getPosX();
const int MIN_X = play_area_.x;
const int MAX_X = play_area_.x + play_area_.w - WIDTH_;
const int MAX_X = play_area_.x + play_area_.w - WIDTH;
if ((X < MIN_X) || (X > MAX_X)) {
player_sprite_->setPosX(std::clamp(X, MIN_X, MAX_X));
player_sprite_->setVelX(-player_sprite_->getVelX());
@@ -171,10 +171,10 @@ 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_->getPosY() > play_area_.h - HEIGHT) {
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;
const auto NEXT_PLAYER_STATUS = isEligibleForHighScore() ? PlayerState::ENTERING_NAME : PlayerState::CONTINUE;
demo_ ? setPlayingState(PlayerState::LYING_ON_THE_FLOOR_FOREVER) : setPlayingState(NEXT_PLAYER_STATUS);
pos_x_ = player_sprite_->getPosX();
pos_y_ = default_pos_y_;
@@ -183,7 +183,7 @@ void Player::move() {
playSound("jump.wav");
} else {
// Decrementa las velocidades de rebote
player_sprite_->setPosY(play_area_.h - HEIGHT_);
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_->setAnimationSpeed(player_sprite_->getAnimationSpeed() * 2);
@@ -195,7 +195,7 @@ void Player::move() {
case PlayerState::TITLE_ANIMATION: {
// Si el jugador abandona el area de juego por los laterales lo detiene
/*const int X = player_sprite_->getPosX();
const int MIN_X = play_area_.x - WIDTH_;
const int MIN_X = play_area_.x - WIDTH;
const int MAX_X = play_area_.x + play_area_.w;
if ((X < MIN_X) || (X > MAX_X))
{
@@ -219,7 +219,7 @@ void Player::move() {
break;
}
pos_x_ += vel_x_ * 2.0f;
const float MIN_X = -WIDTH_;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -253,7 +253,7 @@ void Player::move() {
break;
}
pos_x_ += vel_x_;
const float MIN_X = -WIDTH_;
const float MIN_X = -WIDTH;
const float MAX_X = play_area_.w;
pos_x_ = std::clamp(pos_x_, MIN_X, MAX_X);
shiftSprite();
@@ -298,8 +298,8 @@ void Player::move() {
pos_x_ += vel_x_ / 2.0f;
if (vel_x_ > 0) {
// setInputPlaying(InputAction::RIGHT);
if (pos_x_ > param.game.game_area.rect.w - WIDTH_) {
pos_x_ = param.game.game_area.rect.w - WIDTH_;
if (pos_x_ > param.game.game_area.rect.w - WIDTH) {
pos_x_ = param.game.game_area.rect.w - WIDTH;
vel_x_ *= -1;
}
} else {
@@ -310,7 +310,7 @@ void Player::move() {
}
}
if (pos_x_ > param.game.game_area.center_x - WIDTH_ / 2) {
if (pos_x_ > param.game.game_area.center_x - WIDTH / 2) {
setWalkingState(PlayerState::WALKING_LEFT);
} else {
setWalkingState(PlayerState::WALKING_RIGHT);
@@ -326,7 +326,7 @@ void Player::move() {
// Pinta el jugador en pantalla
void Player::render() {
if (power_up_ && isPlaying()) {
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4) {
if (power_up_counter_ > (POWERUP_COUNTER / 4) || power_up_counter_ % 20 > 4) {
power_sprite_->render();
}
}
@@ -406,7 +406,7 @@ void Player::setAnimation() {
void Player::updateCooldown() {
if (playing_state_ == PlayerState::PLAYING) {
if (cant_fire_counter_ > 0) {
cooling_state_counter_ = COOLING_DURATION_;
cooling_state_counter_ = COOLING_DURATION;
// La mitad del tiempo que no puede disparar tiene el brazo arriba (PlayerState::FIRING)
// y la otra mitad en retroceso (PlayerState::RECOILING)
@@ -434,8 +434,8 @@ void Player::updateCooldown() {
if (recoiling_state_counter_ > 0) {
--recoiling_state_counter_;
} else {
if (cooling_state_counter_ > COOLING_COMPLETE_) {
if (cooling_state_counter_ == COOLING_DURATION_) {
if (cooling_state_counter_ > COOLING_COMPLETE) {
if (cooling_state_counter_ == COOLING_DURATION) {
switch (firing_state_) {
case PlayerState::RECOILING_LEFT:
setFiringState(PlayerState::COOLING_LEFT);
@@ -454,7 +454,7 @@ void Player::updateCooldown() {
--cooling_state_counter_;
}
if (cooling_state_counter_ == COOLING_COMPLETE_) {
if (cooling_state_counter_ == COOLING_COMPLETE) {
setFiringState(PlayerState::FIRING_NONE);
cooling_state_counter_ = -1;
}
@@ -608,7 +608,7 @@ void Player::setPlayingState(PlayerState state) {
setScoreboardMode(ScoreboardMode::SCORE);
switch (id_) {
case 1:
pos_x_ = param.game.game_area.rect.x - WIDTH_;
pos_x_ = param.game.game_area.rect.x - WIDTH;
break;
case 2:
@@ -621,7 +621,7 @@ void Player::setPlayingState(PlayerState state) {
break;
}
case PlayerState::CREDITS: {
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED_ : -BASE_SPEED_;
vel_x_ = (walking_state_ == PlayerState::WALKING_RIGHT) ? BASE_SPEED : -BASE_SPEED;
break;
}
default:
@@ -644,7 +644,7 @@ void Player::decScoreMultiplier() {
// Establece el valor del estado
void Player::setInvulnerable(bool value) {
invulnerable_ = value;
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER : 0;
}
// Monitoriza el estado
@@ -664,7 +664,7 @@ void Player::updateInvulnerable() {
// Establece el valor de la variable
void Player::setPowerUp() {
power_up_ = true;
power_up_counter_ = POWERUP_COUNTER_;
power_up_counter_ = POWERUP_COUNTER;
}
// Actualiza el valor de la variable
@@ -698,8 +698,8 @@ void Player::removeExtraHit() {
// 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_.x = static_cast<int>(pos_x_ + (WIDTH / 2));
collider_.y = static_cast<int>(pos_y_ + (HEIGHT / 2));
}
// Pone las texturas del jugador

View File

@@ -122,7 +122,7 @@ class Player {
bool hasExtraHit() const { return extra_hit_; }
bool isCooling() const { return firing_state_ == PlayerState::COOLING_LEFT || firing_state_ == PlayerState::COOLING_UP || firing_state_ == PlayerState::COOLING_RIGHT; }
bool isRecoiling() const { return firing_state_ == PlayerState::RECOILING_LEFT || firing_state_ == PlayerState::RECOILING_UP || firing_state_ == PlayerState::RECOILING_RIGHT; }
bool IsEligibleForHighScore() const { return score_ > Options::settings.hi_score_table.back().score; }
bool isEligibleForHighScore() const { return score_ > Options::settings.hi_score_table.back().score; }
bool isInvulnerable() const { return invulnerable_; }
bool isPowerUp() const { return power_up_; }
Circle &getCollider() { return collider_; }
@@ -130,7 +130,7 @@ class Player {
int getCoffees() const { return coffees_; }
int getContinueCounter() const { return continue_counter_; }
int getController() const { return controller_index_; }
int getHeight() const { return HEIGHT_; }
int getHeight() const { return HEIGHT; }
int getId() const { return id_; }
int getInvulnerableCounter() const { return invulnerable_counter_; }
int getPosX() const { return static_cast<int>(pos_x_); }
@@ -140,7 +140,7 @@ class Player {
std::string getLastEnterName() const { return last_enter_name_; }
int getScore() const { return score_; }
int getScoreBoardPanel() const { return scoreboard_panel_; }
int getWidth() const { return WIDTH_; }
int getWidth() const { return WIDTH; }
PlayerState getPlayingState() const { return playing_state_; }
const std::string &getName() const { return name_; }
bool get1CC() const { return game_completed_ && credits_used_ == 1; }
@@ -161,71 +161,71 @@ class Player {
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;
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
bool isRenderable() const { 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); // Cambia el modo del marcador
void playSound(const std::string &name); // Hace sonar un sonido
bool isRenderable() const { return !isWaiting() && !isGameOver() && !isTitleHidden(); }
void addScoreToScoreBoard(); // Añade una puntuación a la tabla de records
};

View File

@@ -18,16 +18,16 @@ struct JA_Music_t; // lines 11-11
struct JA_Sound_t; // lines 12-12
// Singleton
Resource *Resource::instance_ = nullptr;
Resource *Resource::instance = nullptr;
// Inicializa la instancia única del singleton
void Resource::init() { Resource::instance_ = new Resource(); }
void Resource::init() { Resource::instance = new Resource(); }
// Libera la instancia
void Resource::destroy() { delete Resource::instance_; }
void Resource::destroy() { delete Resource::instance; }
// Obtiene la instancia
Resource *Resource::get() { return Resource::instance_; }
Resource *Resource::get() { return Resource::instance; }
// Constructor
Resource::Resource() : loading_text_(Screen::get()->getText()) { load(); }
@@ -260,11 +260,11 @@ void Resource::addPalettes() {
// Crea texturas a partir de textos para mostrar puntuaciones y mensajes
void Resource::createTextures() {
struct NameAndText {
std::string name;
std::string text;
std::string name;
std::string text;
NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {}
NameAndText(const std::string &name_init, const std::string &text_init)
: name(name_init), text(text_init) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXTURES");
@@ -303,12 +303,12 @@ void Resource::createTextures() {
// Crea los objetos de texto a partir de los archivos de textura y texto
void Resource::createText() {
struct ResourceInfo {
std::string key;
std::string texture_file;
std::string text_file;
std::string key;
std::string texture_file;
std::string text_file;
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
: key(k), texture_file(t_file), text_file(txt_file) {}
ResourceInfo(const std::string &k, const std::string &t_file, const std::string &txt_file)
: key(k), texture_file(t_file), text_file(txt_file) {}
};
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "\n>> CREATING TEXT OBJECTS");

View File

@@ -146,5 +146,5 @@ class Resource {
~Resource(); // Destructor privado
// --- Instancia singleton ---
static Resource *instance_; // Instancia única de Resource
static Resource *instance; // Instancia única de Resource
};

View File

@@ -16,21 +16,21 @@
#include "texture.h" // Para Texture
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Scoreboard *Scoreboard::scoreboard_ = nullptr;
Scoreboard *Scoreboard::instance = nullptr;
// [SINGLETON] Crearemos el objeto score_board con esta función estática
void Scoreboard::init() {
Scoreboard::scoreboard_ = new Scoreboard();
Scoreboard::instance = new Scoreboard();
}
// [SINGLETON] Destruiremos el objeto score_board con esta función estática
void Scoreboard::destroy() {
delete Scoreboard::scoreboard_;
delete Scoreboard::instance;
}
// [SINGLETON] Con este método obtenemos el objeto score_board y podemos trabajar con él
Scoreboard *Scoreboard::get() {
return Scoreboard::scoreboard_;
return Scoreboard::instance;
}
// Constructor

View File

@@ -67,55 +67,55 @@ class Scoreboard {
void setStage(int stage) { stage_ = stage; }
private:
// --- Singleton ---
static Scoreboard *scoreboard_;
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::shared_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// --- Variables de estado ---
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Variables de estado ---
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre de cada jugador
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
size_t selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
int stage_ = 1; // Número de fase actual
int hi_score_ = 0; // Máxima puntuación
float power_ = 0; // Poder actual de la fase
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
Color color_ = Color(); // Color del marcador
SDL_FRect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
Uint64 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTicks()
int time_counter_ = 0; // Contador de segundos
int loop_counter_ = 0; // Contador de bucle
std::vector<Color> name_colors_; // Colores para destacar el nombre una vez introducido
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
// --- Variables de aspecto ---
Color text_color1_, text_color2_; // Colores para los marcadores del texto;
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Puntos predefinidos para colocar elementos en los paneles ---
SDL_FPoint slot4_1_, slot4_2_, slot4_3_, slot4_4_;
SDL_FPoint enter_name_pos_;
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
std::string updateScoreText(int num); // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Métodos internos ---
void recalculateAnchors(); // Recalcula las anclas de los elementos
std::string updateScoreText(int num); // Transforma un valor numérico en una cadena de 7 cifras
void createBackgroundTexture(); // Crea la textura de fondo
void createPanelTextures(); // Crea las texturas de los paneles
void fillPanelTextures(); // Rellena los diferentes paneles del marcador
void fillBackgroundTexture(); // Rellena la textura de fondo
void updateTimeCounter(); // Actualiza el contador
void renderSeparator(); // Dibuja la línea que separa la zona de juego del marcador
void iniNameColors(); // Inicializa el vector de colores para el nombre
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Constructor y destructor privados (singleton) ---
Scoreboard();
~Scoreboard();
// --- Singleton ---
static Scoreboard *instance;
};

View File

@@ -19,16 +19,16 @@
#include "ui/service_menu.h" // Para ServiceMenu
// Singleton
Screen *Screen::instance_ = nullptr;
Screen *Screen::instance = nullptr;
// Inicializa la instancia única del singleton
void Screen::init() { Screen::instance_ = new Screen(); }
void Screen::init() { Screen::instance = new Screen(); }
// Libera la instancia
void Screen::destroy() { delete Screen::instance_; }
void Screen::destroy() { delete Screen::instance; }
// Obtiene la instancia
auto Screen::get() -> Screen * { return Screen::instance_; }
auto Screen::get() -> Screen * { return Screen::instance; }
// Constructor
Screen::Screen()
@@ -214,7 +214,7 @@ void Screen::renderInfo() {
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(Options::video.info) - 2, 1, Options::video.info, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
// FPS
const std::string FPS_TEXT = std::to_string(fps_.lastValue) + " FPS";
const std::string FPS_TEXT = std::to_string(fps_.last_value) + " FPS";
debug_info_.text->writeDX(TEXT_COLOR | TEXT_STROKE, param.game.width - debug_info_.text->lenght(FPS_TEXT) - 2, 1 + debug_info_.text->getCharacterSize(), FPS_TEXT, 1, param.debug.color, 1, param.debug.color.DARKEN(150));
}
}
@@ -254,7 +254,7 @@ void Screen::adjustWindowSize() {
const int NEW_POS_X = old_pos_x + ((old_width - WIDTH) / 2);
const int NEW_POS_Y = old_pos_y + ((old_height - HEIGHT) / 2);
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS_), std::max(NEW_POS_Y, 0));
SDL_SetWindowPosition(window_, std::max(NEW_POS_X, WINDOWS_DECORATIONS), std::max(NEW_POS_Y, 0));
SDL_SetWindowSize(window_, WIDTH, HEIGHT);
}
}
@@ -370,7 +370,7 @@ void Screen::getDisplayInfo() {
std::to_string(static_cast<int>(dm->refresh_rate)) + " Hz";
// Calcula el máximo factor de zoom que se puede aplicar a la pantalla
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS_) / param.game.height);
const int MAX_ZOOM = std::min(dm->w / param.game.width, (dm->h - WINDOWS_DECORATIONS) / param.game.height);
// Normaliza los valores de zoom
Options::window.size = std::min(Options::window.size, MAX_ZOOM);

View File

@@ -62,24 +62,24 @@ class Screen {
private:
// --- Constantes ---
static constexpr int WINDOWS_DECORATIONS_ = 35;
static constexpr int WINDOWS_DECORATIONS = 35;
// --- Estructuras internas ---
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frameCount; // Número acumulado de frames en el intervalo.
int lastValue; // Número de frames calculado en el último segundo.
// --- Estructuras internas ---
struct FPS {
Uint32 ticks; // Tiempo en milisegundos desde que se comenzó a contar.
int frame_count; // Número acumulado de frames en el intervalo.
int last_value; // Número de frames calculado en el último segundo.
FPS() : ticks(0), frameCount(0), lastValue(0) {}
void increment() { frameCount++; }
int calculate(Uint32 currentTicks) {
if (currentTicks - ticks >= 1000) {
lastValue = frameCount;
frameCount = 0;
ticks = currentTicks;
}
return lastValue;
}
FPS() : ticks(0), frame_count(0), last_value(0) {}
void increment() { frame_count++; }
int calculate(Uint32 current_ticks) {
if (current_ticks - ticks >= 1000) {
last_value = frame_count;
frame_count = 0;
ticks = current_ticks;
}
return last_value;
}
};
// Efecto de flash en pantalla: pinta la pantalla de un color durante unos frames
@@ -108,8 +108,8 @@ class Screen {
int original_width; // Ancho original de la imagen
bool enabled; // Indica si el efecto está activo
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int origPos = 0, int origWidth = 800)
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(origPos), original_width(origWidth), enabled(en) {}
explicit ShakeEffect(bool en = false, int dp = 2, int dl = 3, int cnt = 0, int len = 8, int rem = 0, int orig_pos = 0, int orig_width = 800)
: desp(dp), delay(dl), counter(cnt), lenght(len), remaining(rem), original_pos(orig_pos), original_width(orig_width), enabled(en) {}
// Activa el efecto de sacudida y guarda la posición y tamaño originales
void enable(SDL_FRect &src_rect, SDL_FRect &dst_rect, int new_desp = -1, int new_delay = -1, int new_lenght = -1) {
@@ -168,7 +168,7 @@ class Screen {
#endif
// --- Singleton ---
static Screen *instance_;
static Screen *instance;
// --- Objetos y punteros ---
SDL_Window *window_; // Ventana de la aplicación

View File

@@ -170,9 +170,8 @@ void Credits::fillTextTexture() {
const int TEXTS_HEIGHT = 1 * text->getCharacterSize() + 8 * SPACE_POST_TITLE + 3 * SPACE_PRE_TITLE;
credits_rect_dst_.h = credits_rect_src_.h = TEXTS_HEIGHT;
int y = (param.game.height - TEXTS_HEIGHT) / 2;
// PROGRAMMED_AND_DESIGNED_BY
y = 0;
int y = 0;
text_grad->writeDX(TEXT_CENTER | TEXT_SHADOW, param.game.game_area.center_x, y, TEXTS.at(0), 1, NO_TEXT_COLOR, 1, SHADOW_TEXT_COLOR);
y += SPACE_POST_TITLE;
@@ -259,7 +258,7 @@ void Credits::fillCanvas() {
// SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0xFF, 0, 0, 0xFF);
const Color COLOR = color_.LIGHTEN();
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), COLOR.r, COLOR.g, COLOR.b, 0xFF);
SDL_RenderRect(Screen::get()->getRenderer(), &red_rect);
SDL_RenderRect(Screen::get()->getRenderer(), &border_rect_);
// Si el mini_logo está en su destino, lo dibuja encima de lo anterior
if (mini_logo_on_position_) {
@@ -408,10 +407,10 @@ void Credits::updateBlackRects() {
// Actualiza el rectangulo rojo
void Credits::updateRedRect() {
red_rect.x = left_black_rect_.x + left_black_rect_.w;
red_rect.y = top_black_rect_.y + top_black_rect_.h - 1;
red_rect.w = right_black_rect_.x - red_rect.x;
red_rect.h = bottom_black_rect_.y - red_rect.y + 1;
border_rect_.x = left_black_rect_.x + left_black_rect_.w;
border_rect_.y = top_black_rect_.y + top_black_rect_.h - 1;
border_rect_.w = right_black_rect_.x - border_rect_.x;
border_rect_.h = bottom_black_rect_.y - border_rect_.y + 1;
}
// Actualiza el estado de fade

View File

@@ -16,114 +16,114 @@ class Player;
class TiledBG;
class Credits {
public:
// --- Constructores y destructor ---
Credits();
~Credits();
public:
// --- Constructores y destructor ---
Credits();
~Credits();
// --- Bucle principal ---
void run();
// --- Bucle principal ---
void run();
private:
// --- Constantes de clase ---
static constexpr int PLAY_AREA_HEIGHT = 200;
private:
// --- Constantes de clase ---
static constexpr int PLAY_AREA_HEIGHT = 200;
// --- Objetos principales ---
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
std::unique_ptr<Fade> fade_out_; // Fundido de salida
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
// --- Objetos principales ---
std::unique_ptr<BalloonManager> balloon_manager_; // Gestión de globos
std::unique_ptr<TiledBG> tiled_bg_; // Mosaico animado de fondo
std::unique_ptr<Fade> fade_in_; // Fundido de entrada
std::unique_ptr<Fade> fade_out_; // Fundido de salida
std::vector<std::shared_ptr<Player>> players_; // Vector de jugadores
// --- Gestión de texturas ---
SDL_Texture *text_texture_; // Textura con el texto de créditos
SDL_Texture *canvas_; // Textura donde se dibuja todo
// --- Gestión de texturas ---
SDL_Texture *text_texture_; // Textura con el texto de créditos
SDL_Texture *canvas_; // Textura donde se dibuja todo
// --- Temporización y contadores ---
Uint64 ticks_ = 0; // Control de velocidad del programa
Uint32 counter_ = 0; // Contador principal de lógica
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
// --- Temporización y contadores ---
Uint64 ticks_ = 0; // Control de velocidad del programa
Uint32 counter_ = 0; // Contador principal de lógica
Uint32 counter_pre_fade_ = 0; // Activación del fundido final
Uint32 counter_prevent_endless_ = 0; // Prevención de bucle infinito
// --- Variables de estado ---
bool fading_ = false; // Estado del fade final
bool want_to_pass_ = false; // Jugador quiere saltarse créditos
bool mini_logo_on_position_ = false; // Minilogo en posición final
// --- Variables de estado ---
bool fading_ = false; // Estado del fade final
bool want_to_pass_ = false; // Jugador quiere saltarse créditos
bool mini_logo_on_position_ = false; // Minilogo en posición final
// --- Diseño y posicionamiento ---
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
int mini_logo_final_pos_ = 0; // Posición final del minilogo
Color color_; // Color usado para los efectos
// --- Diseño y posicionamiento ---
float black_bars_size_ = (param.game.game_area.rect.h - PLAY_AREA_HEIGHT) / 2; // Tamaño de las barras negras
int mini_logo_final_pos_ = 0; // Posición final del minilogo
Color color_; // Color usado para los efectos
// --- Control de audio ---
int initial_volume_ = Options::audio.music.volume; // Volumen inicial
int steps_ = 0; // Pasos para reducir audio
// --- Control de audio ---
int initial_volume_ = Options::audio.music.volume; // Volumen inicial
int steps_ = 0; // Pasos para reducir audio
// --- Rectángulos de renderizado ---
// Texto de créditos
SDL_FRect credits_rect_src_ = param.game.game_area.rect;
SDL_FRect credits_rect_dst_ = param.game.game_area.rect;
// --- Rectángulos de renderizado ---
// Texto de créditos
SDL_FRect credits_rect_src_ = param.game.game_area.rect;
SDL_FRect credits_rect_dst_ = param.game.game_area.rect;
// Mini logo
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect;
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect;
// Mini logo
SDL_FRect mini_logo_rect_src_ = param.game.game_area.rect;
SDL_FRect mini_logo_rect_dst_ = param.game.game_area.rect;
// Definición del área de juego
SDL_FRect play_area_ = {
param.game.game_area.rect.x,
param.game.game_area.rect.y + black_bars_size_,
param.game.game_area.rect.w,
PLAY_AREA_HEIGHT};
// Definición del área de juego
SDL_FRect play_area_ = {
param.game.game_area.rect.x,
param.game.game_area.rect.y + black_bars_size_,
param.game.game_area.rect.w,
PLAY_AREA_HEIGHT};
// Barras negras para efecto letterbox
SDL_FRect top_black_rect_ = {
play_area_.x,
param.game.game_area.rect.y,
play_area_.w,
black_bars_size_};
SDL_FRect bottom_black_rect_ = {
play_area_.x,
param.game.game_area.rect.h - black_bars_size_,
play_area_.w,
black_bars_size_};
SDL_FRect left_black_rect_ = {
play_area_.x,
param.game.game_area.center_y - 1,
0,
2};
SDL_FRect right_black_rect_ = {
play_area_.x + play_area_.w,
param.game.game_area.center_y - 1,
0,
2};
// Barras negras para efecto letterbox
SDL_FRect top_black_rect_ = {
play_area_.x,
param.game.game_area.rect.y,
play_area_.w,
black_bars_size_};
SDL_FRect bottom_black_rect_ = {
play_area_.x,
param.game.game_area.rect.h - black_bars_size_,
play_area_.w,
black_bars_size_};
SDL_FRect left_black_rect_ = {
play_area_.x,
param.game.game_area.center_y - 1,
0,
2};
SDL_FRect right_black_rect_ = {
play_area_.x + play_area_.w,
param.game.game_area.center_y - 1,
0,
2};
// Borde para la ventana
SDL_FRect red_rect = play_area_; // Delimitador de ventana
// Borde para la ventana
SDL_FRect border_rect_ = play_area_; // Delimitador de ventana
// --- Métodos del bucle principal ---
void update(); // Actualización principal de la lógica
void render(); // Renderizado de la escena
void checkEvents(); // Manejo de eventos
void checkInput(); // Procesamiento de entrada
// --- Métodos del bucle principal ---
void update(); // Actualización principal de la lógica
void render(); // Renderizado de la escena
void checkEvents(); // Manejo de eventos
void checkInput(); // Procesamiento de entrada
// --- Métodos de renderizado ---
void fillTextTexture(); // Crear textura de texto de créditos
void fillCanvas(); // Renderizar todos los sprites y fondos
void updateTextureDstRects(); // Actualizar destinos de texturas
void renderPlayers(); // Renderiza los jugadores
// --- Métodos de renderizado ---
void fillTextTexture(); // Crear textura de texto de créditos
void fillCanvas(); // Renderizar todos los sprites y fondos
void updateTextureDstRects(); // Actualizar destinos de texturas
void renderPlayers(); // Renderiza los jugadores
// --- Métodos de lógica del juego ---
void throwBalloons(); // Lanzar globos al escenario
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(); // Actualza los jugadores
// --- Métodos de lógica del juego ---
void throwBalloons(); // Lanzar globos al escenario
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(); // Actualza los jugadores
// --- Métodos de interfaz ---
void updateBlackRects(); // Actualizar rectángulos negros (letterbox)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
// --- Métodos de interfaz ---
void updateBlackRects(); // Actualizar rectángulos negros (letterbox)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
// --- Métodos de audio ---
void setVolume(int amount); // Establecer volumen
void resetVolume(); // Restablecer volumen
// --- Métodos de audio ---
void setVolume(int amount); // Establecer volumen
void resetVolume(); // Restablecer volumen
};

View File

@@ -283,7 +283,7 @@ void Game::updateGameStateGameOver() {
cleanVectors();
if (game_over_counter_ > 0) {
if (game_over_counter_ == GAME_OVER_COUNTER_) {
if (game_over_counter_ == GAME_OVER_COUNTER) {
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
Audio::get()->fadeOutMusic(1000);
balloon_manager_->setBouncingSounds(true);
@@ -367,7 +367,7 @@ void Game::updateGameStateCompleted() {
if (game_completed_counter_ == END_CELEBRATIONS) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->IsEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
player->setPlayingState(player->isEligibleForHighScore() ? PlayerState::ENTERING_NAME_GAME_COMPLETED : PlayerState::LEAVING_SCREEN);
}
}
}
@@ -621,7 +621,7 @@ ItemType Game::dropItem() {
break;
case 4:
if (LUCKY_NUMBER < helper_.item_coffee_odds) {
helper_.item_coffee_odds = ITEM_COFFEE_ODDS_;
helper_.item_coffee_odds = ITEM_COFFEE_ODDS;
return ItemType::COFFEE;
} else {
if (helper_.need_coffee) {
@@ -631,7 +631,7 @@ ItemType Game::dropItem() {
break;
case 5:
if (LUCKY_NUMBER < helper_.item_coffee_machine_odds) {
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS_;
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS;
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) {
return ItemType::COFFEE_MACHINE;
}
@@ -786,7 +786,7 @@ void Game::handlePlayerCollision(std::shared_ptr<Player> &player) {
screen_->shake();
playSound("voice_no.wav");
player->setPlayingState(PlayerState::ROLLING);
players_to_reorder.push_back(player);
players_to_reorder_.push_back(player);
if (allPlayersAreNotPlaying()) {
// No se puede subir poder de fase si no hay nadie jugando
Stage::power_can_be_added = false;
@@ -928,7 +928,7 @@ void Game::render() {
void Game::enableTimeStopItem() {
balloon_manager_->stopAllBalloons();
balloon_manager_->reverseColorsToAllBalloons();
time_stopped_counter_ = TIME_STOPPED_COUNTER_;
time_stopped_counter_ = TIME_STOPPED_COUNTER;
}
// Deshabilita el efecto del item de detener el tiempo
@@ -1158,12 +1158,12 @@ void Game::checkInput() {
// Comprueba las entradas si no está el menú de servicio activo
if (!ServiceMenu::get()->isEnabled()) {
checkPauseInput();
demo_.enabled ? DEMO_handlePassInput() : handlePlayersInput();
demo_.enabled ? demoHandlePassInput() : handlePlayersInput();
}
// Mueve los jugadores en el modo demo
if (demo_.enabled) {
DEMO_handleInput();
demoHandleInput();
}
// Verifica los inputs globales.
@@ -1188,7 +1188,7 @@ void Game::checkPauseInput() {
}
// Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void Game::DEMO_handlePassInput() {
void Game::demoHandlePassInput() {
if (input_->checkAnyButton()) {
Section::name = Section::Name::TITLE; // Salir del modo demo y regresar al menú principal.
Section::attract_mode = Section::AttractMode::TITLE_TO_DEMO; // El juego volverá a mostrar la demo
@@ -1197,19 +1197,19 @@ void Game::DEMO_handlePassInput() {
}
// Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void Game::DEMO_handleInput() {
void Game::demoHandleInput() {
int index = 0;
for (const auto &player : players_) {
if (player->isPlaying()) {
// Maneja el input específico del jugador en modo demo.
DEMO_handlePlayerInput(player, index);
demoHandlePlayerInput(player, index);
}
++index;
}
}
// Procesa las entradas para un jugador específico durante el modo demo.
void Game::DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index) {
void Game::demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index) {
const auto &demo_data = demo_.data[index][demo_.counter];
if (demo_data.left == 1) {
@@ -1721,10 +1721,10 @@ void Game::playSound(const std::string &name) {
// Organiza los jugadores para que los vivos se pinten sobre los muertos
void Game::movePlayersToFront() {
if (players_to_reorder.empty())
if (players_to_reorder_.empty())
return;
for (auto &player : players_to_reorder) {
for (auto &player : players_to_reorder_) {
auto it = std::find(players_.begin(), players_.end(), player);
if (it != players_.end() && it != players_.begin()) {
std::shared_ptr<Player> dying_player = *it;
@@ -1732,7 +1732,7 @@ void Game::movePlayersToFront() {
players_.insert(players_.begin(), dying_player);
}
}
players_to_reorder.clear();
players_to_reorder_.clear();
}
// Comprueba si está activo el menu de servicio para poner el juego en pausa

View File

@@ -39,13 +39,13 @@ constexpr int TOTAL_SCORE_DATA = 3;
class Game {
public:
// Constructor
Game(int playerID, int current_stage, bool demo);
Game(int player_id, int current_stage, bool demo);
// Destructor
~Game();
// Destructor
~Game();
// Bucle principal del juego
void run();
// Bucle principal del juego
void run();
private:
// --- Tipos internos ---
@@ -59,18 +59,18 @@ class Game {
};
// --- Constantes internas ---
static constexpr int HELP_COUNTER_ = 1000;
static constexpr int GAME_COMPLETED_START_FADE_ = 500;
static constexpr int GAME_COMPLETED_END_ = 700;
static constexpr int GAME_OVER_COUNTER_ = 350;
static constexpr int TIME_STOPPED_COUNTER_ = 360;
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
static constexpr int ITEM_POINTS_2_GAVINA_ODDS_ = 6;
static constexpr int ITEM_POINTS_3_PACMAR_ODDS_ = 3;
static constexpr int ITEM_CLOCK_ODDS_ = 5;
static constexpr int ITEM_COFFEE_ODDS_ = 5;
static constexpr int ITEM_POWER_BALL_ODDS_ = 0;
static constexpr int ITEM_COFFEE_MACHINE_ODDS_ = 4;
static constexpr int HELP_COUNTER = 1000;
static constexpr int GAME_COMPLETED_START_FADE = 500;
static constexpr int GAME_COMPLETED_END = 700;
static constexpr int GAME_OVER_COUNTER = 350;
static constexpr int TIME_STOPPED_COUNTER = 360;
static constexpr int ITEM_POINTS_1_DISK_ODDS = 10;
static constexpr int ITEM_POINTS_2_GAVINA_ODDS = 6;
static constexpr int ITEM_POINTS_3_PACMAR_ODDS = 3;
static constexpr int ITEM_CLOCK_ODDS = 5;
static constexpr int ITEM_COFFEE_ODDS = 5;
static constexpr int ITEM_POWER_BALL_ODDS = 0;
static constexpr int ITEM_COFFEE_MACHINE_ODDS = 4;
// --- Estructuras ---
struct Helper {
@@ -89,13 +89,13 @@ class Game {
: need_coffee(false),
need_coffee_machine(false),
need_power_ball(false),
counter(HELP_COUNTER_),
item_disk_odds(ITEM_POINTS_1_DISK_ODDS_),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS_),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS_),
item_clock_odds(ITEM_CLOCK_ODDS_),
item_coffee_odds(ITEM_COFFEE_ODDS_),
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS_) {}
counter(HELP_COUNTER),
item_disk_odds(ITEM_POINTS_1_DISK_ODDS),
item_gavina_odds(ITEM_POINTS_2_GAVINA_ODDS),
item_pacmar_odds(ITEM_POINTS_3_PACMAR_ODDS),
item_clock_odds(ITEM_CLOCK_ODDS),
item_coffee_odds(ITEM_COFFEE_ODDS),
item_coffee_machine_odds(ITEM_COFFEE_MACHINE_ODDS) {}
};
// --- Objetos y punteros ---
@@ -144,13 +144,13 @@ class Game {
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
int counter_ = 0; // Contador para el juego
int game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
int game_over_counter_ = GAME_OVER_COUNTER_; // Contador para el estado de fin de partida
int game_over_counter_ = GAME_OVER_COUNTER; // Contador para el estado de fin de partida
int time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
int menace_current_ = 0; // Nivel de amenaza actual
int menace_threshold_ = 0; // Umbral del nivel de amenaza. Si el nivel de amenaza cae por debajo del umbral, se generan más globos. Si el umbral aumenta, aumenta el número de globos
GameState state_ = GameState::FADE_IN; // Estado
std::vector<std::shared_ptr<Player>> players_to_reorder;
std::vector<std::shared_ptr<Player>> players_to_reorder_;
#ifdef DEBUG
bool auto_pop_balloons_ = false; // Si es true, incrementa automaticamente los globos explotados
@@ -208,16 +208,16 @@ class Game {
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); // Saca del estado de GAME OVER al jugador si el otro está activo
void checkPlayersStatusPlaying(); // Comprueba el estado de juego de los jugadores
std::shared_ptr<Player> getPlayer(int id); // Obtiene un jugador a partir de su "id"
int getController(int playerId); // Obtiene un controlador a partir del "id" del jugador
int getController(int player_id); // Obtiene un controlador a partir del "id" del jugador
void checkInput(); // Gestiona la entrada durante el juego
void checkPauseInput(); // Verifica si alguno de los controladores ha solicitado una pausa y actualiza el estado de pausa del juego.
void DEMO_handleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void DEMO_handlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void DEMO_handlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bulletType); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void demoHandleInput(); // Gestiona las entradas de los jugadores en el modo demo, incluyendo movimientos y disparos automáticos.
void demoHandlePassInput(); // Gestiona las entradas de los jugadores en el modo demo para saltarse la demo.
void demoHandlePlayerInput(const std::shared_ptr<Player> &player, int index); // Procesa las entradas para un jugador específico durante el modo demo.
void handleFireInput(const std::shared_ptr<Player> &player, BulletType bullet_type); // Maneja el disparo de un jugador, incluyendo la creación de balas y la gestión del tiempo de espera entre disparos.
void handlePlayersInput(); // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
void handleNormalPlayerInput(const std::shared_ptr<Player> &player); // Maneja las entradas de movimiento y disparo para un jugador en modo normal.
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controllerIndex); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
void handleFireInputs(const std::shared_ptr<Player> &player, bool autofire, int controller_index); // Procesa las entradas de disparo del jugador, permitiendo disparos automáticos si está habilitado.
void handlePlayerContinue(const std::shared_ptr<Player> &player); // Maneja la continuación del jugador cuando no está jugando, permitiendo que continúe si se pulsa el botón de inicio.
void handleNameInput(const std::shared_ptr<Player> &player); // Procesa las entradas para la introducción del nombre del jugador.
void initDemo(int player_id); // Inicializa las variables para el modo DEMO

View File

@@ -383,7 +383,7 @@ void HiScoreTable::updateCounter() {
background_->setAlpha(96);
}
if (counter_ == COUNTER_END_) {
if (counter_ == COUNTER_END) {
fade_->activate();
}
}

View File

@@ -39,40 +39,40 @@ class HiScoreTable {
private:
// --- Constantes ---
static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador
static constexpr Uint16 COUNTER_END = 800; // Valor final para el contador
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
std::vector<Path> paths_; // Vector con los recorridos precalculados
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::unique_ptr<Background> background_; // Objeto para dibujar el fondo del juego
std::unique_ptr<Sprite> header_; // Sprite con la cabecera del texto
std::vector<std::shared_ptr<PathSprite>> entry_names_; // Lista con los sprites de cada uno de los nombres de la tabla de records
std::vector<Path> paths_; // Vector con los recorridos precalculados
// --- Variables ---
Uint16 counter_ = 0; // Contador
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
// --- Variables ---
Uint16 counter_ = 0; // Contador
Uint64 ticks_; // Contador de ticks para ajustar la velocidad del programa
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
FadeMode fade_mode_; // Modo de fade a utilizar
Color background_fade_color_; // Color de atenuación del fondo
std::vector<Color> entry_colors_; // Colores para destacar las entradas en la tabla
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
std::string format(int number); // 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
void updateSprites(); // Actualiza las posiciones de los sprites de texto
void initFade(); // Inicializa el fade
void initBackground(); // Inicializa el fondo
Color getEntryColor(int counter_); // Obtiene un color del vector de colores de entradas
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador
// --- Métodos internos ---
void update(); // Actualiza las variables
void render(); // Pinta en pantalla
void checkEvents(); // Comprueba los eventos
void checkInput(); // Comprueba las entradas
std::string format(int number); // 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
void updateSprites(); // Actualiza las posiciones de los sprites de texto
void initFade(); // Inicializa el fade
void initBackground(); // Inicializa el fondo
Color getEntryColor(int counter); // Obtiene un color del vector de colores de entradas
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador
};

View File

@@ -294,12 +294,12 @@ bool Instructions::moveLines(std::vector<Line> &lines, int width, float duration
bool all_lines_off_screen = true;
for (auto &line : lines) {
// Establecer startTime en el primer cuadro de animación
if (line.startTime == 0) {
line.startTime = current_time + line.y * start_delay;
// Establecer start_time en el primer cuadro de animación
if (line.start_time == 0) {
line.start_time = current_time + line.y * start_delay;
}
float elapsed_time = (current_time - line.startTime) / 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;

View File

@@ -29,11 +29,11 @@ struct Line {
int y; // Coordenada Y de la línea
float x; // Coordenada X inicial (usamos float para mayor precisión en el suavizado)
int direction; // Dirección de movimiento: -1 para izquierda, 1 para derecha
Uint32 startTime; // Tiempo de inicio del movimiento
Uint32 start_time; // Tiempo de inicio del movimiento
// Constructor de Line
Line(int y, float x, int direction)
: y(y), x(x), direction(direction), startTime(0) {}
: y(y), x(x), direction(direction), start_time(0) {}
};
// Clase Instructions
@@ -81,7 +81,7 @@ class Instructions {
void iniSprites(); // Inicializa los sprites de los items
void updateSprites(); // Actualiza los sprites
std::vector<Line> initializeLines(int height); // Inicializa las líneas animadas
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 startDelay); // Mueve las líneas
bool moveLines(std::vector<Line> &lines, int width, float duration, Uint32 start_delay); // Mueve las líneas
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

@@ -408,11 +408,11 @@ void Title::updateStartPrompt() {
}
}
should_render_start_prompt = condition_met;
should_render_start_prompt_ = condition_met;
}
void Title::renderStartPrompt() {
if (should_render_start_prompt) {
if (should_render_start_prompt_) {
text_->writeDX(TEXT_CENTER | TEXT_SHADOW,
param.game.game_area.center_x,
param.title.press_start_position,

View File

@@ -67,7 +67,7 @@ class Title {
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
int num_controllers_; // Número de mandos conectados
TitleState state_; // Estado actual de la sección
bool should_render_start_prompt = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
bool should_render_start_prompt_ = false; // Indica si se muestra o no el texto de PRESS START BUTTON TO PLAY
bool player1_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 1
bool player2_start_pressed_ = false; // Indica si se ha pulsdo el boton de empezar a jugar para el jugador 2

View File

@@ -53,20 +53,20 @@ TiledBG::~TiledBG() {
// Rellena la textura con el contenido
void TiledBG::fillTexture() {
// Crea los objetos para pintar en la textura de fondo
auto tile = std::make_unique<Sprite>(Resource::get()->getTexture("title_bg_tile.png"), (SDL_FRect){0, 0, TILE_WIDTH_, TILE_HEIGHT_});
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_);
SDL_SetRenderTarget(renderer_, canvas_);
// Rellena la textura con el tile
const auto I_MAX = pos_.w * 2 / TILE_WIDTH_;
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT_;
tile->setSpriteClip(0, 0, TILE_WIDTH_, TILE_HEIGHT_);
const auto I_MAX = pos_.w * 2 / TILE_WIDTH;
const auto J_MAX = pos_.h * 2 / TILE_HEIGHT;
tile->setSpriteClip(0, 0, TILE_WIDTH, TILE_HEIGHT);
for (int i = 0; i < I_MAX; ++i) {
for (int j = 0; j < J_MAX; ++j) {
tile->setX(i * TILE_WIDTH_);
tile->setY(j * TILE_HEIGHT_);
tile->setX(i * TILE_WIDTH);
tile->setY(j * TILE_HEIGHT);
tile->render();
}
}
@@ -88,8 +88,8 @@ void TiledBG::update() {
switch (mode_) {
case TiledBGMode::DIAGONAL: {
// El tileado de fondo se desplaza en diagonal
window_.x = static_cast<int>(desp_) % TILE_WIDTH_;
window_.y = static_cast<int>(desp_) % TILE_HEIGHT_;
window_.x = static_cast<int>(desp_) % TILE_WIDTH;
window_.y = static_cast<int>(desp_) % TILE_HEIGHT;
break;
}
@@ -112,7 +112,7 @@ void TiledBG::updateStop() {
const int UMBRAL = 20 * speed_; // Ajusta este valor según la precisión deseada
// Desacelerar si estamos cerca de completar el ciclo (ventana a punto de regresar a 0)
if (window_.x >= TILE_WIDTH_ - UMBRAL) {
if (window_.x >= TILE_WIDTH - UMBRAL) {
speed_ /= 1.05f; // Reduce gradualmente la velocidad
// Asegura que no baje demasiado

View File

@@ -39,24 +39,24 @@ class TiledBG {
private:
// --- Constantes ---
static constexpr int TILE_WIDTH_ = 64; // Ancho del tile
static constexpr int TILE_HEIGHT_ = 64; // Alto del tile
static constexpr int TILE_WIDTH = 64; // Ancho del tile
static constexpr int TILE_HEIGHT = 64; // Alto del tile
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
// --- Objetos y punteros ---
SDL_Renderer *renderer_; // El renderizador de la ventana
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
// --- Variables de estado ---
SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados
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
// --- Variables de estado ---
SDL_FRect pos_; // Posición y tamaño del mosaico
SDL_FRect window_; // Ventana visible para la textura de fondo del título
TiledBGMode mode_; // Tipo de movimiento del mosaico
double sin_[360]; // Vector con los valores del seno precalculados
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 ---
void fillTexture(); // Rellena la textura con el contenido
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
void updateStop(); // Detiene el desplazamiento de forma ordenada
// --- Métodos internos ---
void fillTexture(); // Rellena la textura con el contenido
void updateDesp() { desp_ += speed_; } // Actualiza el desplazamiento
void updateStop(); // Detiene el desplazamiento de forma ordenada
};

View File

@@ -78,8 +78,8 @@ class IntOption : public MenuOption {
Behavior getBehavior() const override { return Behavior::ADJUST; }
std::string getValueAsString() const override { return std::to_string(*linked_variable_); }
void adjustValue(bool adjust_up) override {
int newValue = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(newValue, min_value_, max_value_);
int new_value = *linked_variable_ + (adjust_up ? step_value_ : -step_value_);
*linked_variable_ = std::clamp(new_value, min_value_, max_value_);
}
int getMaxValueWidth(Text *text_renderer) const override {
int max_width = 0;

View File

@@ -37,7 +37,7 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
// Dibuja la línea separadora
y = rect_.y + upper_height_;
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), BORDER_COLOR.r, BORDER_COLOR.g, BORDER_COLOR.b, 255);
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y);
SDL_RenderLine(Screen::get()->getRenderer(), rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y);
// Dibuja las opciones
y = options_y_;
@@ -47,8 +47,8 @@ void MenuRenderer::render(const ServiceMenu *menu_state) {
const Color &current_color = IS_SELECTED ? param.service_menu.selected_color : param.service_menu.text_color;
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING_, y, option_pairs.at(i).first, current_color, -2);
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ - element_text_->lenght(option_pairs.at(i).second, -2);
element_text_->writeColored(rect_.x + ServiceMenu::OPTIONS_HORIZONTAL_PADDING, y, option_pairs.at(i).first, current_color, -2);
const int X = rect_.x + rect_.w - ServiceMenu::OPTIONS_HORIZONTAL_PADDING - element_text_->lenght(option_pairs.at(i).second, -2);
element_text_->writeColored(X, y, option_pairs.at(i).second, current_color, -2);
} else {
element_text_->writeDX(TEXT_CENTER | TEXT_COLOR, rect_.x + rect_.w / 2, y, option_pairs.at(i).first, -2, current_color);
@@ -96,7 +96,7 @@ void MenuRenderer::setAnchors(const ServiceMenu *menu_state) {
lower_padding_ = (options_padding_ * 3);
lower_height_ = ((max_entries > 0 ? max_entries - 1 : 0) * (options_height_ + options_padding_)) + options_height_ + (lower_padding_ * 2);
width_ = ServiceMenu::MIN_WIDTH_;
width_ = ServiceMenu::MIN_WIDTH;
height_ = upper_height_ + lower_height_;
}
@@ -151,7 +151,7 @@ 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_)
w = ServiceMenu::MIN_WIDTH_;
w = ServiceMenu::MIN_WIDTH;
for (int group = 0; group < 5; ++group) {
auto sg = static_cast<ServiceMenu::SettingsGroup>(group);
int max_option_width = 0;
@@ -164,11 +164,11 @@ void MenuRenderer::precalculateMenuWidths(const std::vector<std::unique_ptr<Menu
max_value_width = std::max(max_value_width, option->getMaxValueWidth(element_text_.get()));
}
}
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING_ * 2);
size_t total_width = max_option_width + (ServiceMenu::OPTIONS_HORIZONTAL_PADDING * 2);
if (menu_state->getCurrentGroupAlignment() == ServiceMenu::GroupAlignment::LEFT) {
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE_ + max_value_width;
total_width += ServiceMenu::MIN_GAP_OPTION_VALUE + max_value_width;
}
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH_, (int)total_width);
group_menu_widths_[group] = std::max((int)ServiceMenu::MIN_WIDTH, (int)total_width);
}
}

View File

@@ -13,10 +13,10 @@
#include "utils.h" // Para Zone
// Singleton
ServiceMenu *ServiceMenu::instance_ = nullptr;
void ServiceMenu::init() { ServiceMenu::instance_ = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance_; }
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance_; }
ServiceMenu *ServiceMenu::instance = nullptr;
void ServiceMenu::init() { ServiceMenu::instance = new ServiceMenu(); }
void ServiceMenu::destroy() { delete ServiceMenu::instance; }
ServiceMenu *ServiceMenu::get() { return ServiceMenu::instance; }
// Constructor
ServiceMenu::ServiceMenu()
@@ -150,7 +150,7 @@ void ServiceMenu::updateOptionPairs() {
void ServiceMenu::updateMenu() {
title_ = settingsGroupToString(current_settings_group_);
AdjustListValues();
adjustListValues();
// Actualiza las opciones visibles
updateDisplayOptions();
@@ -254,7 +254,7 @@ void ServiceMenu::initializeOptions() {
}
// Sincroniza los valores de las opciones tipo lista
void ServiceMenu::AdjustListValues() {
void ServiceMenu::adjustListValues() {
for (auto &option : options_) {
if (auto list_option = dynamic_cast<ListOption *>(option.get())) {
list_option->sync();

View File

@@ -28,9 +28,9 @@ class ServiceMenu {
};
// --- Constantes públicas que el Renderer podría necesitar ---
static constexpr size_t OPTIONS_HORIZONTAL_PADDING_ = 20;
static constexpr size_t MIN_WIDTH_ = 240;
static constexpr size_t MIN_GAP_OPTION_VALUE_ = 30;
static constexpr size_t OPTIONS_HORIZONTAL_PADDING = 20;
static constexpr size_t MIN_WIDTH = 240;
static constexpr size_t MIN_GAP_OPTION_VALUE = 30;
static void init();
static void destroy();
@@ -89,7 +89,7 @@ class ServiceMenu {
void applyAudioSettings();
void applySettingsSettings();
MenuOption *getOptionByCaption(const std::string &caption) const;
void AdjustListValues();
void adjustListValues();
void playMoveSound();
void playAdjustSound();
void playSelectSound();
@@ -102,5 +102,5 @@ class ServiceMenu {
~ServiceMenu() = default;
ServiceMenu(const ServiceMenu &) = delete;
ServiceMenu &operator=(const ServiceMenu &) = delete;
static ServiceMenu *instance_;
static ServiceMenu *instance;
};

View File

@@ -13,7 +13,7 @@ void UIMessage::show() {
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
start_y_ = DESP; // Empieza 8 píxeles arriba de la posición base
target_y_ = 0.0f; // La posición final es la base
y_offset_ = start_y_;
anim_step_ = 0;
@@ -27,7 +27,7 @@ void UIMessage::hide() {
return;
start_y_ = y_offset_; // Comienza desde la posición actual
target_y_ = DESP_; // Termina 8 píxeles arriba de la base
target_y_ = DESP; // Termina 8 píxeles arriba de la base
anim_step_ = 0;
animating_ = true;
}

View File

@@ -49,7 +49,7 @@ class UIMessage {
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

@@ -67,7 +67,7 @@ void Writer::setEnabled(bool value) {
}
// Obtiene el valor de la variable
bool Writer::IsEnabled() const {
bool Writer::isEnabled() const {
return enabled_;
}

View File

@@ -34,7 +34,7 @@ class Writer {
void center(int x);
// Getters
bool IsEnabled() const; // Indica si el objeto está habilitado
bool isEnabled() const; // Indica si el objeto está habilitado
bool hasFinished() const; // Indica si ya ha terminado
private: