This commit is contained in:
2025-10-19 22:01:31 +02:00
parent 16306f2325
commit 2b4523d644
101 changed files with 2058 additions and 1564 deletions

View File

@@ -1,10 +1,11 @@
// IWYU pragma: no_include <bits/std_abs.h>
#include "credits.hpp"
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event
#include <SDL3/SDL.h> // Para SDL_RenderFillRect, SDL_RenderTexture, SDL_SetRenderTarget, SDL_SetRenderDrawColor, SDL_CreateTexture, SDL_DestroyTexture, SDL_GetTicks, SDL_GetRenderTarget, SDL_PixelFormat, SDL_PollEvent, SDL_RenderClear, SDL_RenderRect, SDL_SetTextureBlendMode, SDL_TextureAccess, SDL_BLENDMODE_BLEND, SDL_Event, Uint64
#include <algorithm> // Para max, min, clamp
#include <array> // Para array
#include <cmath> // Para abs
#include <stdexcept> // Para runtime_error
#include <string> // Para basic_string, string
#include <string_view> // Para string_view
@@ -12,23 +13,23 @@
#include "audio.hpp" // Para Audio
#include "balloon_manager.hpp" // Para BalloonManager
#include "color.hpp" // Para Zone, Colors::SHADOW_TEXT, Colors::NO_COLOR_MOD, Color
#include "fade.hpp" // Para Fade, FadeType, FadeMode
#include "global_events.hpp" // Para check
#include "color.hpp" // Para Color, SHADOW_TEXT, NO_COLOR_MOD
#include "fade.hpp" // Para Fade
#include "global_events.hpp" // Para handle
#include "global_inputs.hpp" // Para check
#include "input.hpp" // Para Input, Input::ALLOW_REPEAT
#include "input.hpp" // Para Input
#include "lang.hpp" // Para getText
#include "param.hpp" // Para Param, param, ParamGame, ParamFade
#include "player.hpp" // Para Player, PlayerState
#include "player.hpp" // Para Player
#include "resource.hpp" // Para Resource
#include "screen.hpp" // Para Screen
#include "section.hpp" // Para Name, name
#include "sprite.hpp" // Para Sprite
#include "text.hpp" // Para Text, Text::CENTER, Text::SHADOW
#include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture
#include "tiled_bg.hpp" // Para TiledBG, TiledBGMode
#include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp"
#include "utils.hpp" // Para Zone
// Textos
constexpr std::string_view TEXT_COPYRIGHT = "@2020,2025 JailDesigner";
@@ -81,10 +82,10 @@ Credits::~Credits() {
// Calcula el deltatime
auto Credits::calculateDeltaTime() -> float {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
last_time_ = current_time;
return delta_time;
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convertir ms a segundos
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Bucle principal
@@ -93,33 +94,33 @@ void Credits::run() {
while (Section::name == Section::Name::CREDITS) {
checkInput();
const float delta_time = calculateDeltaTime();
update(delta_time);
const float DELTA_TIME = calculateDeltaTime();
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}
}
// Actualiza las variables (time-based)
void Credits::update(float deltaTime) {
const float multiplier = want_to_pass_ ? 4.0f : 1.0f;
const float adjusted_delta_time = deltaTime * multiplier;
void Credits::update(float delta_time) {
const float MULTIPLIER = want_to_pass_ ? 4.0F : 1.0F;
const float ADJUSTED_DELTA_TIME = delta_time * MULTIPLIER;
static auto* const SCREEN = Screen::get();
SCREEN->update(deltaTime); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
SCREEN->update(delta_time); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
tiled_bg_->update(adjusted_delta_time);
tiled_bg_->update(ADJUSTED_DELTA_TIME);
cycleColors();
balloon_manager_->update(adjusted_delta_time);
updateTextureDstRects(adjusted_delta_time);
throwBalloons(adjusted_delta_time);
updatePlayers(adjusted_delta_time);
updateAllFades(adjusted_delta_time);
balloon_manager_->update(ADJUSTED_DELTA_TIME);
updateTextureDstRects(ADJUSTED_DELTA_TIME);
throwBalloons(ADJUSTED_DELTA_TIME);
updatePlayers(ADJUSTED_DELTA_TIME);
updateAllFades(ADJUSTED_DELTA_TIME);
// Convertir deltaTime a equivalente de frames (60fps)
const float frameFactor = adjusted_delta_time * 60.0f;
counter_ += frameFactor;
const float FRAME_FACTOR = ADJUSTED_DELTA_TIME * 60.0F;
counter_ += FRAME_FACTOR;
fillCanvas();
}
@@ -291,9 +292,9 @@ void Credits::fillCanvas() {
}
// Actualiza el destino de los rectangulos de las texturas (time-based)
void Credits::updateTextureDstRects(float deltaTime) {
constexpr float TEXTURE_UPDATE_INTERVAL_S = 10.0f / 60.0f; // ~0.167s (cada 10 frames)
credits_state_.texture_accumulator += deltaTime;
void Credits::updateTextureDstRects(float delta_time) {
constexpr float TEXTURE_UPDATE_INTERVAL_S = 10.0F / 60.0F; // ~0.167s (cada 10 frames)
credits_state_.texture_accumulator += delta_time;
if (credits_state_.texture_accumulator >= TEXTURE_UPDATE_INTERVAL_S) {
credits_state_.texture_accumulator -= TEXTURE_UPDATE_INTERVAL_S;
@@ -325,18 +326,18 @@ void Credits::updateTextureDstRects(float deltaTime) {
}
// Tira globos al escenario (time-based)
void Credits::throwBalloons(float deltaTime) {
void Credits::throwBalloons(float delta_time) {
constexpr int SPEED = 200;
const std::vector<int> SETS = {0, 63, 25, 67, 17, 75, 13, 50};
constexpr float BALLOON_INTERVAL_S = SPEED / 60.0f; // ~3.33s (cada 200 frames)
constexpr float POWERBALL_INTERVAL_S = (SPEED * 4) / 60.0f; // ~13.33s (cada 800 frames)
constexpr float BALLOON_INTERVAL_S = SPEED / 60.0F; // ~3.33s (cada 200 frames)
constexpr float POWERBALL_INTERVAL_S = (SPEED * 4) / 60.0F; // ~13.33s (cada 800 frames)
if (counter_ > ((SETS.size() - 1) * SPEED) * 3) {
return;
}
credits_state_.balloon_accumulator += deltaTime;
credits_state_.powerball_accumulator += deltaTime;
credits_state_.balloon_accumulator += delta_time;
credits_state_.powerball_accumulator += delta_time;
if (credits_state_.balloon_accumulator >= BALLOON_INTERVAL_S) {
credits_state_.balloon_accumulator -= BALLOON_INTERVAL_S;
@@ -418,12 +419,12 @@ void Credits::initPlayers() {
}
// Actualiza los rectangulos negros (time-based)
void Credits::updateBlackRects(float deltaTime) {
static float current_step_ = static_cast<float>(steps_);
constexpr float BLACK_RECT_INTERVAL_S = 4.0f / 60.0f; // ~0.067s (cada 4 frames)
void Credits::updateBlackRects(float delta_time) {
static auto current_step_ = static_cast<float>(steps_);
constexpr float BLACK_RECT_INTERVAL_S = 4.0F / 60.0F; // ~0.067s (cada 4 frames)
if (top_black_rect_.h != param.game.game_area.center_y - 1 && bottom_black_rect_.y != param.game.game_area.center_y + 1) {
// Si los rectangulos superior e inferior no han llegado al centro
credits_state_.black_rect_accumulator += deltaTime;
credits_state_.black_rect_accumulator += delta_time;
if (credits_state_.black_rect_accumulator >= BLACK_RECT_INTERVAL_S) {
credits_state_.black_rect_accumulator -= BLACK_RECT_INTERVAL_S;
@@ -459,8 +460,8 @@ void Credits::updateBlackRects(float deltaTime) {
fade_out_->activate();
} else {
// Convertir deltaTime a equivalente de frames
const float frameFactor = deltaTime * 60.0f;
counter_pre_fade_ += frameFactor;
const float FRAME_FACTOR = delta_time * 60.0F;
counter_pre_fade_ += FRAME_FACTOR;
}
}
}
@@ -475,9 +476,9 @@ void Credits::updateRedRect() {
}
// Actualiza el estado de fade (time-based)
void Credits::updateAllFades(float deltaTime) {
void Credits::updateAllFades(float delta_time) {
if (fading_) {
updateBlackRects(deltaTime);
updateBlackRects(delta_time);
updateRedRect();
}
@@ -510,7 +511,7 @@ void Credits::cycleColors() {
constexpr int LOWER_LIMIT = 30; // Límite inferior
// Inicializar valores RGB si es la primera vez
if (credits_state_.r == 255.0f && credits_state_.g == 0.0f && credits_state_.b == 0.0f && credits_state_.step_r == -0.5f) {
if (credits_state_.r == 255.0F && credits_state_.g == 0.0F && credits_state_.b == 0.0F && credits_state_.step_r == -0.5F) {
credits_state_.r = static_cast<float>(UPPER_LIMIT);
credits_state_.g = static_cast<float>(LOWER_LIMIT);
credits_state_.b = static_cast<float>(LOWER_LIMIT);
@@ -540,9 +541,9 @@ void Credits::cycleColors() {
}
// Actualza los jugadores (time-based)
void Credits::updatePlayers(float deltaTime) {
void Credits::updatePlayers(float delta_time) {
for (auto& player : players_) {
player->update(deltaTime);
player->update(delta_time);
}
}

View File

@@ -27,10 +27,9 @@ class Credits {
private:
// --- Métodos del bucle principal ---
void update(float deltaTime); // Actualización principal de la lógica (time-based)
void update(float delta_time); // Actualización principal de la lógica (time-based)
auto calculateDeltaTime() -> float; // Calcula el deltatime
private:
// --- Constantes de clase ---
static constexpr int PLAY_AREA_HEIGHT = 200;
@@ -67,16 +66,16 @@ class Credits {
// --- Estado de acumuladores para animaciones ---
struct CreditsState {
float texture_accumulator = 0.0f;
float balloon_accumulator = 0.0f;
float powerball_accumulator = 0.0f;
float black_rect_accumulator = 0.0f;
float r = 255.0f; // UPPER_LIMIT
float g = 0.0f; // LOWER_LIMIT
float b = 0.0f; // LOWER_LIMIT
float step_r = -0.5f;
float step_g = 0.3f;
float step_b = 0.1f;
float texture_accumulator = 0.0F;
float balloon_accumulator = 0.0F;
float powerball_accumulator = 0.0F;
float black_rect_accumulator = 0.0F;
float r = 255.0F; // UPPER_LIMIT
float g = 0.0F; // LOWER_LIMIT
float b = 0.0F; // LOWER_LIMIT
float step_r = -0.5F;
float step_g = 0.3F;
float step_b = 0.1F;
} credits_state_;
// --- Rectángulos de renderizado ---
@@ -130,20 +129,20 @@ class Credits {
void renderPlayers(); // Renderiza los jugadores
// --- Métodos de lógica del juego ---
void throwBalloons(); // Lanzar globos al escenario (frame-based)
void throwBalloons(float deltaTime); // Lanzar globos al escenario (time-based)
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade (frame-based)
void updateAllFades(float deltaTime); // Actualizar estados de fade (time-based)
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(float deltaTime); // Actualza los jugadores (time-based)
void throwBalloons(); // Lanzar globos al escenario (frame-based)
void throwBalloons(float delta_time); // Lanzar globos al escenario (time-based)
void initPlayers(); // Inicializar jugadores
void updateAllFades(); // Actualizar estados de fade (frame-based)
void updateAllFades(float delta_time); // Actualizar estados de fade (time-based)
void cycleColors(); // Cambiar colores de fondo
void updatePlayers(float delta_time); // Actualza los jugadores (time-based)
// --- Métodos de interfaz ---
void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based)
void updateBlackRects(float deltaTime); // Actualizar rectángulos negros (letterbox) (time-based)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based)
void updateTextureDstRects(float deltaTime); // Actualizar destinos de texturas (time-based)
void updateBlackRects(); // Actualizar rectángulos negros (letterbox) (frame-based)
void updateBlackRects(float delta_time); // Actualizar rectángulos negros (letterbox) (time-based)
void updateRedRect(); // Actualizar rectángulo rojo (borde)
void updateTextureDstRects(); // Actualizar destinos de texturas (frame-based)
void updateTextureDstRects(float delta_time); // Actualizar destinos de texturas (time-based)
// --- Métodos de audio ---
static void setVolume(int amount); // Establecer volumen

View File

@@ -1,14 +1,16 @@
#include "game.hpp"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_CreateTexture, SDL_Delay, SDL_DestroyTexture, SDL_EventType, SDL_GetRenderTarget, SDL_PollEvent, SDL_RenderTexture, SDL_SetTextureBlendMode, SDL_BLENDMODE_BLEND, SDL_Event, SDL_PixelFormat, SDL_Point, SDL_TextureAccess
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderTarget, SDL_EventType, SDL_CreateTexture, SDL_Delay, SDL_DestroyTexture, SDL_Event, SDL_GetRenderTarget, SDL_PollEvent, SDL_RenderTexture, SDL_SetTextureBlendMode, SDLK_1, SDLK_2, SDLK_3, SDLK_4, SDLK_5, SDLK_6, SDLK_7, SDLK_8, SDLK_9, SDLK_KP_MINUS, SDLK_KP_PLUS, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_Point, SDL_TextureAccess, Uint64
#include <algorithm> // Para find, clamp, find_if, min, std::shuffle, std::iota
#include <algorithm> // Para find, clamp, find_if, min, shuffle
#include <array> // Para array
#include <cstdlib> // Para rand, size_t
#include <functional> // Para function
#include <iterator> // Para size
#include <memory> // Para shared_ptr, unique_ptr, __shared_ptr_access, allocator, make_unique, operator==, make_shared
#include <random> // std::random_device, std::default_random_engine
#include <memory> // Para shared_ptr, unique_ptr, __shared_ptr_access, make_unique, allocator, operator==
#include <numeric> // Para iota
#include <optional> // Para optional
#include <random> // Para random_device, default_random_engine
#include <utility> // Para move
#include "asset.hpp" // Para Asset
@@ -16,12 +18,12 @@
#include "background.hpp" // Para Background
#include "balloon.hpp" // Para Balloon
#include "balloon_manager.hpp" // Para BalloonManager
#include "bullet.hpp" // Para Bullet, Bullet::Type, BulletMoveStatus
#include "bullet.hpp" // Para Bullet
#include "bullet_manager.hpp" // Para BulletManager
#include "color.hpp" // Para Color, Colors::FLASH
#include "color.hpp" // Para Color, FLASH, NO_COLOR_MOD
#include "difficulty.hpp" // Para Code
#include "fade.hpp" // Para Fade, FadeType, FadeMode
#include "global_events.hpp" // Para check
#include "fade.hpp" // Para Fade
#include "global_events.hpp" // Para handle
#include "global_inputs.hpp" // Para check
#include "hit.hpp" // Para Hit
#include "input.hpp" // Para Input
@@ -30,7 +32,7 @@
#include "lang.hpp" // Para getText
#include "manage_hiscore_table.hpp" // Para HiScoreEntry, ManageHiScoreTable
#include "param.hpp" // Para Param, param, ParamGame, ParamScoreboard, ParamFade, ParamBalloon
#include "path_sprite.hpp" // Para Path, PathSprite, createPath, PathType
#include "path_sprite.hpp" // Para Path, PathSprite, PathType
#include "pause_manager.hpp" // Para PauseManager
#include "player.hpp" // Para Player
#include "resource.hpp" // Para Resource
@@ -38,13 +40,14 @@
#include "screen.hpp" // Para Screen
#include "section.hpp" // Para Name, name, AttractMode, Options, attract_mode, options
#include "smart_sprite.hpp" // Para SmartSprite
#include "stage.hpp" // Para number, Stage, get, total_power, power, init, power_can_be_added, stages
#include "stage.hpp" // Para StageManager, StageData
#include "tabe.hpp" // Para Tabe
#include "text.hpp" // Para Text
#include "texture.hpp" // Para Texture
#include "ui/service_menu.hpp" // Para ServiceMenu
#include "utils.hpp" // Para Zone, checkCollision, easeInQuint, easeOutQuint, boolToString
#ifdef _DEBUG
#include <iostream> // Para std::cout
#include <iostream> // Para basic_ostream, basic_ostream::operator<<, operator<<, cout
#include "ui/notifier.hpp" // Para Notifier
#endif
@@ -240,9 +243,9 @@ void Game::updateHiScore() {
}
// Actualiza las variables del jugador
void Game::updatePlayers(float deltaTime) {
void Game::updatePlayers(float delta_time) {
for (auto& player : players_) {
player->update(deltaTime);
player->update(delta_time);
if (player->isPlaying()) {
// Comprueba la colisión entre el jugador y los globos
@@ -341,29 +344,29 @@ void Game::updateStage() {
}
// Actualiza las variables y sistemas durante el estado de fin de partida
void Game::updateGameStateGameOver(float deltaTime) {
void Game::updateGameStateGameOver(float delta_time) {
fade_out_->update();
updatePlayers(deltaTime);
updateScoreboard(deltaTime);
updateBackground(deltaTime);
balloon_manager_->update(deltaTime);
tabe_->update(deltaTime);
bullet_manager_->update(deltaTime);
updateItems(deltaTime);
updateSmartSprites(deltaTime);
updatePathSprites(deltaTime);
updateTimeStopped(deltaTime);
updatePlayers(delta_time);
updateScoreboard(delta_time);
updateBackground(delta_time);
balloon_manager_->update(delta_time);
tabe_->update(delta_time);
bullet_manager_->update(delta_time);
updateItems(delta_time);
updateSmartSprites(delta_time);
updatePathSprites(delta_time);
updateTimeStopped(delta_time);
bullet_manager_->checkCollisions();
cleanVectors();
if (game_over_timer_ < GAME_OVER_DURATION_S) {
game_over_timer_ += deltaTime; // Incremento time-based primero
handleGameOverEvents(); // Maneja eventos después del incremento
game_over_timer_ += delta_time; // Incremento time-based primero
handleGameOverEvents(); // Maneja eventos después del incremento
}
if (Options::audio.enabled) {
const float progress = std::min(game_over_timer_ / GAME_OVER_DURATION_S, 1.0f);
const float VOL = 64.0f * (1.0f - progress);
const float PROGRESS = std::min(game_over_timer_ / GAME_OVER_DURATION_S, 1.0F);
const float VOL = 64.0F * (1.0F - PROGRESS);
Audio::get()->setSoundVolume(static_cast<int>(VOL), Audio::Group::GAME);
}
@@ -378,16 +381,16 @@ void Game::updateGameStateGameOver(float deltaTime) {
}
// Gestiona eventos para el estado del final del juego
void Game::updateGameStateCompleted(float deltaTime) {
updatePlayers(deltaTime);
updateScoreboard(deltaTime);
updateBackground(deltaTime);
balloon_manager_->update(deltaTime);
tabe_->update(deltaTime);
bullet_manager_->update(deltaTime);
updateItems(deltaTime);
updateSmartSprites(deltaTime);
updatePathSprites(deltaTime);
void Game::updateGameStateCompleted(float delta_time) {
updatePlayers(delta_time);
updateScoreboard(delta_time);
updateBackground(delta_time);
balloon_manager_->update(delta_time);
tabe_->update(delta_time);
bullet_manager_->update(delta_time);
updateItems(delta_time);
updateSmartSprites(delta_time);
updatePathSprites(delta_time);
cleanVectors();
// Maneja eventos del juego completado
@@ -399,7 +402,7 @@ void Game::updateGameStateCompleted(float deltaTime) {
}
// Incrementa el acumulador al final
game_completed_timer_ += deltaTime;
game_completed_timer_ += delta_time;
}
// Comprueba el estado del juego
@@ -589,9 +592,9 @@ void Game::handleItemDrop(const std::shared_ptr<Balloon>& balloon, const std::sh
}
// Maneja la destrucción del globo y puntuación
void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player>& player) {
void Game::handleBalloonDestruction(const std::shared_ptr<Balloon>& balloon, const std::shared_ptr<Player>& player) {
if (player->isPlaying()) {
auto const SCORE = balloon_manager_->popBalloon(std::move(balloon)) * player->getScoreMultiplier() * difficulty_score_multiplier_;
auto const SCORE = balloon_manager_->popBalloon(balloon) * player->getScoreMultiplier() * difficulty_score_multiplier_;
player->addScore(SCORE, Options::settings.hi_score_table.back().score);
player->incScoreMultiplier();
}
@@ -600,13 +603,13 @@ void Game::handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std:
}
// Actualiza los items
void Game::updateItems(float deltaTime) {
void Game::updateItems(float delta_time) {
for (auto& item : items_) {
if (item->isEnabled()) {
item->update(deltaTime);
item->update(delta_time);
if (item->isOnFloor()) {
playSound("title.wav");
screen_->shake(1, 0.033f, 0.067f); // desp=1, delay=0.033s, length=0.067s
screen_->shake(1, 0.033F, 0.067F); // desp=1, delay=0.033s, length=0.067s
}
}
}
@@ -711,8 +714,8 @@ void Game::createItemText(int x, const std::shared_ptr<Texture>& texture) {
path_sprites_.back()->setWidth(W);
path_sprites_.back()->setHeight(H);
path_sprites_.back()->setSpriteClip({0, 0, static_cast<float>(W), static_cast<float>(H)});
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 1.667f, easeOutQuint, 0); // 100 frames → 1.667s
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 1.333f, easeInQuint, 0); // 80 frames → 1.333s
path_sprites_.back()->addPath(Y0, Y1, PathType::VERTICAL, x, 1.667F, easeOutQuint, 0); // 100 frames → 1.667s
path_sprites_.back()->addPath(Y1, Y2, PathType::VERTICAL, x, 1.333F, easeInQuint, 0); // 80 frames → 1.333s
path_sprites_.back()->enable();
}
@@ -757,10 +760,10 @@ void Game::throwCoffee(int x, int y) {
smart_sprites_.back()->setPosY(y - 8);
smart_sprites_.back()->setWidth(Item::WIDTH);
smart_sprites_.back()->setHeight(Item::HEIGHT);
smart_sprites_.back()->setVelX((-1.0F + ((rand() % 5) * 0.5F)) * 60.0f); // Convertir a pixels/segundo
smart_sprites_.back()->setVelY(-4.0F * 60.0f); // Convertir a pixels/segundo
smart_sprites_.back()->setVelX((-1.0F + ((rand() % 5) * 0.5F)) * 60.0F); // Convertir a pixels/segundo
smart_sprites_.back()->setVelY(-4.0F * 60.0F); // Convertir a pixels/segundo
smart_sprites_.back()->setAccelX(0.0F);
smart_sprites_.back()->setAccelY(0.2F * 60.0f * 60.0f); // Convertir a pixels/segundo² (0.2 × 60²)
smart_sprites_.back()->setAccelY(0.2F * 60.0F * 60.0F); // Convertir a pixels/segundo² (0.2 × 60²)
smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
smart_sprites_.back()->setDestY(param.game.height + 1);
smart_sprites_.back()->setEnabled(true);
@@ -772,9 +775,9 @@ void Game::throwCoffee(int x, int y) {
}
// Actualiza los SmartSprites
void Game::updateSmartSprites(float deltaTime) {
void Game::updateSmartSprites(float delta_time) {
for (auto& sprite : smart_sprites_) {
sprite->update(deltaTime);
sprite->update(delta_time);
}
}
@@ -786,9 +789,9 @@ void Game::renderSmartSprites() {
}
// Actualiza los PathSprites
void Game::updatePathSprites(float deltaTime) {
void Game::updatePathSprites(float delta_time) {
for (auto& sprite : path_sprites_) {
sprite->update(deltaTime);
sprite->update(delta_time);
}
}
@@ -831,44 +834,44 @@ void Game::handlePlayerCollision(std::shared_ptr<Player>& player, std::shared_pt
}
// Actualiza el estado del tiempo detenido
void Game::updateTimeStopped(float deltaTime) {
static constexpr float WARNING_THRESHOLD_S = 2.0f; // 120 frames a 60fps → segundos
static constexpr float CLOCK_SOUND_INTERVAL_S = 0.5f; // 30 frames a 60fps → segundos
static constexpr float COLOR_FLASH_INTERVAL_S = 0.25f; // 15 frames a 60fps → segundos
void Game::updateTimeStopped(float delta_time) {
static constexpr float WARNING_THRESHOLD_S = 2.0F; // 120 frames a 60fps → segundos
static constexpr float CLOCK_SOUND_INTERVAL_S = 0.5F; // 30 frames a 60fps → segundos
static constexpr float COLOR_FLASH_INTERVAL_S = 0.25F; // 15 frames a 60fps → segundos
if (time_stopped_timer_ > 0) {
time_stopped_timer_ -= deltaTime;
time_stopped_timer_ -= delta_time;
// Fase de advertencia (últimos 2 segundos)
if (time_stopped_timer_ <= WARNING_THRESHOLD_S) {
static float last_sound_time = 0.0f;
static float last_sound_time_ = 0.0F;
// CLAC al entrar en fase de advertencia
if (!time_stopped_flags_.warning_phase_started) {
playSound("clock.wav");
time_stopped_flags_.warning_phase_started = true;
last_sound_time = 0.0f; // Reset para empezar el ciclo rápido
last_sound_time_ = 0.0F; // Reset para empezar el ciclo rápido
}
last_sound_time += deltaTime;
last_sound_time_ += delta_time;
if (last_sound_time >= CLOCK_SOUND_INTERVAL_S) {
if (last_sound_time_ >= CLOCK_SOUND_INTERVAL_S) {
balloon_manager_->normalColorsToAllBalloons();
playSound("clock.wav");
last_sound_time = 0.0f;
last_sound_time_ = 0.0F;
time_stopped_flags_.color_flash_sound_played = false; // Reset flag para el próximo intervalo
} else if (last_sound_time >= COLOR_FLASH_INTERVAL_S && !time_stopped_flags_.color_flash_sound_played) {
} else if (last_sound_time_ >= COLOR_FLASH_INTERVAL_S && !time_stopped_flags_.color_flash_sound_played) {
balloon_manager_->reverseColorsToAllBalloons();
playSound("clock.wav");
time_stopped_flags_.color_flash_sound_played = true; // Evita que suene múltiples veces
}
} else {
// Fase normal - solo sonido ocasional
static float sound_timer = 0.0f;
sound_timer += deltaTime;
if (sound_timer >= CLOCK_SOUND_INTERVAL_S) {
static float sound_timer_ = 0.0F;
sound_timer_ += delta_time;
if (sound_timer_ >= CLOCK_SOUND_INTERVAL_S) {
playSound("clock.wav");
sound_timer = 0.0f;
sound_timer_ = 0.0F;
}
}
@@ -881,15 +884,15 @@ void Game::updateTimeStopped(float deltaTime) {
}
// Actualiza toda la lógica del juego
void Game::update(float deltaTime) {
screen_->update(deltaTime); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
void Game::update(float delta_time) {
screen_->update(delta_time); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
updateDemo(deltaTime);
updateDemo(delta_time);
#ifdef RECORDING
updateRecording(deltaTime);
#endif
updateGameStates(deltaTime);
updateGameStates(delta_time);
fillCanvas();
}
@@ -909,26 +912,26 @@ void Game::render() {
}
// Actualiza los estados del juego
void Game::updateGameStates(float deltaTime) {
void Game::updateGameStates(float delta_time) {
if (!pause_manager_->isPaused()) {
switch (state_) {
case State::FADE_IN:
updateGameStateFadeIn(deltaTime);
updateGameStateFadeIn(delta_time);
break;
case State::ENTERING_PLAYER:
updateGameStateEnteringPlayer(deltaTime);
updateGameStateEnteringPlayer(delta_time);
break;
case State::SHOWING_GET_READY_MESSAGE:
updateGameStateShowingGetReadyMessage(deltaTime);
updateGameStateShowingGetReadyMessage(delta_time);
break;
case State::PLAYING:
updateGameStatePlaying(deltaTime);
updateGameStatePlaying(delta_time);
break;
case State::COMPLETED:
updateGameStateCompleted(deltaTime);
updateGameStateCompleted(delta_time);
break;
case State::GAME_OVER:
updateGameStateGameOver(deltaTime);
updateGameStateGameOver(delta_time);
break;
default:
break;
@@ -937,8 +940,8 @@ void Game::updateGameStates(float deltaTime) {
}
// Actualiza el fondo
void Game::updateBackground(float deltaTime) {
background_->update(deltaTime);
void Game::updateBackground(float delta_time) {
background_->update(delta_time);
}
// Dibuja los elementos de la zona de juego en su textura
@@ -980,10 +983,10 @@ void Game::disableTimeStopItem() {
// Calcula el deltatime en segundos
auto Game::calculateDeltaTime() -> float {
const Uint64 current_time = SDL_GetTicks();
const float delta_time_ms = static_cast<float>(current_time - last_time_);
last_time_ = current_time;
return delta_time_ms / 1000.0f; // Convertir de milisegundos a segundos
const Uint64 CURRENT_TIME = SDL_GetTicks();
const auto DELTA_TIME_MS = static_cast<float>(CURRENT_TIME - last_time_);
last_time_ = CURRENT_TIME;
return DELTA_TIME_MS / 1000.0F; // Convertir de milisegundos a segundos
}
// Bucle para el juego
@@ -991,9 +994,9 @@ void Game::run() {
last_time_ = SDL_GetTicks();
while (Section::name == Section::Name::GAME) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
handleEvents(); // Tiene que ir antes del render
render();
}
@@ -1003,7 +1006,7 @@ void Game::run() {
void Game::initPaths() {
// --- Duración estándar para 80 frames ---
// (Basado en tu ejemplo: 80 frames → 1.333s)
const float DURATION_80F_S = 1.333f;
const float DURATION_80F_S = 1.333F;
// Recorrido para el texto de "Get Ready!" (0,1)
{
@@ -1013,9 +1016,9 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = param.game.play_area.rect.w;
// Y_base es la LÍNEA CENTRAL. addPath(true) restará H/2
const int Y_base = param.game.play_area.center_y;
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 0.5f, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 0.0f, easeInQuint);
const int Y_BASE = param.game.play_area.center_y;
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 0.5F, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
// Recorrido para el texto de "Last Stage!" o de "X stages left" (2,3)
@@ -1026,9 +1029,9 @@ void Game::initPaths() {
const int Y1 = param.game.play_area.center_y - (H / 2);
const int Y2 = -H;
// X_base es la LÍNEA CENTRAL. addPath(true) restará W/2
const int X_base = param.game.play_area.center_x;
paths_.emplace_back(Y0, Y1, PathType::VERTICAL, X_base, DURATION_80F_S, 0.5f, easeOutQuint);
paths_.emplace_back(Y1, Y2, PathType::VERTICAL, X_base, DURATION_80F_S, 0.0f, easeInQuint);
const int X_BASE = param.game.play_area.center_x;
paths_.emplace_back(Y0, Y1, PathType::VERTICAL, X_BASE, DURATION_80F_S, 0.5F, easeOutQuint);
paths_.emplace_back(Y1, Y2, PathType::VERTICAL, X_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
// Recorrido para el texto de "Congratulations!!" (4,5)
@@ -1040,9 +1043,9 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = param.game.play_area.rect.w;
// Y_base es la LÍNEA CENTRAL. addPath(true) restará H/2
const int Y_base = param.game.play_area.center_y - (H / 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 7.0f, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 0.0f, easeInQuint);
const int Y_BASE = param.game.play_area.center_y - (H / 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 7.0F, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
// Recorrido para el texto de "1.000.000 points!" (6,7)
@@ -1054,9 +1057,9 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2);
const int X2 = -W;
// Y_base es la LÍNEA CENTRAL (desplazada PREV_H hacia abajo). addPath(true) restará H/2
const int Y_base = param.game.play_area.center_y + (H / 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 7.0f, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 0.0f, easeInQuint);
const int Y_BASE = param.game.play_area.center_y + (H / 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 7.0F, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
// Recorrido para el texto de "New Record!" (8,9)
@@ -1068,9 +1071,9 @@ void Game::initPaths() {
const int X1 = param.game.play_area.center_x - (W / 2); // Destino (no-fijo), está bien
const int X2 = param.game.play_area.rect.w;
// Y_base es la LÍNEA CENTRAL (desplazada 2*H hacia arriba). addPath(true) restará H/2
const int Y_base = param.game.play_area.center_y - (H * 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 1.0f, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_base, DURATION_80F_S, 0.0f, easeInQuint);
const int Y_BASE = param.game.play_area.center_y - (H * 2);
paths_.emplace_back(X0, X1, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 1.0F, easeOutQuint);
paths_.emplace_back(X1, X2, PathType::HORIZONTAL, Y_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
// Recorrido para el texto de "Game Over" (10,11)
@@ -1081,9 +1084,9 @@ void Game::initPaths() {
const int Y1 = param.game.play_area.center_y - (H / 2); // Destino (no-fijo), está bien
const int Y2 = -H;
// X_base es la LÍNEA CENTRAL. addPath(true) restará W/2
const int X_base = param.game.play_area.center_x;
paths_.emplace_back(Y0, Y1, PathType::VERTICAL, X_base, DURATION_80F_S, 2.0f, easeOutQuint);
paths_.emplace_back(Y1, Y2, PathType::VERTICAL, X_base, DURATION_80F_S, 0.0f, easeInQuint);
const int X_BASE = param.game.play_area.center_x;
paths_.emplace_back(Y0, Y1, PathType::VERTICAL, X_BASE, DURATION_80F_S, 2.0F, easeOutQuint);
paths_.emplace_back(Y1, Y2, PathType::VERTICAL, X_BASE, DURATION_80F_S, 0.0F, easeInQuint);
}
}
@@ -1159,7 +1162,7 @@ void Game::handleEvents() {
}
// Actualiza el marcador
void Game::updateScoreboard(float deltaTime) {
void Game::updateScoreboard(float delta_time) {
for (const auto& player : players_) {
scoreboard_->setScore(player->getScoreBoardPanel(), player->getScore());
scoreboard_->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier());
@@ -1171,7 +1174,7 @@ void Game::updateScoreboard(float deltaTime) {
scoreboard_->setHiScore(hi_score_.score);
scoreboard_->setHiScoreName(hi_score_.name);
scoreboard_->update(deltaTime);
scoreboard_->update(delta_time);
}
// Pone en el marcador el nombre del primer jugador de la tabla
@@ -1207,7 +1210,7 @@ void Game::checkPlayersStatusPlaying() {
// Obtiene un jugador a partir de su "id"
auto Game::getPlayer(Player::Id id) -> std::shared_ptr<Player> {
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto& player) { return player->getId() == id; });
auto it = std::ranges::find_if(players_, [id](const auto& player) { return player->getId() == id; });
if (it != players_.end()) {
return *it;
@@ -1699,7 +1702,7 @@ void Game::stopMusic() const {
}
// Actualiza las variables durante el modo demo
void Game::updateDemo(float deltaTime) {
void Game::updateDemo(float delta_time) {
if (demo_.enabled) {
balloon_manager_->setCreationTimeEnabled(balloon_manager_->getNumBalloons() != 0);
@@ -1708,7 +1711,7 @@ void Game::updateDemo(float deltaTime) {
fade_out_->update();
// Actualiza el contador de tiempo y el índice
demo_.elapsed_s += deltaTime;
demo_.elapsed_s += delta_time;
demo_.index = static_cast<int>(demo_.elapsed_s * 60.0F);
// Activa el fundido antes de acabar con los datos de la demo
@@ -1755,10 +1758,10 @@ void Game::updateRecording(float deltaTime) {
#endif
// Actualiza las variables durante dicho estado
void Game::updateGameStateFadeIn(float deltaTime) {
void Game::updateGameStateFadeIn(float delta_time) {
fade_in_->update();
updateScoreboard(deltaTime);
updateBackground(deltaTime);
updateScoreboard(delta_time);
updateBackground(delta_time);
if (fade_in_->hasEnded()) {
setState(State::ENTERING_PLAYER);
balloon_manager_->createTwoBigBalloons();
@@ -1767,11 +1770,11 @@ void Game::updateGameStateFadeIn(float deltaTime) {
}
// Actualiza las variables durante dicho estado
void Game::updateGameStateEnteringPlayer(float deltaTime) {
balloon_manager_->update(deltaTime);
updatePlayers(deltaTime);
updateScoreboard(deltaTime);
updateBackground(deltaTime);
void Game::updateGameStateEnteringPlayer(float delta_time) {
balloon_manager_->update(delta_time);
updatePlayers(delta_time);
updateScoreboard(delta_time);
updateBackground(delta_time);
for (const auto& player : players_) {
if (player->isPlaying()) {
setState(State::SHOWING_GET_READY_MESSAGE);
@@ -1782,38 +1785,38 @@ void Game::updateGameStateEnteringPlayer(float deltaTime) {
}
// Actualiza las variables durante dicho estado
void Game::updateGameStateShowingGetReadyMessage(float deltaTime) {
updateGameStatePlaying(deltaTime);
void Game::updateGameStateShowingGetReadyMessage(float delta_time) {
updateGameStatePlaying(delta_time);
constexpr float MUSIC_START_S = 1.67F;
static float music_timer = 0.0f;
music_timer += deltaTime;
if (music_timer >= MUSIC_START_S) {
static float music_timer_ = 0.0F;
music_timer_ += delta_time;
if (music_timer_ >= MUSIC_START_S) {
playMusic("playing.ogg");
music_timer = 0.0F;
music_timer_ = 0.0F;
setState(State::PLAYING);
}
}
// Actualiza las variables durante el transcurso normal del juego
void Game::updateGameStatePlaying(float deltaTime) {
void Game::updateGameStatePlaying(float delta_time) {
#ifdef _DEBUG
if (auto_pop_balloons_) {
stage_manager_->addPower(2);
}
#endif
updatePlayers(deltaTime);
updatePlayers(delta_time);
checkPlayersStatusPlaying();
updateScoreboard(deltaTime);
updateBackground(deltaTime);
balloon_manager_->update(deltaTime);
tabe_->update(deltaTime);
bullet_manager_->update(deltaTime);
updateItems(deltaTime);
updateScoreboard(delta_time);
updateBackground(delta_time);
balloon_manager_->update(delta_time);
tabe_->update(delta_time);
bullet_manager_->update(delta_time);
updateItems(delta_time);
updateStage();
updateSmartSprites(deltaTime);
updatePathSprites(deltaTime);
updateTimeStopped(deltaTime);
updateSmartSprites(delta_time);
updatePathSprites(delta_time);
updateTimeStopped(delta_time);
updateHelper();
bullet_manager_->checkCollisions();
updateMenace();
@@ -1916,9 +1919,9 @@ void Game::sortPlayersByZOrder() {
// Procesar jugadores que van al fondo (se dibujan primero)
if (!players_to_put_at_back_.empty()) {
for (auto& player : players_to_put_at_back_) {
auto it = std::find(players_.begin(), players_.end(), player);
auto it = std::ranges::find(players_, player);
if (it != players_.end() && it != players_.begin()) {
std::shared_ptr<Player> dying_player = *it;
const std::shared_ptr<Player>& dying_player = *it;
players_.erase(it);
players_.insert(players_.begin(), dying_player);
}
@@ -1929,9 +1932,9 @@ void Game::sortPlayersByZOrder() {
// Procesar jugadores que van al frente (se dibujan últimos)
if (!players_to_put_at_front_.empty()) {
for (auto& player : players_to_put_at_front_) {
auto it = std::find(players_.begin(), players_.end(), player);
auto it = std::ranges::find(players_, player);
if (it != players_.end() && it != players_.end() - 1) {
std::shared_ptr<Player> front_player = *it;
const std::shared_ptr<Player>& front_player = *it;
players_.erase(it);
players_.push_back(front_player);
}
@@ -1957,8 +1960,8 @@ void Game::onPauseStateChanged(bool is_paused) {
// Maneja eventos del juego completado usando flags para triggers únicos
void Game::handleGameCompletedEvents() {
constexpr float START_CELEBRATIONS_S = 6.0f;
constexpr float END_CELEBRATIONS_S = 14.0f;
constexpr float START_CELEBRATIONS_S = 6.0F;
constexpr float END_CELEBRATIONS_S = 14.0F;
// Inicio de celebraciones
if (!game_completed_flags_.start_celebrations_triggered && game_completed_timer_ >= START_CELEBRATIONS_S) {
@@ -1992,8 +1995,8 @@ void Game::handleGameCompletedEvents() {
// Maneja eventos discretos basados en tiempo durante el estado game over
void Game::handleGameOverEvents() {
constexpr float MESSAGE_TRIGGER_S = 1.5f;
constexpr float FADE_TRIGGER_S = GAME_OVER_DURATION_S - 2.5f;
constexpr float MESSAGE_TRIGGER_S = 1.5F;
constexpr float FADE_TRIGGER_S = GAME_OVER_DURATION_S - 2.5F;
// Trigger inicial: fade out de música y sonidos de globos
if (!game_over_flags_.music_fade_triggered) {

View File

@@ -1,23 +1,18 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_Renderer, SDL_Texture, Uint64, Uint8
#include <SDL3/SDL.h> // Para SDL_Event, SDL_Renderer, SDL_Texture, Uint64
#include <memory> // Para shared_ptr, unique_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "bullet.hpp" // Para Bullet
#include "bullet_manager.hpp" // Para BulletManager
#include "demo.hpp" // Para Demo
#include "hit.hpp" // Para Hit
#include "item.hpp" // Para Item, ItemType
#include "manage_hiscore_table.hpp" // Para HiScoreEntry
#include "options.hpp" // Para Settings, settings
#include "path_sprite.hpp" // Para PathSprite, Path
#include "player.hpp" // Para Player
#include "smart_sprite.hpp" // Para SmartSprite
#include "stage.hpp" // Para StageManager
#include "utils.hpp" // Para otras utilidades
#include "bullet.hpp" // for Bullet
#include "demo.hpp" // for Demo
#include "hit.hpp" // for Hit
#include "item.hpp" // for Item (ptr only), ItemType
#include "manage_hiscore_table.hpp" // for HiScoreEntry
#include "options.hpp" // for Settings, settings
#include "player.hpp" // for Player
class Background;
class Balloon;
@@ -25,11 +20,15 @@ class BalloonManager;
class BulletManager;
class Fade;
class Input;
class PathSprite;
class PauseManager;
class Scoreboard;
class Screen;
class SmartSprite;
class StageManager;
class Tabe;
class Texture;
struct Path;
namespace Difficulty {
enum class Code;
@@ -76,12 +75,12 @@ class Game {
};
// --- Constantes de tiempo (en segundos) ---
static constexpr float HELP_COUNTER_S = 16.667f; // Contador de ayuda (1000 frames a 60fps → segundos)
static constexpr float GAME_COMPLETED_START_FADE_S = 8.333f; // Inicio del fade al completar (500 frames → segundos)
static constexpr float GAME_COMPLETED_END_S = 11.667f; // Fin del juego completado (700 frames → segundos)
static constexpr float GAME_OVER_DURATION_S = 8.5f;
static constexpr float TIME_STOPPED_DURATION_S = 6.0f;
static constexpr float DEMO_FADE_PRE_DURATION_S = 0.5f;
static constexpr float HELP_COUNTER_S = 16.667F; // Contador de ayuda (1000 frames a 60fps → segundos)
static constexpr float GAME_COMPLETED_START_FADE_S = 8.333F; // Inicio del fade al completar (500 frames → segundos)
static constexpr float GAME_COMPLETED_END_S = 11.667F; // Fin del juego completado (700 frames → segundos)
static constexpr float GAME_OVER_DURATION_S = 8.5F;
static constexpr float TIME_STOPPED_DURATION_S = 6.0F;
static constexpr float DEMO_FADE_PRE_DURATION_S = 0.5F;
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;
@@ -155,11 +154,11 @@ class Game {
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime
bool coffee_machine_enabled_ = false; // Indica si hay una máquina de café en el terreno de juego
bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
float difficulty_score_multiplier_ = 1.0f; // Multiplicador de puntos en función de la dificultad
float counter_ = 0.0f; // Contador para el juego
float game_completed_timer_ = 0.0f; // Acumulador de tiempo para el tramo final (milisegundos)
float game_over_timer_ = 0.0f; // Timer para el estado de fin de partida (milisegundos)
float time_stopped_timer_ = 0.0f; // Temporizador para llevar la cuenta del tiempo detenido
float difficulty_score_multiplier_ = 1.0F; // Multiplicador de puntos en función de la dificultad
float counter_ = 0.0F; // Contador para el juego
float game_completed_timer_ = 0.0F; // Acumulador de tiempo para el tramo final (milisegundos)
float game_over_timer_ = 0.0F; // Timer para el estado de fin de partida (milisegundos)
float time_stopped_timer_ = 0.0F; // Temporizador para llevar la cuenta del tiempo detenido
int menace_ = 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
State state_ = State::FADE_IN; // Estado
@@ -205,7 +204,7 @@ class Game {
#endif
// --- Ciclo principal del juego ---
void update(float deltaTime); // Actualiza la lógica principal del juego
void update(float delta_time); // Actualiza la lógica principal del juego
auto calculateDeltaTime() -> float; // Calcula el deltatime
void render(); // Renderiza todos los elementos del juego
void handleEvents(); // Procesa los eventos del sistema en cola
@@ -214,17 +213,17 @@ class Game {
void cleanVectors(); // Limpia vectores de elementos deshabilitados
// --- Gestión de estados del juego ---
void updateGameStates(float deltaTime); // Actualiza todos los estados del juego
void updateGameStateFadeIn(float deltaTime); // Gestiona el estado de transición de entrada (time-based)
void updateGameStateEnteringPlayer(float deltaTime); // Gestiona el estado de entrada de jugador
void updateGameStateShowingGetReadyMessage(float deltaTime); // Gestiona el estado de mensaje "preparado"
void updateGameStatePlaying(float deltaTime); // Gestiona el estado de juego activo
void updateGameStateCompleted(float deltaTime); // Gestiona el estado de juego completado
void updateGameStateGameOver(float deltaTime); // Gestiona las actualizaciones continuas del estado de fin de partida
void updateGameStates(float delta_time); // Actualiza todos los estados del juego
void updateGameStateFadeIn(float delta_time); // Gestiona el estado de transición de entrada (time-based)
void updateGameStateEnteringPlayer(float delta_time); // Gestiona el estado de entrada de jugador
void updateGameStateShowingGetReadyMessage(float delta_time); // Gestiona el estado de mensaje "preparado"
void updateGameStatePlaying(float delta_time); // Gestiona el estado de juego activo
void updateGameStateCompleted(float delta_time); // Gestiona el estado de juego completado
void updateGameStateGameOver(float delta_time); // Gestiona las actualizaciones continuas del estado de fin de partida
// --- Gestión de jugadores ---
void initPlayers(Player::Id player_id); // Inicializa los datos de los jugadores
void updatePlayers(float deltaTime); // Actualiza las variables y estados de los jugadores
void updatePlayers(float delta_time); // Actualiza las variables y estados de los jugadores
void renderPlayers(); // Renderiza todos los jugadores en pantalla
void sortPlayersByZOrder(); // Reorganiza el orden de dibujado de jugadores
auto getPlayer(Player::Id id) -> std::shared_ptr<Player>; // Obtiene un jugador por su identificador
@@ -269,7 +268,7 @@ class Game {
void processBalloonHit(const std::shared_ptr<Bullet>& bullet, const std::shared_ptr<Balloon>& balloon); // Procesa impacto en globo
// --- Sistema de ítems y power-ups ---
void updateItems(float deltaTime); // Actualiza posición y estado de todos los ítems
void updateItems(float delta_time); // Actualiza posición y estado de todos los ítems
void renderItems(); // Renderiza todos los ítems activos
auto dropItem() -> ItemType; // Determina aleatoriamente qué ítem soltar
void createItem(ItemType type, float x, float y); // Crea un nuevo ítem en posición específica
@@ -277,35 +276,35 @@ class Game {
void destroyAllItems(); // Elimina todos los ítems activos de la pantalla
// --- ítems especiales ---
void enableTimeStopItem(); // Activa el efecto de detener el tiempo
void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo
void updateTimeStopped(float deltaTime); // Actualiza el estado del tiempo detenido
void handleGameCompletedEvents(); // Maneja eventos del juego completado
void handleGameOverEvents(); // Maneja eventos discretos basados en tiempo durante game over
void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
void enableTimeStopItem(); // Activa el efecto de detener el tiempo
void disableTimeStopItem(); // Desactiva el efecto de detener el tiempo
void updateTimeStopped(float delta_time); // Actualiza el estado del tiempo detenido
void handleGameCompletedEvents(); // Maneja eventos del juego completado
void handleGameOverEvents(); // Maneja eventos discretos basados en tiempo durante game over
void throwCoffee(int x, int y); // Crea efecto de café arrojado al ser golpeado
// --- Gestión de caída de ítems ---
void handleItemDrop(const std::shared_ptr<Balloon>& balloon, const std::shared_ptr<Player>& player); // Gestiona caída de ítem desde globo
// --- Sprites inteligentes (smartsprites) ---
void updateSmartSprites(float deltaTime); // Actualiza todos los sprites con lógica propia (time-based)
void renderSmartSprites(); // Renderiza todos los sprites inteligentes
void freeSmartSprites(); // Libera memoria de sprites inteligentes
void updateSmartSprites(float delta_time); // Actualiza todos los sprites con lógica propia (time-based)
void renderSmartSprites(); // Renderiza todos los sprites inteligentes
void freeSmartSprites(); // Libera memoria de sprites inteligentes
// --- Sprites por ruta (pathsprites) ---
void updatePathSprites(float deltaTime); // Actualiza sprites que siguen rutas predefinidas
void renderPathSprites(); // Renderiza sprites animados por ruta
void freePathSprites(); // Libera memoria de sprites por ruta
void initPaths(); // Inicializa rutas predefinidas para animaciones
void updatePathSprites(float delta_time); // Actualiza sprites que siguen rutas predefinidas
void renderPathSprites(); // Renderiza sprites animados por ruta
void freePathSprites(); // Libera memoria de sprites por ruta
void initPaths(); // Inicializa rutas predefinidas para animaciones
// --- Creación de sprites especiales ---
void createItemText(int x, const std::shared_ptr<Texture>& texture); // Crea texto animado para ítems
void createMessage(const std::vector<Path>& paths, const std::shared_ptr<Texture>& texture); // Crea mensaje con animación por ruta
// --- Sistema de globos y enemigos ---
void handleBalloonDestruction(std::shared_ptr<Balloon> balloon, const std::shared_ptr<Player>& player); // Procesa destrucción de globo
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso
void handleBalloonDestruction(const std::shared_ptr<Balloon>& balloon, const std::shared_ptr<Player>& player); // Procesa destrucción de globo
void handleTabeHitEffects(); // Gestiona efectos al golpear a Tabe
void checkAndUpdateBalloonSpeed(); // Ajusta velocidad de globos según progreso
// --- Gestión de fases y progresión ---
void updateStage(); // Verifica y actualiza cambio de fase
@@ -316,20 +315,20 @@ class Game {
void setMenace(); // Calcula y establece amenaza según globos activos
// --- Puntuación y marcador ---
void updateHiScore(); // Actualiza el récord máximo si es necesario
void updateScoreboard(float deltaTime); // Actualiza la visualización del marcador
void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla
void initScoreboard(); // Inicializa el sistema de puntuación
void updateHiScore(); // Actualiza el récord máximo si es necesario
void updateScoreboard(float delta_time); // Actualiza la visualización del marcador
void updateHiScoreName(); // Pone en el marcador el nombre del primer jugador de la tabla
void initScoreboard(); // Inicializa el sistema de puntuación
// --- Modo demostración ---
void initDemo(Player::Id player_id); // Inicializa variables para el modo demostración
void updateDemo(float deltaTime); // Actualiza lógica específica del modo demo
void updateDemo(float delta_time); // Actualiza lógica específica del modo demo
// --- Recursos y renderizado ---
void setResources(); // Asigna texturas y animaciones a los objetos
void updateBackground(float deltaTime); // Actualiza elementos del fondo (time-based)
void fillCanvas(); // Renderiza elementos del área de juego en su textura
void updateHelper(); // Actualiza variables auxiliares de renderizado
void setResources(); // Asigna texturas y animaciones a los objetos
void updateBackground(float delta_time); // Actualiza elementos del fondo (time-based)
void fillCanvas(); // Renderiza elementos del área de juego en su textura
void updateHelper(); // Actualiza variables auxiliares de renderizado
// --- Sistema de audio ---
static void playMusic(const std::string& music_file, int loop = -1); // Reproduce la música de fondo

View File

@@ -33,7 +33,7 @@ HiScoreTable::HiScoreTable()
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
fade_(std::make_unique<Fade>()),
background_(std::make_unique<Background>()),
last_time_(0),
view_area_(SDL_FRect{0, 0, param.game.width, param.game.height}),
fade_mode_(Fade::Mode::IN),
background_fade_color_(Color(0, 0, 0)) {
@@ -75,7 +75,7 @@ void HiScoreTable::render() {
SCREEN->clean(); // Limpia la pantalla
background_->render(); // Pinta el fondo
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir tiempo a equivalente frame para UI
float counter_equivalent = elapsed_time_ * 60.0F; // Convertir tiempo a equivalente frame para UI
view_area_.y = std::max(0.0F, param.game.height - counter_equivalent + 100); // Establece la ventana del backbuffer
SDL_RenderTexture(renderer_, backbuffer_, nullptr, &view_area_); // Copia el backbuffer al renderizador
fade_->render(); // Renderiza el fade
@@ -118,11 +118,11 @@ void HiScoreTable::checkInput() {
}
// Calcula el tiempo transcurrido desde el último frame
float HiScoreTable::calculateDeltaTime() {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
last_time_ = current_time;
return delta_time;
auto HiScoreTable::calculateDeltaTime() -> float {
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convertir ms a segundos
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Bucle para la pantalla de instrucciones
@@ -131,10 +131,10 @@ void HiScoreTable::run() {
Audio::get()->playMusic("title.ogg");
while (Section::name == Section::Name::HI_SCORE_TABLE) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}
@@ -262,12 +262,12 @@ void HiScoreTable::createSprites() {
// Actualiza las posiciones de los sprites de texto
void HiScoreTable::updateSprites(float delta_time) {
if (elapsed_time_ >= INIT_DELAY_S) {
const float elapsed_since_init = elapsed_time_ - INIT_DELAY_S;
int index = static_cast<int>(elapsed_since_init / ENTRY_DELAY_S);
const float ELAPSED_SINCE_INIT = elapsed_time_ - INIT_DELAY_S;
int index = static_cast<int>(ELAPSED_SINCE_INIT / ENTRY_DELAY_S);
if (index < static_cast<int>(entry_names_.size()) && index >= 0) {
// Verificar si este índice debe activarse ahora
float expected_time = index * ENTRY_DELAY_S;
if (elapsed_since_init >= expected_time && elapsed_since_init < expected_time + delta_time) {
if (ELAPSED_SINCE_INIT >= expected_time && ELAPSED_SINCE_INIT < expected_time + delta_time) {
entry_names_.at(index)->enable();
}
}
@@ -357,7 +357,7 @@ void HiScoreTable::iniEntryColors() {
// Hace brillar los nombres de la tabla de records
void HiScoreTable::glowEntryNames() {
int color_counter = static_cast<int>(elapsed_time_ * 60.0f / 5.0f); // Convertir tiempo a equivalente frame
int color_counter = static_cast<int>(elapsed_time_ * 60.0F / 5.0F); // Convertir tiempo a equivalente frame
const Color ENTRY_COLOR = getEntryColor(color_counter);
for (const auto& entry_index : Options::settings.glowing_entries) {
if (entry_index != -1) {

View File

@@ -1,17 +1,18 @@
#pragma once
#include <SDL3/SDL.h> // Para Uint16, SDL_FRect, SDL_Renderer, SDL_Texture, Uint64, Uint8
#include <SDL3/SDL.h> // Para SDL_FRect, SDL_Renderer, SDL_Texture, Uint64
#include <memory> // Para unique_ptr, shared_ptr
#include <string> // Para string
#include <vector> // Para vector
#include "color.hpp" // Para Color
#include "fade.hpp" // Para Fade
#include "path_sprite.hpp" // Para Path, PathSprite (ptr only)
#include "color.hpp" // for Color
#include "fade.hpp" // for Fade
class Background;
class PathSprite;
class Sprite;
struct Path;
// --- Clase HiScoreTable: muestra la tabla de puntuaciones más altas ---
// Esta clase gestiona un estado del programa. Se encarga de mostrar la tabla con las puntuaciones
@@ -31,12 +32,12 @@ class HiScoreTable {
private:
// --- Constantes (en segundos) ---
static constexpr float COUNTER_END_S = 800.0f / 60.0f; // Tiempo final (≈13.33s)
static constexpr float INIT_DELAY_S = 190.0f / 60.0f; // Retraso inicial (≈3.17s)
static constexpr float ENTRY_DELAY_S = 16.0f / 60.0f; // Retraso entre entradas (≈0.27s)
static constexpr float BACKGROUND_CHANGE_S = 150.0f / 60.0f; // Tiempo cambio fondo (≈2.5s)
static constexpr float ANIM_DURATION_S = 80.0f / 60.0f; // Duración animación (≈1.33s)
static constexpr float CLOUDS_SPEED = -6.0f; // Velocidad nubes (pixels/s)
static constexpr float COUNTER_END_S = 800.0F / 60.0F; // Tiempo final (≈13.33s)
static constexpr float INIT_DELAY_S = 190.0F / 60.0F; // Retraso inicial (≈3.17s)
static constexpr float ENTRY_DELAY_S = 16.0F / 60.0F; // Retraso entre entradas (≈0.27s)
static constexpr float BACKGROUND_CHANGE_S = 150.0F / 60.0F; // Tiempo cambio fondo (≈2.5s)
static constexpr float ANIM_DURATION_S = 80.0F / 60.0F; // Duración animación (≈1.33s)
static constexpr float CLOUDS_SPEED = -6.0F; // Velocidad nubes (pixels/s)
// --- Objetos y punteros ---
SDL_Renderer* renderer_; // El renderizador de la ventana
@@ -49,7 +50,7 @@ class HiScoreTable {
std::vector<Path> paths_; // Vector con los recorridos precalculados
// --- Variables ---
float elapsed_time_ = 0.0f; // Tiempo transcurrido (segundos)
float elapsed_time_ = 0.0F; // Tiempo transcurrido (segundos)
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
SDL_FRect view_area_; // Parte de la textura que se muestra en pantalla
Fade::Mode fade_mode_; // Modo de fade a utilizar
@@ -83,5 +84,5 @@ class HiScoreTable {
void iniEntryColors(); // Inicializa los colores de las entradas
void glowEntryNames(); // Hace brillar los nombres de la tabla de records
void updateCounter(); // Gestiona el contador
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
};

View File

@@ -90,19 +90,19 @@ void Instructions::updateSprites() {
SDL_FRect src_rect = {0, 0, Item::WIDTH, Item::HEIGHT};
// Disquito (desplazamiento 12/60 = 0.2s)
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.2f) / SPRITE_ANIMATION_CYCLE_S) % 2);
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.2F) / SPRITE_ANIMATION_CYCLE_S) % 2);
sprites_[0]->setSpriteClip(src_rect);
// Gavina (desplazamiento 9/60 = 0.15s)
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.15f) / SPRITE_ANIMATION_CYCLE_S) % 2);
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.15F) / SPRITE_ANIMATION_CYCLE_S) % 2);
sprites_[1]->setSpriteClip(src_rect);
// Pacmar (desplazamiento 6/60 = 0.1s)
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.1f) / SPRITE_ANIMATION_CYCLE_S) % 2);
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.1F) / SPRITE_ANIMATION_CYCLE_S) % 2);
sprites_[2]->setSpriteClip(src_rect);
// Time Stopper (desplazamiento 3/60 = 0.05s)
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.05f) / SPRITE_ANIMATION_CYCLE_S) % 2);
src_rect.y = Item::HEIGHT * (static_cast<int>((elapsed_time_ + 0.05F) / SPRITE_ANIMATION_CYCLE_S) % 2);
sprites_[3]->setSpriteClip(src_rect);
// Coffee (sin desplazamiento)
@@ -255,11 +255,11 @@ void Instructions::checkInput() {
}
// Calcula el tiempo transcurrido desde el último frame
float Instructions::calculateDeltaTime() {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
last_time_ = current_time;
return delta_time;
auto Instructions::calculateDeltaTime() -> float {
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convertir ms a segundos
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Bucle para la pantalla de instrucciones
@@ -268,10 +268,10 @@ void Instructions::run() {
Audio::get()->playMusic("title.ogg");
while (Section::name == Section::Name::INSTRUCTIONS) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}
@@ -328,7 +328,7 @@ void Instructions::renderLines(SDL_Renderer* renderer, SDL_Texture* texture, con
// Gestiona la textura con los graficos
void Instructions::updateBackbuffer(float delta_time) {
// Establece la ventana del backbuffer (convertir elapsed_time_ a equivalente de counter)
float counter_equivalent = elapsed_time_ * 60.0f; // Convertir segundos a equivalente frame para UI
float counter_equivalent = elapsed_time_ * 60.0F; // Convertir segundos a equivalente frame para UI
view_.y = std::max(0.0F, param.game.height - counter_equivalent + 100);
// Verifica si view_.y == 0 y gestiona el temporizador
@@ -336,7 +336,7 @@ void Instructions::updateBackbuffer(float delta_time) {
if (!start_delay_triggered_) {
// Activa el temporizador si no ha sido activado
start_delay_triggered_ = true;
start_delay_timer_ = 0.0f;
start_delay_timer_ = 0.0F;
} else {
start_delay_timer_ += delta_time;
if (start_delay_timer_ >= START_DELAY_S) {

View File

@@ -1,13 +1,12 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_Texture, Uint32, SDL_Renderer, SDL_FPoint, SDL_FRect, Uint64
#include <SDL3/SDL.h> // Para SDL_Texture, SDL_Renderer, Uint32, SDL_FPoint, SDL_FRect, Uint64
#include <memory> // Para unique_ptr, shared_ptr
#include <vector> // Para vector
#include "sprite.hpp" // Para Sprite
class Fade;
class Sprite;
class Text;
class Texture;
class TiledBG;
@@ -51,10 +50,10 @@ class Instructions {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float SPRITE_ANIMATION_CYCLE_S = 36.0f / 60.0f; // Ciclo de animación sprites (≈0.6s)
static constexpr float START_DELAY_S = 4.0f; // Retraso antes de mover líneas (4s)
static constexpr float LINE_MOVE_DURATION_S = 1.0f; // Duración movimiento líneas (1s)
static constexpr float LINE_START_DELAY_MS = 5.0f; // Retraso entre líneas (5ms)
static constexpr float SPRITE_ANIMATION_CYCLE_S = 36.0F / 60.0F; // Ciclo de animación sprites (≈0.6s)
static constexpr float START_DELAY_S = 4.0F; // Retraso antes de mover líneas (4s)
static constexpr float LINE_MOVE_DURATION_S = 1.0F; // Duración movimiento líneas (1s)
static constexpr float LINE_START_DELAY_MS = 5.0F; // Retraso entre líneas (5ms)
// --- Objetos y punteros ---
SDL_Renderer* renderer_; // El renderizador de la ventana
@@ -68,14 +67,14 @@ class Instructions {
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
// --- Variables ---
float elapsed_time_ = 0.0f; // Tiempo transcurrido (segundos)
float elapsed_time_ = 0.0F; // Tiempo transcurrido (segundos)
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
SDL_FRect view_; // Vista del backbuffer que se va a mostrar por pantalla
SDL_FPoint sprite_pos_ = {0, 0}; // Posición del primer sprite en la lista
float item_space_ = 2.0; // Espacio entre los items en pantalla
std::vector<Line> lines_; // Vector que contiene las líneas animadas en la pantalla
bool all_lines_off_screen_ = false; // Indica si todas las líneas han salido de la pantalla
float start_delay_timer_ = 0.0f; // Timer para retraso antes de mover líneas (segundos)
float start_delay_timer_ = 0.0F; // Timer para retraso antes de mover líneas (segundos)
bool start_delay_triggered_ = false; // Bandera para determinar si el retraso ha comenzado
// --- Métodos internos ---
@@ -91,5 +90,5 @@ class Instructions {
static auto moveLines(std::vector<Line>& lines, int width, float duration, Uint32 start_delay) -> bool; // Mueve las líneas (ya usa tiempo real)
static void renderLines(SDL_Renderer* renderer, SDL_Texture* texture, const std::vector<Line>& lines); // Renderiza las líneas
void updateBackbuffer(float delta_time); // Gestiona la textura con los gráficos
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
};

View File

@@ -1,8 +1,7 @@
#include "intro.hpp"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderDrawColor, SDL_FRect, SDL_RenderFillRect, SDL_GetRenderTarget, SDL_RenderClear, SDL_RenderRect, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_PollEvent, SDL_RenderTexture, SDL_TextureAccess, SDL_Event, Uint32
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_SetRenderDrawColor, SDL_FRect, SDL_RenderFillRect, SDL_GetRenderTarget, SDL_RenderClear, SDL_RenderRect, SDL_SetRenderTarget, SDL_BLENDMODE_BLEND, SDL_PixelFormat, SDL_PollEvent, SDL_RenderTexture, SDL_TextureAccess, SDL_Event, Uint64
#include <algorithm> // Para max
#include <array> // Para array
#include <functional> // Para function
#include <string> // Para basic_string, string
@@ -10,7 +9,7 @@
#include "audio.hpp" // Para Audio
#include "color.hpp" // Para Color
#include "global_events.hpp" // Para check
#include "global_events.hpp" // Para handle
#include "global_inputs.hpp" // Para check
#include "input.hpp" // Para Input
#include "lang.hpp" // Para getText
@@ -191,7 +190,7 @@ void Intro::updateScene5() {
// Acaba la ultima imagen
if (card_sprites_.at(5)->hasFinished() && texts_.at(8)->hasFinished()) {
state_ = State::POST;
state_start_time_ = SDL_GetTicks() / 1000.0f;
state_start_time_ = SDL_GetTicks() / 1000.0F;
}
}
@@ -251,11 +250,11 @@ void Intro::render() {
}
// Calcula el tiempo transcurrido desde el último frame
float Intro::calculateDeltaTime() {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
last_time_ = current_time;
return delta_time;
auto Intro::calculateDeltaTime() -> float {
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convertir ms a segundos
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Bucle principal
@@ -264,10 +263,10 @@ void Intro::run() {
Audio::get()->playMusic("intro.ogg", 0);
while (Section::name == Section::Name::INTRO) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}
@@ -338,13 +337,13 @@ void Intro::initSprites() {
const float X_DEST = param.game.game_area.center_x - (CARD_WIDTH / 2);
const float Y_DEST = param.game.game_area.first_quarter_y - (CARD_HEIGHT / 4);
card_sprites_.at(0)->addPath(-CARD_WIDTH - CARD_OFFSET_MARGIN, X_DEST, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_NORMAL, easeInOutExpo, 0.0f);
card_sprites_.at(1)->addPath(param.game.width, X_DEST, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_NORMAL, easeOutBounce, 0.0f);
card_sprites_.at(2)->addPath(-CARD_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_FAST, easeOutQuint, 0.0f);
card_sprites_.at(3)->addPath(param.game.height, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_VERY_SLOW, easeInOutExpo, 0.0f);
card_sprites_.at(4)->addPath(-CARD_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_MEDIUM, easeOutElastic, 0.0f);
card_sprites_.at(0)->addPath(-CARD_WIDTH - CARD_OFFSET_MARGIN, X_DEST, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_NORMAL, easeInOutExpo, 0.0F);
card_sprites_.at(1)->addPath(param.game.width, X_DEST, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_NORMAL, easeOutBounce, 0.0F);
card_sprites_.at(2)->addPath(-CARD_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_FAST, easeOutQuint, 0.0F);
card_sprites_.at(3)->addPath(param.game.height, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_VERY_SLOW, easeInOutExpo, 0.0F);
card_sprites_.at(4)->addPath(-CARD_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_MEDIUM, easeOutElastic, 0.0F);
card_sprites_.at(5)->addPath(-CARD_HEIGHT, Y_DEST, PathType::VERTICAL, X_DEST, CARD_ANIM_DURATION_SLOW, easeOutQuad, CARD_ANIM_DELAY_LONG_S);
card_sprites_.at(5)->addPath(X_DEST, -CARD_WIDTH, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_SHORT, easeInElastic, 0.0f);
card_sprites_.at(5)->addPath(X_DEST, -CARD_WIDTH, PathType::HORIZONTAL, Y_DEST, CARD_ANIM_DURATION_SHORT, easeInElastic, 0.0F);
// Constantes
const float DESP = SHADOW_OFFSET;
@@ -389,13 +388,13 @@ void Intro::initSprites() {
const float S_X_DEST = X_DEST + DESP;
const float S_Y_DEST = Y_DEST + DESP;
shadow_sprites_.at(0)->addPath(param.game.height + CARD_OFFSET_MARGIN, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_NORMAL, easeInOutExpo, 0.0f);
shadow_sprites_.at(1)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_NORMAL, easeOutBounce, 0.0f);
shadow_sprites_.at(2)->addPath(-SHADOW_SPRITE_WIDTH, S_X_DEST, PathType::HORIZONTAL, S_Y_DEST, CARD_ANIM_DURATION_FAST, easeOutQuint, 0.0f);
shadow_sprites_.at(3)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_VERY_SLOW, easeInOutExpo, 0.0f);
shadow_sprites_.at(4)->addPath(param.game.height, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_MEDIUM, easeOutElastic, 0.0f);
shadow_sprites_.at(0)->addPath(param.game.height + CARD_OFFSET_MARGIN, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_NORMAL, easeInOutExpo, 0.0F);
shadow_sprites_.at(1)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_NORMAL, easeOutBounce, 0.0F);
shadow_sprites_.at(2)->addPath(-SHADOW_SPRITE_WIDTH, S_X_DEST, PathType::HORIZONTAL, S_Y_DEST, CARD_ANIM_DURATION_FAST, easeOutQuint, 0.0F);
shadow_sprites_.at(3)->addPath(-SHADOW_SPRITE_HEIGHT, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_VERY_SLOW, easeInOutExpo, 0.0F);
shadow_sprites_.at(4)->addPath(param.game.height, S_Y_DEST, PathType::VERTICAL, S_X_DEST, CARD_ANIM_DURATION_MEDIUM, easeOutElastic, 0.0F);
shadow_sprites_.at(5)->addPath(param.game.width, S_X_DEST, PathType::HORIZONTAL, S_Y_DEST, CARD_ANIM_DURATION_SLOW, easeOutQuad, CARD_ANIM_DELAY_LONG_S);
shadow_sprites_.at(5)->addPath(S_X_DEST, param.game.width, PathType::HORIZONTAL, S_Y_DEST, CARD_ANIM_DURATION_SHORT, easeInElastic, 0.0f);
shadow_sprites_.at(5)->addPath(S_X_DEST, param.game.width, PathType::HORIZONTAL, S_Y_DEST, CARD_ANIM_DURATION_SHORT, easeInElastic, 0.0F);
}
// Inicializa los textos
@@ -485,7 +484,7 @@ void Intro::renderTexts() {
// Actualiza el estado POST
void Intro::updatePostState() {
const float ELAPSED_TIME = (SDL_GetTicks() / 1000.0f) - state_start_time_;
const float ELAPSED_TIME = (SDL_GetTicks() / 1000.0F) - state_start_time_;
switch (post_state_) {
case PostState::STOP_BG:
@@ -503,7 +502,7 @@ void Intro::updatePostState() {
// Cambia de estado si el fondo se ha detenido y recuperado el color
if (tiled_bg_->isStopped() && bg_color_.IS_EQUAL_TO(param.title.bg_color)) {
post_state_ = PostState::END;
state_start_time_ = SDL_GetTicks() / 1000.0f;
state_start_time_ = SDL_GetTicks() / 1000.0F;
}
break;

View File

@@ -38,32 +38,32 @@ class Intro {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float TEXT_DISPLAY_DURATION_S = 3.0f; // Duración de visualización de texto (180 frames a 60fps)
static constexpr float POST_BG_STOP_DELAY_S = 1.0f; // Retraso antes de detener el fondo
static constexpr float POST_END_DELAY_S = 1.0f; // Retraso antes de finalizar intro
static constexpr float TEXT_DISPLAY_DURATION_S = 3.0F; // Duración de visualización de texto (180 frames a 60fps)
static constexpr float POST_BG_STOP_DELAY_S = 1.0F; // Retraso antes de detener el fondo
static constexpr float POST_END_DELAY_S = 1.0F; // Retraso antes de finalizar intro
// --- Constantes de layout ---
static constexpr float CARD_BORDER_SIZE = 2.0f; // Tamaño del borde de tarjetas
static constexpr float SHADOW_OFFSET = 8.0f; // Desplazamiento de sombra
static constexpr float TILED_BG_SPEED = 18.0f; // Velocidad del fondo mosaico (pixels/segundo)
static constexpr float CARD_BORDER_SIZE = 2.0F; // Tamaño del borde de tarjetas
static constexpr float SHADOW_OFFSET = 8.0F; // Desplazamiento de sombra
static constexpr float TILED_BG_SPEED = 18.0F; // Velocidad del fondo mosaico (pixels/segundo)
static constexpr int TEXT_KERNING = -2; // Espaciado entre caracteres
// --- Constantes de velocidades de texto (segundos entre caracteres) ---
static constexpr float TEXT_SPEED_NORMAL = 0.133f; // Velocidad normal (8 frames * 16.67ms = 133ms)
static constexpr float TEXT_SPEED_FAST = 0.2f; // Velocidad rápida (12 frames * 16.67ms = 200ms)
static constexpr float TEXT_SPEED_VERY_SLOW = 0.0167f; // Velocidad muy lenta (1 frame * 16.67ms = 16.7ms)
static constexpr float TEXT_SPEED_VERY_FAST = 0.267f; // Velocidad muy rápida (16 frames * 16.67ms = 267ms)
static constexpr float TEXT_SPEED_SLOW = 0.033f; // Velocidad lenta (2 frames * 16.67ms = 33ms)
static constexpr float TEXT_SPEED_MEDIUM_SLOW = 0.05f; // Velocidad medio-lenta (3 frames * 16.67ms = 50ms)
static constexpr float TEXT_SPEED_ULTRA_FAST = 0.333f; // Velocidad ultra rápida (20 frames * 16.67ms = 333ms)
static constexpr float TEXT_SPEED_NORMAL = 0.133F; // Velocidad normal (8 frames * 16.67ms = 133ms)
static constexpr float TEXT_SPEED_FAST = 0.2F; // Velocidad rápida (12 frames * 16.67ms = 200ms)
static constexpr float TEXT_SPEED_VERY_SLOW = 0.0167F; // Velocidad muy lenta (1 frame * 16.67ms = 16.7ms)
static constexpr float TEXT_SPEED_VERY_FAST = 0.267F; // Velocidad muy rápida (16 frames * 16.67ms = 267ms)
static constexpr float TEXT_SPEED_SLOW = 0.033F; // Velocidad lenta (2 frames * 16.67ms = 33ms)
static constexpr float TEXT_SPEED_MEDIUM_SLOW = 0.05F; // Velocidad medio-lenta (3 frames * 16.67ms = 50ms)
static constexpr float TEXT_SPEED_ULTRA_FAST = 0.333F; // Velocidad ultra rápida (20 frames * 16.67ms = 333ms)
// --- Constantes de animaciones de tarjetas (duraciones en segundos) ---
static constexpr float CARD_ANIM_DURATION_NORMAL = 100.0f / 60.0f; // ≈ 1.6667 s
static constexpr float CARD_ANIM_DURATION_FAST = 40.0f / 60.0f; // ≈ 0.6667 s
static constexpr float CARD_ANIM_DURATION_MEDIUM = 70.0f / 60.0f; // ≈ 1.1667 s
static constexpr float CARD_ANIM_DURATION_SHORT = 80.0f / 60.0f; // ≈ 1.3333 s
static constexpr float CARD_ANIM_DURATION_SLOW = 250.0f / 60.0f; // ≈ 4.1667 s
static constexpr float CARD_ANIM_DURATION_VERY_SLOW = 300.0f / 60.0f; // ≈ 5.0000 s
static constexpr float CARD_ANIM_DURATION_NORMAL = 100.0F / 60.0F; // ≈ 1.6667 s
static constexpr float CARD_ANIM_DURATION_FAST = 40.0F / 60.0F; // ≈ 0.6667 s
static constexpr float CARD_ANIM_DURATION_MEDIUM = 70.0F / 60.0F; // ≈ 1.1667 s
static constexpr float CARD_ANIM_DURATION_SHORT = 80.0F / 60.0F; // ≈ 1.3333 s
static constexpr float CARD_ANIM_DURATION_SLOW = 250.0F / 60.0F; // ≈ 4.1667 s
static constexpr float CARD_ANIM_DURATION_VERY_SLOW = 300.0F / 60.0F; // ≈ 5.0000 s
static constexpr float CARD_ANIM_DELAY_LONG_S = 7.5F; // Retraso largo antes de animación
static constexpr float CARD_OFFSET_MARGIN = 10.0F; // Margen fuera de pantalla
@@ -107,7 +107,7 @@ class Intro {
void renderTexts(); // Dibuja los textos
static void renderTextRect(); // Dibuja el rectangulo de fondo del texto;
void updatePostState(); // Actualiza el estado POST
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
// --- Métodos para manejar cada escena individualmente ---
void updateScene0();

View File

@@ -1,12 +1,14 @@
#include "logo.hpp"
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_PollEvent, SDL_Event, SDL_FRect
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_PollEvent, SDL_Event, SDL_FRect, Uint64
#include <cstddef> // Para size_t
#include <string> // Para basic_string
#include <utility> // Para move
#include "audio.hpp" // Para Audio
#include "color.hpp" // Para Color
#include "global_events.hpp" // Para check
#include "global_events.hpp" // Para handle
#include "global_inputs.hpp" // Para check
#include "input.hpp" // Para Input
#include "param.hpp" // Para Param, ParamGame, param
@@ -118,16 +120,16 @@ void Logo::updateJAILGAMES(float delta_time) {
void Logo::updateTextureColors(float delta_time) {
// Manejo de 'sinceTexture'
for (int i = 0; i <= MAX_SINCE_COLOR_INDEX; ++i) {
const float target_time = SHOW_SINCE_SPRITE_TIME_S + COLOR_CHANGE_INTERVAL_S * i;
if (elapsed_time_s_ >= target_time && elapsed_time_s_ - delta_time < target_time) {
const float TARGET_TIME = SHOW_SINCE_SPRITE_TIME_S + (COLOR_CHANGE_INTERVAL_S * i);
if (elapsed_time_s_ >= TARGET_TIME && elapsed_time_s_ - delta_time < TARGET_TIME) {
since_texture_->setColor(color_[i].r, color_[i].g, color_[i].b);
}
}
// Manejo de 'jailTexture' y 'sinceTexture' en el fade
for (int i = 0; i <= MAX_FADE_COLOR_INDEX; ++i) {
const float target_time = INIT_FADE_TIME_S + COLOR_CHANGE_INTERVAL_S * i;
if (elapsed_time_s_ >= target_time && elapsed_time_s_ - delta_time < target_time) {
const float TARGET_TIME = INIT_FADE_TIME_S + (COLOR_CHANGE_INTERVAL_S * i);
if (elapsed_time_s_ >= TARGET_TIME && elapsed_time_s_ - delta_time < TARGET_TIME) {
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);
}
@@ -160,11 +162,11 @@ void Logo::render() {
}
// Calcula el tiempo transcurrido desde el último frame
float Logo::calculateDeltaTime() {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convertir ms a segundos
last_time_ = current_time;
return delta_time;
auto Logo::calculateDeltaTime() -> float {
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convertir ms a segundos
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Bucle para el logo del juego
@@ -172,10 +174,10 @@ void Logo::run() {
last_time_ = SDL_GetTicks();
while (Section::name == Section::Name::LOGO) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}

View File

@@ -2,12 +2,12 @@
#include <SDL3/SDL.h> // Para SDL_FPoint, Uint64
#include <memory> // Para unique_ptr, shared_ptr
#include <memory> // Para shared_ptr, unique_ptr
#include <vector> // Para vector
#include "color.hpp" // Para Color
#include "sprite.hpp" // Para Sprite
#include "color.hpp" // for Color
class Sprite;
class Texture;
// --- Clase Logo: pantalla de presentación de JAILGAMES con efectos retro ---
@@ -36,13 +36,13 @@ class Logo {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float SOUND_TRIGGER_TIME_S = 0.5f; // Tiempo para activar el sonido del logo
static constexpr float SHOW_SINCE_SPRITE_TIME_S = 1.167f; // Tiempo para mostrar el sprite "SINCE 1998"
static constexpr float INIT_FADE_TIME_S = 5.0f; // Tiempo de inicio del fade a negro
static constexpr float END_LOGO_TIME_S = 6.668f; // Tiempo de finalización del logo
static constexpr float POST_LOGO_DURATION_S = 0.333f; // Duración adicional después del fade
static constexpr float LOGO_SPEED_PX_PER_S = 480.0f; // Velocidad de desplazamiento (píxeles por segundo) - 8.0f/16.67f*1000
static constexpr float COLOR_CHANGE_INTERVAL_S = 0.0667f; // Intervalo entre cambios de color (~4 frames a 60fps)
static constexpr float SOUND_TRIGGER_TIME_S = 0.5F; // Tiempo para activar el sonido del logo
static constexpr float SHOW_SINCE_SPRITE_TIME_S = 1.167F; // Tiempo para mostrar el sprite "SINCE 1998"
static constexpr float INIT_FADE_TIME_S = 5.0F; // Tiempo de inicio del fade a negro
static constexpr float END_LOGO_TIME_S = 6.668F; // Tiempo de finalización del logo
static constexpr float POST_LOGO_DURATION_S = 0.333F; // Duración adicional después del fade
static constexpr float LOGO_SPEED_PX_PER_S = 480.0F; // Velocidad de desplazamiento (píxeles por segundo) - 8.0f/16.67f*1000
static constexpr float COLOR_CHANGE_INTERVAL_S = 0.0667F; // 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"
@@ -73,7 +73,7 @@ class Logo {
// --- Variables ---
std::vector<Color> color_; // Vector con los colores para el fade
float elapsed_time_s_ = 0.0f; // Tiempo transcurrido en segundos
float elapsed_time_s_ = 0.0F; // Tiempo transcurrido en segundos
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
SDL_FPoint dest_; // Posición donde dibujar el logo
bool sound_triggered_ = false; // Indica si el sonido del logo ya se reprodujo
@@ -87,5 +87,5 @@ class Logo {
void renderJAILGAMES(); // Renderiza el logo de JAILGAMES
void updateTextureColors(float delta_time); // Gestiona el color de las texturas
void handleSound(); // Maneja la reproducción del sonido del logo
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
};

View File

@@ -1,16 +1,16 @@
#include "title.hpp"
#include <SDL3/SDL.h> // Para SDL_GetTicks, Uint32, SDL_Event, SDL_PollEvent, SDL_EventType
#include <SDL3/SDL.h> // Para SDL_GetTicks, SDL_Event, SDL_Keycode, SDL_PollEvent, SDLK_A, SDLK_C, SDLK_D, SDLK_F, SDLK_S, SDLK_V, SDLK_X, SDLK_Z, SDL_EventType, Uint64
#include <algorithm> // Para max, find_if
#include <string> // Para operator+, char_traits, to_string, string, basic_string
#include <vector> // Para vector
#include <ranges> // Para __find_if_fn, find_if
#include <string> // Para basic_string, char_traits, operator+, to_string, string
#include <vector> // Para vector
#include "audio.hpp" // Para Audio
#include "color.hpp" // Para Colors::NO_COLOR_MOD, Colors::TITLE_SHADOW_TEXT
#include "fade.hpp" // Para Fade, FadeType
#include "color.hpp" // Para Color, NO_COLOR_MOD, TITLE_SHADOW_TEXT
#include "fade.hpp" // Para Fade
#include "game_logo.hpp" // Para GameLogo
#include "global_events.hpp" // Para check
#include "global_events.hpp" // Para handle
#include "global_inputs.hpp" // Para check
#include "input.hpp" // Para Input
#include "input_types.hpp" // Para InputAction
@@ -31,8 +31,8 @@
class Texture;
#ifdef _DEBUG
#include <iomanip> // Para operator<<, setfill, setw
#include <iostream>
#include <iomanip> // Para operator<<, setfill, setw
#include <iostream> // Para basic_ostream, basic_ostream::operator<<, operator<<, cout, hex
#endif
// Constructor
@@ -84,23 +84,23 @@ Title::~Title() {
}
// Actualiza las variables del objeto
void Title::update(float deltaTime) {
void Title::update(float delta_time) {
static auto* const SCREEN = Screen::get();
SCREEN->update(deltaTime); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
SCREEN->update(delta_time); // Actualiza el objeto screen
Audio::update(); // Actualiza el objeto audio
updateFade();
updateState(deltaTime);
updateStartPrompt(deltaTime);
updatePlayers(deltaTime);
updateState(delta_time);
updateStartPrompt(delta_time);
updatePlayers(delta_time);
}
// Calcula el tiempo transcurrido desde el último frame
float Title::calculateDeltaTime() {
const Uint64 current_time = SDL_GetTicks();
const float delta_time = static_cast<float>(current_time - last_time_) / 1000.0f; // Convert ms to seconds
last_time_ = current_time;
return delta_time;
auto Title::calculateDeltaTime() -> float {
const Uint64 CURRENT_TIME = SDL_GetTicks();
const float DELTA_TIME = static_cast<float>(CURRENT_TIME - last_time_) / 1000.0F; // Convert ms to seconds
last_time_ = CURRENT_TIME;
return DELTA_TIME;
}
// Dibuja el objeto en pantalla
@@ -145,7 +145,7 @@ void Title::handleKeyDownEvent(const SDL_Event& event) {
void Title::handleDebugColorKeys(SDL_Keycode key) {
adjustColorComponent(key, debug_color_);
counter_time_ = 0.0f;
counter_time_ = 0.0F;
tiled_bg_->setColor(debug_color_);
printColorValue(debug_color_);
}
@@ -299,7 +299,7 @@ void Title::processPlayer2Start() {
void Title::activatePlayerAndSetState(Player::Id player_id) {
getPlayer(player_id)->setPlayingState(Player::State::TITLE_ANIMATION);
setState(State::START_HAS_BEEN_PRESSED);
counter_time_ = 0.0f;
counter_time_ = 0.0F;
}
// Bucle para el titulo del juego
@@ -307,17 +307,17 @@ void Title::run() {
last_time_ = SDL_GetTicks();
while (Section::name == Section::Name::TITLE) {
const float delta_time = calculateDeltaTime();
const float DELTA_TIME = calculateDeltaTime();
checkInput();
update(delta_time);
update(DELTA_TIME);
checkEvents(); // Tiene que ir antes del render
render();
}
}
// Reinicia el contador interno
void Title::resetCounter() { counter_time_ = 0.0f; }
void Title::resetCounter() { counter_time_ = 0.0F; }
// Intercambia la asignación de mandos a los jugadores
void Title::swapControllers() {
@@ -379,9 +379,9 @@ void Title::updateFade() {
}
// Actualiza el estado
void Title::updateState(float deltaTime) {
game_logo_->update(deltaTime);
tiled_bg_->update(deltaTime);
void Title::updateState(float delta_time) {
game_logo_->update(delta_time);
tiled_bg_->update(delta_time);
// Establece la lógica según el estado
switch (state_) {
@@ -392,7 +392,7 @@ void Title::updateState(float deltaTime) {
break;
}
case State::LOGO_FINISHED: {
counter_time_ += deltaTime;
counter_time_ += delta_time;
if (counter_time_ >= param.title.title_duration) {
// El menu ha hecho time out
@@ -403,7 +403,7 @@ void Title::updateState(float deltaTime) {
break;
}
case State::START_HAS_BEEN_PRESSED: {
counter_time_ += deltaTime;
counter_time_ += delta_time;
if (counter_time_ >= START_PRESSED_DELAY_S) {
fade_->activate();
@@ -416,12 +416,12 @@ void Title::updateState(float deltaTime) {
}
}
void Title::updateStartPrompt(float deltaTime) {
blink_accumulator_ += deltaTime;
void Title::updateStartPrompt(float delta_time) {
blink_accumulator_ += delta_time;
bool condition_met = false;
float period = 0.0f;
float on_time = 0.0f;
float period = 0.0F;
float on_time = 0.0F;
switch (state_) {
case State::LOGO_FINISHED:
@@ -438,7 +438,7 @@ void Title::updateStartPrompt(float deltaTime) {
break;
}
if (period > 0.0f) {
if (period > 0.0F) {
// Reset accumulator when it exceeds the period
if (blink_accumulator_ >= period) {
blink_accumulator_ -= period;
@@ -494,11 +494,11 @@ void Title::setState(State state) {
case State::LOGO_FINISHED:
Audio::get()->playMusic("title.ogg");
tiled_bg_->changeSpeedTo(60.0F, 0.5F);
blink_accumulator_ = 0.0f; // Resetea el timer para empezar el parpadeo desde el inicio
blink_accumulator_ = 0.0F; // Resetea el timer para empezar el parpadeo desde el inicio
break;
case State::START_HAS_BEEN_PRESSED:
Audio::get()->fadeOutMusic(MUSIC_FADE_OUT_LONG_MS);
blink_accumulator_ = 0.0f; // Resetea el timer para empezar el parpadeo desde el inicio
blink_accumulator_ = 0.0F; // Resetea el timer para empezar el parpadeo desde el inicio
break;
}
}
@@ -568,9 +568,9 @@ void Title::initPlayers() {
}
// Actualiza los jugadores
void Title::updatePlayers(float deltaTime) {
void Title::updatePlayers(float delta_time) {
for (auto& player : players_) {
player->update(deltaTime);
player->update(delta_time);
}
}

View File

@@ -1,13 +1,15 @@
#pragma once
#include <SDL3/SDL.h> // Para SDL_Event, Uint64
#include <SDL3/SDL.h> // Para SDL_Keycode, SDL_Event, Uint64
#include <cstdint> // Para uint8_t
#include <memory> // Para shared_ptr, unique_ptr
#include <string_view> // Para string_view
#include <vector> // Para vector
#include "player.hpp" // Para Player
#include "section.hpp" // Para Options, Name (ptr only)
#include "color.hpp" // for Color
#include "player.hpp" // for Player
#include "section.hpp" // for Options, Name (ptr only)
class Fade;
class GameLogo;
@@ -46,15 +48,15 @@ class Title {
private:
// --- Constantes de tiempo (en segundos) ---
static constexpr float START_PRESSED_DELAY_S = 1666.67f / 1000.0f; // Tiempo antes de fade tras pulsar start (100 frames a 60fps)
static constexpr float START_PRESSED_DELAY_S = 1666.67F / 1000.0F; // Tiempo antes de fade tras pulsar start (100 frames a 60fps)
static constexpr int MUSIC_FADE_OUT_LONG_MS = 1500; // Fade out largo de música
static constexpr int MUSIC_FADE_OUT_SHORT_MS = 300; // Fade out corto de música
// --- Constantes de parpadeo (en segundos) ---
static constexpr float LOGO_BLINK_PERIOD_S = 833.0f / 1000.0f; // Período de parpadeo del logo (833ms)
static constexpr float LOGO_BLINK_ON_TIME_S = 583.0f / 1000.0f; // Tiempo encendido del logo (583ms)
static constexpr float START_BLINK_PERIOD_S = 167.0f / 1000.0f; // Período de parpadeo del start (167ms)
static constexpr float START_BLINK_ON_TIME_S = 83.0f / 1000.0f; // Tiempo encendido del start (83ms)
static constexpr float LOGO_BLINK_PERIOD_S = 833.0F / 1000.0F; // Período de parpadeo del logo (833ms)
static constexpr float LOGO_BLINK_ON_TIME_S = 583.0F / 1000.0F; // Tiempo encendido del logo (583ms)
static constexpr float START_BLINK_PERIOD_S = 167.0F / 1000.0F; // Período de parpadeo del start (167ms)
static constexpr float START_BLINK_ON_TIME_S = 83.0F / 1000.0F; // Tiempo encendido del start (83ms)
// --- Constantes de layout ---
static constexpr int MINI_LOGO_Y_DIVISOR = 5; // Divisor para posición Y del mini logo
@@ -92,8 +94,8 @@ class Title {
Section::Options selection_ = Section::Options::TITLE_TIME_OUT; // Opción elegida en el título
State state_; // Estado actual de la sección
Uint64 last_time_ = 0; // Último timestamp para calcular delta-time
float counter_time_ = 0.0f; // Temporizador para la pantalla de título (en segundos)
float blink_accumulator_ = 0.0f; // Acumulador para el parpadeo (en segundos)
float counter_time_ = 0.0F; // Temporizador para la pantalla de título (en segundos)
float blink_accumulator_ = 0.0F; // Acumulador para el parpadeo (en segundos)
int num_controllers_; // Número de mandos conectados
bool should_render_start_prompt_ = false; // Indica si se muestra el texto de PRESS START BUTTON TO PLAY
bool player1_start_pressed_ = false; // Indica si se ha pulsado el botón de empezar para el jugador 1
@@ -104,11 +106,11 @@ class Title {
#endif
// --- Ciclo de vida del título ---
void update(float deltaTime); // Actualiza las variables del objeto
float calculateDeltaTime(); // Calcula el tiempo transcurrido desde el último frame
void updateState(float deltaTime); // Actualiza el estado actual del título
void setState(State state); // Cambia el estado del título
void resetCounter(); // Reinicia el contador interno
void update(float delta_time); // Actualiza las variables del objeto
auto calculateDeltaTime() -> float; // Calcula el tiempo transcurrido desde el último frame
void updateState(float delta_time); // Actualiza el estado actual del título
void setState(State state); // Cambia el estado del título
void resetCounter(); // Reinicia el contador interno
// --- Entrada de usuario ---
void checkEvents(); // Comprueba los eventos
@@ -125,16 +127,16 @@ class Title {
// --- Gestión de jugadores ---
void initPlayers(); // Inicializa los jugadores
void updatePlayers(float deltaTime); // Actualiza los jugadores
void updatePlayers(float delta_time); // Actualiza los jugadores
void renderPlayers(); // Renderiza los jugadores
auto getPlayer(Player::Id id) -> std::shared_ptr<Player>; // Obtiene un jugador a partir de su "id"
// --- Visualización / Renderizado ---
void render(); // Dibuja el objeto en pantalla
void updateFade(); // Actualiza el efecto de fundido (fade in/out)
void updateStartPrompt(float deltaTime); // Actualiza el mensaje de "Pulsa Start"
void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla
void renderCopyright(); // Dibuja el aviso de copyright
void render(); // Dibuja el objeto en pantalla
void updateFade(); // Actualiza el efecto de fundido (fade in/out)
void updateStartPrompt(float delta_time); // Actualiza el mensaje de "Pulsa Start"
void renderStartPrompt(); // Dibuja el mensaje de "Pulsa Start" en pantalla
void renderCopyright(); // Dibuja el aviso de copyright
// --- Utilidades estáticas ---
static void swapControllers(); // Intercambia la asignación de mandos a los jugadores