magic numbers: game.cpp

This commit is contained in:
2025-09-19 09:11:10 +02:00
parent af7cb01ead
commit 49a3989ecf
3 changed files with 102 additions and 133 deletions

View File

@@ -93,7 +93,9 @@ void MovingSprite::update(float deltaTime) {
} }
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void MovingSprite::render() { getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_); } void MovingSprite::render() {
getTexture()->render(pos_.x, pos_.y, &sprite_clip_, horizontal_zoom_, vertical_zoom_, rotate_.angle, &rotate_.center, flip_);
}
// Establece la rotacion (frame-based) // Establece la rotacion (frame-based)
void MovingSprite::rotate() { void MovingSprite::rotate() {

View File

@@ -210,7 +210,6 @@ void Game::updateHiScore() {
} }
} }
// Actualiza las variables del jugador // Actualiza las variables del jugador
void Game::updatePlayers(float deltaTime) { void Game::updatePlayers(float deltaTime) {
for (auto &player : players_) { for (auto &player : players_) {
@@ -223,7 +222,7 @@ void Game::updatePlayers(float deltaTime) {
// Si hay colisión // Si hay colisión
if (balloon) { if (balloon) {
// Si el globo está parado y el temporizador activo, lo explota // Si el globo está parado y el temporizador activo, lo explota
if (balloon->isStopped() && time_stopped_counter_ > 0) { if (balloon->isStopped() && time_stopped_timer_ > 0) {
balloon_manager_->popBalloon(balloon); balloon_manager_->popBalloon(balloon);
} }
// En caso contrario, el jugador ha sido golpeado por un globo activo // En caso contrario, el jugador ha sido golpeado por un globo activo
@@ -328,17 +327,13 @@ void Game::updateGameStateGameOver(float deltaTime) {
checkBulletCollision(); checkBulletCollision();
cleanVectors(); cleanVectors();
if (game_over_timer_ > 0) { if (game_over_timer_ < GAME_OVER_DURATION_MS) {
if (game_over_timer_ >= GAME_OVER_DURATION_MS) { handleGameOverEvents(); // Maneja eventos al inicio
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
Audio::get()->fadeOutMusic(1000);
balloon_manager_->setBouncingSounds(true);
}
game_over_timer_ -= deltaTime; // Decremento time-based game_over_timer_ += deltaTime; // Incremento time-based
constexpr float FADE_TRIGGER_MS = 150.0f * (1000.0f / 60.0f); // 150 frames = 2500ms constexpr float FADE_TRIGGER_MS = GAME_OVER_DURATION_MS - (150.0f * (1000.0f / 60.0f)); // 2500ms antes del final
if (game_over_timer_ <= FADE_TRIGGER_MS && !fade_out_->isEnabled()) { if (game_over_timer_ >= FADE_TRIGGER_MS && !fade_out_->isEnabled()) {
fade_out_->activate(); fade_out_->activate();
} }
} }
@@ -351,7 +346,7 @@ void Game::updateGameStateGameOver(float deltaTime) {
} }
if (fade_out_->hasEnded()) { if (fade_out_->hasEnded()) {
if (game_completed_counter_ > 0) { if (game_completed_timer_ > 0) {
Section::name = Section::Name::CREDITS; // Los jugadores han completado el juego Section::name = Section::Name::CREDITS; // Los jugadores han completado el juego
} else { } else {
Section::name = Section::Name::HI_SCORE_TABLE; // La partida ha terminado con la derrota de los jugadores Section::name = Section::Name::HI_SCORE_TABLE; // La partida ha terminado con la derrota de los jugadores
@@ -366,9 +361,6 @@ void Game::updateGameStateGameOver(float deltaTime) {
// Gestiona eventos para el estado del final del juego // Gestiona eventos para el estado del final del juego
void Game::updateGameStateCompleted(float deltaTime) { void Game::updateGameStateCompleted(float deltaTime) {
constexpr int START_CELEBRATIONS = 400;
constexpr int END_CELEBRATIONS = START_CELEBRATIONS + 300;
updatePlayers(deltaTime); updatePlayers(deltaTime);
updateScoreboard(); updateScoreboard();
updateBackground(); updateBackground();
@@ -380,40 +372,16 @@ void Game::updateGameStateCompleted(float deltaTime) {
updatePathSprites(); updatePathSprites();
cleanVectors(); cleanVectors();
// Comienza las celebraciones // Maneja eventos del juego completado
// Muestra el mensaje de felicitación y da los puntos a los jugadores handleGameCompletedEvents();
if (game_completed_counter_ == START_CELEBRATIONS) {
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
for (auto &player : players_) {
if (player->isPlaying()) {
player->addScore(1000000, Options::settings.hi_score_table.back().score);
player->setPlayingState(Player::State::CELEBRATING);
} else {
player->setPlayingState(Player::State::GAME_OVER);
}
}
updateHiScore();
}
// Termina las celebraciones
if (game_completed_counter_ == END_CELEBRATIONS) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);
}
}
}
// Si los jugadores ya no estan y no quedan mensajes en pantalla // Si los jugadores ya no estan y no quedan mensajes en pantalla
if (allPlayersAreGameOver() && path_sprites_.empty()) { if (allPlayersAreGameOver() && path_sprites_.empty()) {
setState(State::GAME_OVER); setState(State::GAME_OVER);
} }
// Incrementa el contador al final // Incrementa el acumulador al final
++game_completed_counter_; game_completed_timer_ += deltaTime;
} }
// Comprueba el estado del juego // Comprueba el estado del juego
@@ -895,11 +863,11 @@ void Game::updateTimeStopped(float deltaTime) {
static constexpr float CLOCK_SOUND_INTERVAL_MS = 500.0f; // 30 frames a 60fps static constexpr float CLOCK_SOUND_INTERVAL_MS = 500.0f; // 30 frames a 60fps
static constexpr float COLOR_FLASH_INTERVAL_MS = 250.0f; // 15 frames a 60fps static constexpr float COLOR_FLASH_INTERVAL_MS = 250.0f; // 15 frames a 60fps
if (time_stopped_counter_ > 0) { if (time_stopped_timer_ > 0) {
time_stopped_counter_ -= deltaTime; time_stopped_timer_ -= deltaTime;
// Fase de advertencia (últimos 2 segundos) // Fase de advertencia (últimos 2 segundos)
if (time_stopped_counter_ <= WARNING_THRESHOLD_MS) { if (time_stopped_timer_ <= WARNING_THRESHOLD_MS) {
static float last_sound_time = 0.0f; static float last_sound_time = 0.0f;
last_sound_time += deltaTime; last_sound_time += deltaTime;
@@ -925,7 +893,6 @@ void Game::updateTimeStopped(float deltaTime) {
} }
} }
// Actualiza toda la lógica del juego // Actualiza toda la lógica del juego
void Game::update(float deltaTime) { void Game::update(float deltaTime) {
screen_->update(); screen_->update();
@@ -1011,12 +978,12 @@ void Game::fillCanvas() {
void Game::enableTimeStopItem() { void Game::enableTimeStopItem() {
balloon_manager_->stopAllBalloons(); balloon_manager_->stopAllBalloons();
balloon_manager_->reverseColorsToAllBalloons(); balloon_manager_->reverseColorsToAllBalloons();
time_stopped_counter_ = TIME_STOPPED_DURATION_MS; time_stopped_timer_ = TIME_STOPPED_DURATION_MS;
} }
// Deshabilita el efecto del item de detener el tiempo // Deshabilita el efecto del item de detener el tiempo
void Game::disableTimeStopItem() { void Game::disableTimeStopItem() {
time_stopped_counter_ = 0; time_stopped_timer_ = 0;
balloon_manager_->startAllBalloons(); balloon_manager_->startAllBalloons();
balloon_manager_->normalColorsToAllBalloons(); balloon_manager_->normalColorsToAllBalloons();
} }
@@ -1926,6 +1893,55 @@ void Game::onPauseStateChanged(bool is_paused) {
tabe_->pauseTimer(is_paused); tabe_->pauseTimer(is_paused);
} }
// Maneja eventos del juego completado usando flags para triggers únicos
void Game::handleGameCompletedEvents() {
constexpr float START_CELEBRATIONS_MS = 6667.0f; // 400 frames a 60fps
constexpr float END_CELEBRATIONS_MS = 11667.0f; // 700 frames a 60fps
// Inicio de celebraciones
static bool start_celebrations_triggered = false;
if (!start_celebrations_triggered && game_completed_timer_ >= START_CELEBRATIONS_MS) {
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
for (auto &player : players_) {
if (player->isPlaying()) {
player->addScore(1000000, Options::settings.hi_score_table.back().score);
player->setPlayingState(Player::State::CELEBRATING);
} else {
player->setPlayingState(Player::State::GAME_OVER);
}
}
updateHiScore();
start_celebrations_triggered = true;
}
// Fin de celebraciones
static bool end_celebrations_triggered = false;
if (!end_celebrations_triggered && game_completed_timer_ >= END_CELEBRATIONS_MS) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);
}
}
fade_out_->activate();
end_celebrations_triggered = true;
}
}
// Maneja eventos de game over usando flag para trigger único
void Game::handleGameOverEvents() {
static bool game_over_triggered = false;
if (!game_over_triggered && game_over_timer_ == 0.0f) {
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
Audio::get()->fadeOutMusic(1000);
balloon_manager_->setBouncingSounds(true);
game_over_triggered = true;
}
}
#ifdef _DEBUG #ifdef _DEBUG
// Comprueba los eventos en el modo DEBUG // Comprueba los eventos en el modo DEBUG
void Game::handleDebugEvents(const SDL_Event &event) { void Game::handleDebugEvents(const SDL_Event &event) {
@@ -2002,53 +2018,4 @@ void Game::handleDebugEvents(const SDL_Event &event) {
} }
} }
} }
// Maneja eventos del juego completado usando flags para triggers únicos
void Game::handleGameCompletedEvents() {
constexpr float START_CELEBRATIONS_MS = 6667.0f; // 400 frames a 60fps
constexpr float END_CELEBRATIONS_MS = 11667.0f; // 700 frames a 60fps
// Inicio de celebraciones
static bool start_celebrations_triggered = false;
if (!start_celebrations_triggered && game_completed_counter_ >= START_CELEBRATIONS_MS) {
createMessage({paths_.at(4), paths_.at(5)}, Resource::get()->getTexture("game_text_congratulations"));
createMessage({paths_.at(6), paths_.at(7)}, Resource::get()->getTexture("game_text_1000000_points"));
for (auto &player : players_) {
if (player->isPlaying()) {
player->addScore(1000000, Options::settings.hi_score_table.back().score);
player->setPlayingState(Player::State::CELEBRATING);
} else {
player->setPlayingState(Player::State::GAME_OVER);
}
}
updateHiScore();
start_celebrations_triggered = true;
}
// Fin de celebraciones
static bool end_celebrations_triggered = false;
if (!end_celebrations_triggered && game_completed_counter_ >= END_CELEBRATIONS_MS) {
for (auto &player : players_) {
if (player->isCelebrating()) {
player->setPlayingState(player->qualifiesForHighScore() ? Player::State::ENTERING_NAME_GAME_COMPLETED : Player::State::LEAVING_SCREEN);
}
}
fade_out_->activate();
end_celebrations_triggered = true;
}
}
// Maneja eventos de game over usando flag para trigger único
void Game::handleGameOverEvents() {
static bool game_over_triggered = false;
if (!game_over_triggered && game_over_timer_ >= GAME_OVER_DURATION_MS) {
createMessage({paths_.at(2), paths_.at(3)}, Resource::get()->getTexture("game_text_game_over"));
Audio::get()->fadeOutMusic(1000);
balloon_manager_->setBouncingSounds(true);
game_over_triggered = true;
}
}
#endif #endif

View File

@@ -153,11 +153,11 @@ class Game {
Uint64 last_time_ = 0; // Último tiempo registrado para deltaTime 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 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 bool hi_score_achieved_ = false; // Indica si se ha superado la puntuación máxima
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad float difficulty_score_multiplier_ = 1.0f; // Multiplicador de puntos en función de la dificultad
float counter_ = 0; // Contador para el juego float counter_ = 0.0f; // Contador para el juego
float game_completed_counter_ = 0; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más globos float game_completed_timer_ = 0.0f; // Acumulador de tiempo para el tramo final (milisegundos)
float game_over_timer_ = GAME_OVER_DURATION_MS; // Timer para el estado de fin de partida (milisegundos) float game_over_timer_ = 0.0f; // Timer para el estado de fin de partida (milisegundos)
float time_stopped_counter_ = 0; // Temporizador para llevar la cuenta del tiempo detenido float time_stopped_timer_ = 0.0f; // Temporizador para llevar la cuenta del tiempo detenido
int menace_ = 0; // Nivel de amenaza actual 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 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 State state_ = State::FADE_IN; // Estado