magic numbers: logo.cpp

This commit is contained in:
2025-09-17 13:01:43 +02:00
parent 66566913f6
commit 577510ff8c
3 changed files with 105 additions and 73 deletions

View File

@@ -42,7 +42,7 @@ Director::Director(int argc, std::span<char *> argv) {
Section::name = Section::Name::GAME; Section::name = Section::Name::GAME;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#elif _DEBUG #elif _DEBUG
Section::name = Section::Name::GAME; Section::name = Section::Name::LOGO;
Section::options = Section::Options::GAME_PLAY_1P; Section::options = Section::Options::GAME_PLAY_1P;
#else // NORMAL GAME #else // NORMAL GAME
Section::name = Section::Name::LOGO; Section::name = Section::Name::LOGO;

View File

@@ -28,38 +28,38 @@ Logo::Logo()
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2; dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2;
since_sprite_->setPosition(SDL_FRect{ since_sprite_->setPosition(SDL_FRect{
static_cast<float>((param.game.width - since_texture_->getWidth()) / 2), static_cast<float>((param.game.width - since_texture_->getWidth()) / 2),
static_cast<float>(83 + jail_texture_->getHeight() + 5), static_cast<float>(SINCE_SPRITE_Y_OFFSET + jail_texture_->getHeight() + LOGO_SPACING),
static_cast<float>(since_texture_->getWidth()), static_cast<float>(since_texture_->getWidth()),
static_cast<float>(since_texture_->getHeight())}); static_cast<float>(since_texture_->getHeight())});
since_sprite_->setY(dest_.y + jail_texture_->getHeight() + 5); since_sprite_->setY(dest_.y + jail_texture_->getHeight() + LOGO_SPACING);
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight()); since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
since_texture_->setColor(0x00, 0x00, 0x00); since_texture_->setColor(SPECTRUM_BLACK.r, SPECTRUM_BLACK.g, SPECTRUM_BLACK.b);
// Crea los sprites de cada linea // Crea los sprites de cada linea
for (int i = 0; i < jail_texture_->getHeight(); ++i) { for (int i = 0; i < jail_texture_->getHeight(); ++i) {
auto temp = std::make_unique<Sprite>(jail_texture_, 0, i, jail_texture_->getWidth(), 1); auto temp = std::make_unique<Sprite>(jail_texture_, 0, i, jail_texture_->getWidth(), SPRITE_LINE_HEIGHT);
temp->setSpriteClip(0, i, jail_texture_->getWidth(), 1); temp->setSpriteClip(0, i, jail_texture_->getWidth(), SPRITE_LINE_HEIGHT);
const int POS_X = (i % 2 == 0) ? param.game.width + (i * 3) : -jail_texture_->getWidth() - (i * 3); const int POS_X = (i % 2 == 0) ? param.game.width + (i * LINE_OFFSET_FACTOR) : -jail_texture_->getWidth() - (i * LINE_OFFSET_FACTOR);
temp->setX(POS_X); temp->setX(POS_X);
temp->setY(dest_.y + i); temp->setY(dest_.y + i);
jail_sprite_.push_back(std::move(temp)); jail_sprite_.push_back(std::move(temp));
} }
// Inicializa el vector de colores // Inicializa el vector de colores con la paleta ZX Spectrum
color_.emplace_back(0x00, 0x00, 0x00); // Black color_.emplace_back(SPECTRUM_BLACK);
color_.emplace_back(0x00, 0x00, 0xd8); // Blue color_.emplace_back(SPECTRUM_BLUE);
color_.emplace_back(0xd8, 0x00, 0x00); // Red color_.emplace_back(SPECTRUM_RED);
color_.emplace_back(0xd8, 0x00, 0xd8); // Magenta color_.emplace_back(SPECTRUM_MAGENTA);
color_.emplace_back(0x00, 0xd8, 0x00); // Green color_.emplace_back(SPECTRUM_GREEN);
color_.emplace_back(0x00, 0xd8, 0xd8); // Cyan color_.emplace_back(SPECTRUM_CYAN);
color_.emplace_back(0xd8, 0xd8, 0x00); // Yellow color_.emplace_back(SPECTRUM_YELLOW);
color_.emplace_back(0xFF, 0xFF, 0xFF); // Bright white color_.emplace_back(SPECTRUM_WHITE);
} }
// Destructor // Destructor
Logo::~Logo() { Logo::~Logo() {
jail_texture_->setColor(255, 255, 255); jail_texture_->setColor(RESET_COLOR.r, RESET_COLOR.g, RESET_COLOR.b);
since_texture_->setColor(255, 255, 255); since_texture_->setColor(RESET_COLOR.r, RESET_COLOR.g, RESET_COLOR.b);
Audio::get()->stopAllSounds(); Audio::get()->stopAllSounds();
Audio::get()->stopMusic(); Audio::get()->stopMusic();
} }
@@ -78,24 +78,30 @@ void Logo::checkInput() {
GlobalInputs::check(); GlobalInputs::check();
} }
// Maneja la reproducción del sonido del logo
void Logo::handleSound() {
static bool sound_triggered = false;
if (!sound_triggered && elapsed_time_ms_ >= SOUND_TRIGGER_TIME_MS) {
Audio::get()->playSound("logo.wav");
sound_triggered = true;
}
}
// Gestiona el logo de JAILGAMES // Gestiona el logo de JAILGAMES
void Logo::updateJAILGAMES(float delta_time) { void Logo::updateJAILGAMES(float delta_time) {
if (counter_ == 30) { if (elapsed_time_ms_ > SOUND_TRIGGER_TIME_MS) {
Audio::get()->playSound("logo.wav"); const float PIXELS_TO_MOVE = LOGO_SPEED_PX_PER_MS * delta_time;
}
if (counter_ > 30) { for (size_t i = 0; i < jail_sprite_.size(); ++i) {
const float pixels_to_move = SPEED * delta_time;
for (int i = 0; i < (int)jail_sprite_.size(); ++i) {
if (jail_sprite_[i]->getX() != dest_.x) { if (jail_sprite_[i]->getX() != dest_.x) {
if (i % 2 == 0) { if (i % 2 == 0) {
jail_sprite_[i]->incX(-pixels_to_move); jail_sprite_[i]->incX(-PIXELS_TO_MOVE);
if (jail_sprite_[i]->getX() < dest_.x) { if (jail_sprite_[i]->getX() < dest_.x) {
jail_sprite_[i]->setX(dest_.x); jail_sprite_[i]->setX(dest_.x);
} }
} else { } else {
jail_sprite_[i]->incX(pixels_to_move); jail_sprite_[i]->incX(PIXELS_TO_MOVE);
if (jail_sprite_[i]->getX() > dest_.x) { if (jail_sprite_[i]->getX() > dest_.x) {
jail_sprite_[i]->setX(dest_.x); jail_sprite_[i]->setX(dest_.x);
} }
@@ -105,48 +111,41 @@ void Logo::updateJAILGAMES(float delta_time) {
} }
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
if (counter_ == END_LOGO_COUNTER_MARK + POST_LOGO_DURATION) { if (elapsed_time_ms_ >= END_LOGO_TIME_MS + POST_LOGO_DURATION_MS) {
Section::name = Section::Name::INTRO; Section::name = Section::Name::INTRO;
} }
} }
// Gestiona el color de las texturas // Gestiona el color de las texturas
void Logo::updateTextureColors() { void Logo::updateTextureColors(float delta_time) {
constexpr int INC = 4;
// Manejo de 'sinceTexture' // Manejo de 'sinceTexture'
for (int i = 0; i <= 7; ++i) { for (int i = 0; i <= MAX_SINCE_COLOR_INDEX; ++i) {
if (counter_ == SHOW_SINCE_SPRITE_COUNTER_MARK + INC * i) { const float target_time = SHOW_SINCE_SPRITE_TIME_MS + COLOR_CHANGE_INTERVAL_MS * i;
if (elapsed_time_ms_ >= target_time && elapsed_time_ms_ - delta_time < target_time) {
since_texture_->setColor(color_[i].r, color_[i].g, color_[i].b); since_texture_->setColor(color_[i].r, color_[i].g, color_[i].b);
} }
} }
// Manejo de 'jailTexture' y 'sinceTexture' en el fade // Manejo de 'jailTexture' y 'sinceTexture' en el fade
for (int i = 0; i <= 6; ++i) { for (int i = 0; i <= MAX_FADE_COLOR_INDEX; ++i) {
if (counter_ == INIT_FADE_COUNTER_MARK + INC * i) { const float target_time = INIT_FADE_TIME_MS + COLOR_CHANGE_INTERVAL_MS * i;
jail_texture_->setColor(color_[6 - i].r, color_[6 - i].g, color_[6 - i].b); if (elapsed_time_ms_ >= target_time && elapsed_time_ms_ - delta_time < target_time) {
since_texture_->setColor(color_[6 - i].r, color_[6 - i].g, color_[6 - i].b); jail_texture_->setColor(color_[MAX_FADE_COLOR_INDEX - i].r, color_[MAX_FADE_COLOR_INDEX - i].g, color_[MAX_FADE_COLOR_INDEX - i].b);
since_texture_->setColor(color_[MAX_FADE_COLOR_INDEX - i].r, color_[MAX_FADE_COLOR_INDEX - i].g, color_[MAX_FADE_COLOR_INDEX - i].b);
} }
} }
} }
// Actualiza las variables // Actualiza las variables
void Logo::update(float delta_time) { void Logo::update(float delta_time) {
static float logic_accumulator = 0.0f; elapsed_time_ms_ += delta_time; // Acumula el tiempo transcurrido
logic_accumulator += delta_time;
// Ejecutar lógica a 60 FPS (cada 16.67ms) para mantener consistencia en counter_ y colores Screen::get()->update(); // Actualiza el objeto screen
constexpr float LOGIC_FRAME_TIME = 1000.0f / 60.0f; Audio::update(); // Actualiza el objeto audio
if (logic_accumulator >= LOGIC_FRAME_TIME) { handleSound(); // Maneja la reproducción del sonido
Screen::get()->update(); // Actualiza el objeto screen updateTextureColors(delta_time); // Actualiza los colores de las texturas
updateTextureColors(); // Actualiza los colores de las texturas updateJAILGAMES(delta_time); // Actualiza el logo de JAILGAMES
++counter_; // Gestiona el contador
logic_accumulator -= LOGIC_FRAME_TIME;
}
updateJAILGAMES(delta_time); // Actualiza el logo de JAILGAMES con delta-time real
Audio::update();
} }
// Dibuja en pantalla // Dibuja en pantalla
@@ -190,7 +189,7 @@ void Logo::renderJAILGAMES() {
sprite->render(); sprite->render();
} }
if (counter_ >= SHOW_SINCE_SPRITE_COUNTER_MARK) { if (elapsed_time_ms_ >= SHOW_SINCE_SPRITE_TIME_MS) {
since_sprite_->render(); since_sprite_->render();
} }
} }

View File

@@ -10,12 +10,21 @@
class Texture; class Texture;
// --- Clase Logo: dibuja el logo de JAILGAMES con efectos visuales --- // --- Clase Logo: pantalla de presentación de JAILGAMES con efectos retro ---
// Esta clase gestiona un estado del programa. Se encarga de dibujar por pantalla el //
// logo de "JAILGAMES" utilizando un sencillo efecto consistente en generar un sprite por // Esta clase gestiona el estado inicial del programa, mostrando el logo corporativo
// cada línea del bitmap que forma la palabra "JAILGAMES". Posteriormente realiza una // de JAILGAMES con efectos visuales inspirados en el ZX Spectrum.
// modulación de color sobre la textura para simular un fade to black al estilo //
// ZX Spectrum. // Funcionalidades principales:
// • Animación de convergencia: cada línea del logo entra desde los laterales
// • Efectos de color: transiciones automáticas usando la paleta ZX Spectrum
// • Audio sincronizado: reproduce sonido del logo en momento específico
// • Transición temporal: duración controlada con paso automático al siguiente estado
// • Sistema delta-time: animaciones suaves independientes del framerate
//
// La clase utiliza un sistema de tiempo basado en milisegundos para garantizar
// consistencia visual en diferentes velocidades de procesamiento.
class Logo { class Logo {
public: public:
// --- Constructor y destructor --- // --- Constructor y destructor ---
@@ -26,12 +35,35 @@ class Logo {
void run(); void run();
private: private:
// --- Constantes --- // --- Constantes de tiempo (en milisegundos) ---
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998" static constexpr float SOUND_TRIGGER_TIME_MS = 500.0f; // Tiempo para activar el sonido del logo
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro static constexpr float SHOW_SINCE_SPRITE_TIME_MS = 1167.0f; // Tiempo para mostrar el sprite "SINCE 1998"
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo static constexpr float INIT_FADE_TIME_MS = 5000.0f; // Tiempo de inicio del fade a negro
static constexpr int POST_LOGO_DURATION = 20; // Tiempo que dura el logo con el fade al máximo static constexpr float END_LOGO_TIME_MS = 6668.0f; // Tiempo de finalización del logo
static constexpr float SPEED = 8.0f / 15.0f; // Velocidad de desplazamiento de cada línea (píxeles por ms) static constexpr float POST_LOGO_DURATION_MS = 333.0f; // Duración adicional después del fade
static constexpr float LOGO_SPEED_PX_PER_MS = 8.0f / 16.67f; // Velocidad de desplazamiento (píxeles por ms)
static constexpr float COLOR_CHANGE_INTERVAL_MS = 66.7f; // Intervalo entre cambios de color (~4 frames a 60fps)
// --- Constantes de layout ---
static constexpr int SINCE_SPRITE_Y_OFFSET = 83; // Posición Y base del sprite "Since 1998"
static constexpr int LOGO_SPACING = 5; // Espaciado entre elementos del logo
static constexpr int LINE_OFFSET_FACTOR = 3; // Factor de desplazamiento inicial por línea
static constexpr int SPRITE_LINE_HEIGHT = 1; // Altura de cada línea sprite
// --- Constantes de colores ---
static constexpr int MAX_SINCE_COLOR_INDEX = 7; // Índice máximo para colores del sprite "Since"
static constexpr int MAX_FADE_COLOR_INDEX = 6; // Índice máximo para colores del fade
// --- Paleta ZX Spectrum para efectos de logo ---
static constexpr Color SPECTRUM_BLACK = Color(0x00, 0x00, 0x00); // Negro
static constexpr Color SPECTRUM_BLUE = Color(0x00, 0x00, 0xd8); // Azul
static constexpr Color SPECTRUM_RED = Color(0xd8, 0x00, 0x00); // Rojo
static constexpr Color SPECTRUM_MAGENTA = Color(0xd8, 0x00, 0xd8); // Magenta
static constexpr Color SPECTRUM_GREEN = Color(0x00, 0xd8, 0x00); // Verde
static constexpr Color SPECTRUM_CYAN = Color(0x00, 0xd8, 0xd8); // Cian
static constexpr Color SPECTRUM_YELLOW = Color(0xd8, 0xd8, 0x00); // Amarillo
static constexpr Color SPECTRUM_WHITE = Color(0xFF, 0xFF, 0xFF); // Blanco brillante
static constexpr Color RESET_COLOR = Color(255, 255, 255); // Color de reset
// --- Objetos y punteros --- // --- Objetos y punteros ---
std::shared_ptr<Texture> since_texture_; // Textura con los gráficos "Since 1998" std::shared_ptr<Texture> since_texture_; // Textura con los gráficos "Since 1998"
@@ -40,18 +72,19 @@ class Logo {
std::vector<std::unique_ptr<Sprite>> jail_sprite_; // Vector con los sprites de cada línea que forman el bitmap JAILGAMES std::vector<std::unique_ptr<Sprite>> jail_sprite_; // Vector con los sprites de cada línea que forman el bitmap JAILGAMES
// --- Variables --- // --- Variables ---
std::vector<Color> color_; // Vector con los colores para el fade std::vector<Color> color_; // Vector con los colores para el fade
int counter_ = 0; // Contador float elapsed_time_ms_ = 0.0f; // Tiempo transcurrido en milisegundos
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
SDL_FPoint dest_; // Posición donde dibujar el logo SDL_FPoint dest_; // Posición donde dibujar el logo
// --- Métodos internos --- // --- Métodos internos ---
void update(float delta_time); // Actualiza las variables void update(float delta_time); // Actualiza las variables
void render(); // Dibuja en pantalla void render(); // Dibuja en pantalla
static void checkEvents(); // Comprueba el manejador de eventos static void checkEvents(); // Comprueba el manejador de eventos
static void checkInput(); // Comprueba las entradas static void checkInput(); // Comprueba las entradas
void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAMES void updateJAILGAMES(float delta_time); // Gestiona el logo de JAILGAMES
void renderJAILGAMES(); // Renderiza el logo de JAILGAMES void renderJAILGAMES(); // Renderiza el logo de JAILGAMES
void updateTextureColors(); // Gestiona el color de las texturas void updateTextureColors(float delta_time); // Gestiona el color de las texturas
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame void handleSound(); // Maneja la reproducción del sonido del logo
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
}; };