Continue amb BalloonManager

This commit is contained in:
2024-11-07 20:56:56 +01:00
parent 0e527ff9d9
commit 2fb7e88e4b
12 changed files with 226 additions and 178 deletions

View File

@@ -1,9 +1,19 @@
#include "game.h"
#include "stage.h"
#include "asset.h" // Para Asset
#include "background.h" // Para Background
#include "bullet.h" // Para Bullet, BulletType, BulletMoveStatus
#include "balloon_manager.h"
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // Para SDLK_1, SDLK_2, SDLK_3, SDLK_4
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_FOCUS_GAINED, SDL_...
#include <stdlib.h> // Para rand, size_t
#include <algorithm> // Para find_if, clamp, min
#include <functional> // Para function
#include <iterator> // Para distance, size
#include "asset.h" // Para Asset
#include "background.h" // Para Background
#include "balloon.h" // Para Balloon, BALLOON_SPEED
#include "balloon_manager.h" // Para BalloonManager
#include "bullet.h" // Para Bullet, BulletType, BulletMoveStatus
#include "fade.h" // Para Fade, FadeType
#include "global_inputs.h" // Para check
#include "input.h" // Para InputType, Input, INPUT_DO_NOT_ALL...
@@ -14,27 +24,17 @@
#include "notifier.h" // Para Notifier
#include "param.h" // Para Param, param, ParamGame, ParamFade
#include "path_sprite.h" // Para Path, PathSprite, createPath, Path...
#include "player.h" // Para Player, PlayerStatus
#include "player.h" // Para Player, PlayerState
#include "resource.h" // Para Resource
#include "scoreboard.h" // Para Scoreboard, ScoreboardMode, SCOREB...
#include "screen.h" // Para Screen
#include "section.h" // Para Name, name, Options, options
#include "smart_sprite.h" // Para SmartSprite
#include "stage.h" // Para get, number, Stage, power
#include "text.h" // Para Text
#include "dbgtxt.h" // Para dbg_print
#include "texture.h" // Para Texture
#include <SDL2/SDL_blendmode.h> // Para SDL_BLENDMODE_BLEND
#include <SDL2/SDL_events.h> // Para SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // Para SDLK_1, SDLK_2, SDLK_3, SDLK_4
#include <SDL2/SDL_pixels.h> // Para SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_timer.h> // Para SDL_GetTicks
#include <SDL2/SDL_video.h> // Para SDL_WINDOWEVENT_FOCUS_GAINED, SDL_...
#include <algorithm> // Para find_if, clamp, min, remove_if
#include <functional> // Para function
#include <iterator> // Para distance, size
#include <numeric> // Para accumulate
#include <stdlib.h> // Para rand, size_t
struct JA_Sound_t; // lines 36-36
struct JA_Sound_t; // lines 37-37
// Constructor
Game::Game(int player_id, int current_stage, bool demo)
@@ -45,8 +45,7 @@ Game::Game(int player_id, int current_stage, bool demo)
background_(std::make_unique<Background>()),
canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h)),
fade_(std::make_unique<Fade>()),
balloon_manager_(std::make_unique<BalloonManager>(*this)),
current_stage_(current_stage)
balloon_manager_(std::make_unique<BalloonManager>())
{
// Pasa variables
demo_.enabled = demo;
@@ -54,6 +53,8 @@ Game::Game(int player_id, int current_stage, bool demo)
// Otras variables
section::name = section::Name::GAME;
section::options = section::Options::GAME_PLAY_1P;
Stage::init();
Stage::number = current_stage;
// Asigna texturas y animaciones
setResources();
@@ -81,16 +82,16 @@ Game::Game(int player_id, int current_stage, bool demo)
#ifdef DEBUG
// Si se empieza en una fase que no es la primera
if (!demo_.enabled)
for (int i = 0; i < current_stage_; ++i)
for (int i = 0; i < Stage::number; ++i)
{
balloons_popped_ += balloon_formations_->getStage(i).power_to_complete;
balloons_popped_ += Stage::get(i).power_to_complete;
}
#endif
// Crea los primeros globos y el mensaje de inicio
if (!demo_.enabled)
{
createTwoBigBalloons();
balloon_manager_->createTwoBigBalloons();
evaluateAndSetMenace();
createMessage({paths_.at(0), paths_.at(1)}, Resource::get()->getTexture("get_ready"));
}
@@ -243,28 +244,29 @@ void Game::updateStage()
{
if (state_ == GameState::PLAYING)
{
if (current_power_ >= balloon_formations_->getStage(current_stage_).power_to_complete)
if (Stage::power >= Stage::get(Stage::number).power_to_complete)
{
// Cambio de fase
++current_stage_;
current_power_ = 0;
++Stage::number;
Stage::power = 0;
JA_PlaySound(Resource::get()->getSound("stage_change.wav"));
balloon_speed_ = default_balloon_speed_;
setBalloonSpeed(balloon_speed_);
balloon_manager_->resetBalloonSpeed();
screen_->flash(flash_color, 100);
screen_->shake();
// Escribe el texto por pantalla
if (current_stage_ < 10)
if (Stage::number < 10)
{
const auto stage_number = balloon_formations_->getStage(current_stage_).number;
const auto stage_number = Stage::get(Stage::number).number;
std::vector<Path> paths = {paths_.at(2), paths_.at(3)};
if (stage_number == 10)
{
createMessage(paths, Resource::get()->getTexture("last_stage"));
}
else
{
auto text = Resource::get()->getText("04b_25_2x");
const std::string caption = std::to_string(10 - current_stage_) + lang::getText(38);
const std::string caption = std::to_string(10 - Stage::number) + lang::getText(38);
createMessage(paths, text->writeToTexture(caption, 1, -4));
}
}
@@ -314,10 +316,10 @@ void Game::updateCompletedState()
if (game_completed_counter_ == 0)
{
stopMusic();
current_stage_ = 9; // Deja el valor dentro de los limites
destroyAllBalloons(); // Destruye a todos los globos
destroyAllItems(); // Destruye todos los items
current_power_ = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos los globos
Stage::number = 9; // Deja el valor dentro de los limites
balloon_manager_->destroyAllBalloons(); // Destruye a todos los globos
destroyAllItems(); // Destruye todos los items
Stage::power = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos los globos
}
// Comienza las celebraciones
@@ -359,7 +361,7 @@ void Game::updateCompletedState()
// Comprueba el estado del juego
void Game::checkState()
{
if (state_ != GameState::COMPLETED && current_stage_ == 10)
if (state_ != GameState::COMPLETED && Stage::number == 10)
{
state_ = GameState::COMPLETED;
}
@@ -380,10 +382,16 @@ void Game::destroyAllItems()
// Comprueba la colisión entre el jugador y los globos activos
bool Game::checkPlayerBalloonCollision(std::shared_ptr<Player> &player)
{
for (auto &balloon : balloons_)
for (auto &balloon : balloon_manager_->getBalloons())
{
if (!balloon->isStopped() && !balloon->isInvulnerable())
{
if (checkCollision(player->getCollider(), balloon->getCollider()))
{
return true;
}
}
}
return false;
}
@@ -485,7 +493,7 @@ void Game::checkBulletBalloonCollision()
{
for (auto &bullet : bullets_)
{
for (auto &balloon : balloons_)
for (auto &balloon : balloon_manager_->getBalloons())
{
if (balloon->isEnabled() && (!balloon->isInvulnerable()) && bullet->isEnabled())
{
@@ -518,7 +526,9 @@ void Game::checkBulletBalloonCollision()
}
// Explota el globo
popBalloon(balloon);
balloon_manager_->popBalloon(balloon);
balloons_popped_++;
evaluateAndSetMenace();
// Sonido de explosión
JA_PlaySound(Resource::get()->getSound("balloon.wav"));
@@ -821,9 +831,9 @@ void Game::updateTimeStopped()
if (time_stopped_counter_ % 15 == 0)
JA_PlaySound(Resource::get()->getSound("clock.wav"));
if (time_stopped_counter_ % 30 == 0)
normalColorsToAllBalloons();
balloon_manager_->normalColorsToAllBalloons();
if (time_stopped_counter_ % 30 == 15)
reverseColorsToAllBalloons();
balloon_manager_->reverseColorsToAllBalloons();
}
}
else
@@ -858,7 +868,9 @@ void Game::updateBackground()
{
// Si el juego está completado, se reduce la velocidad de las nubes
if (state_ == GameState::COMPLETED)
{
balloons_popped_ = (balloons_popped_ > 400) ? (balloons_popped_ - 25) : 200;
}
// Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego
constexpr float clouds_initial_speed = 0.05f;
@@ -887,11 +899,12 @@ void Game::fillCanvas()
background_->render();
renderItems();
renderSmartSprites();
explosions_->render();
balloon_manager_->renderBalloons();
balloon_manager_->render();
renderBullets();
renderPathSprites();
renderPlayers();
dbg_print(0, 40, std::to_string(menace_current_).c_str(), 255, 0 ,0);
dbg_print(0, 50, std::to_string(menace_threshold_).c_str(), 255, 0 ,0);
// Deja el renderizador apuntando donde estaba
SDL_SetRenderTarget(renderer_, temp);
@@ -919,8 +932,8 @@ void Game::render()
// Habilita el efecto del item de detener el tiempo
void Game::enableTimeStopItem()
{
stopAllBalloons();
reverseColorsToAllBalloons();
balloon_manager_->stopAllBalloons();
balloon_manager_->reverseColorsToAllBalloons();
time_stopped_counter_ = TIME_STOPPED_COUNTER_;
}
@@ -928,8 +941,8 @@ void Game::enableTimeStopItem()
void Game::disableTimeStopItem()
{
time_stopped_counter_ = 0;
startAllBalloons();
normalColorsToAllBalloons();
balloon_manager_->startAllBalloons();
balloon_manager_->normalColorsToAllBalloons();
}
// Comprueba si la música ha de estar sonando
@@ -1118,7 +1131,7 @@ void Game::checkEvents()
}
case SDLK_2: // Crea dos globos gordos
{
createTwoBigBalloons();
balloon_manager_->createTwoBigBalloons();
}
break;
case SDLK_3: // Activa el modo para pasar el juego automaticamente
@@ -1188,8 +1201,8 @@ void Game::updateScoreboard()
}
// Resto de marcador
scoreboard_->setStage(balloon_formations_->getStage(current_stage_).number);
scoreboard_->setPower((float)current_power_ / (float)balloon_formations_->getStage(current_stage_).power_to_complete);
scoreboard_->setStage(Stage::get(Stage::number).number);
scoreboard_->setPower((float)Stage::power / (float)Stage::get(Stage::number).power_to_complete);
scoreboard_->setHiScore(hi_score_.score);
scoreboard_->setHiScoreName(hi_score_.name);
@@ -1200,8 +1213,8 @@ void Game::updateScoreboard()
// Pausa el juego
void Game::pause(bool value)
{
paused_ = value;
screen_->attenuate(paused_);
//paused_ = value;
//screen_->attenuate(paused_);
}
// Añade una puntuación a la tabla de records
@@ -1528,13 +1541,13 @@ void Game::initDemo(int player_id)
constexpr auto demos = 3;
const auto demo = rand() % demos;
const int stages[demos] = {0, 3, 5};
current_stage_ = stages[demo];
Stage::number = stages[demo];
}
// Actualiza el numero de globos explotados según la fase del modo demostración
for (int i = 0; i < current_stage_; ++i)
for (int i = 0; i < Stage::number; ++i)
{
balloons_popped_ += balloon_formations_->getStage(i).power_to_complete;
balloons_popped_ += Stage::get(i).power_to_complete;
}
// Activa o no al otro jugador
@@ -1604,7 +1617,7 @@ void Game::initDifficultyVars()
{
case GameDifficulty::EASY:
{
default_balloon_speed_ = BALLOON_SPEED[0];
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]);
difficulty_score_multiplier_ = 0.5f;
scoreboard_->setColor(scoreboard_easy_color);
break;
@@ -1612,7 +1625,7 @@ void Game::initDifficultyVars()
case GameDifficulty::NORMAL:
{
default_balloon_speed_ = BALLOON_SPEED[0];
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[0]);
difficulty_score_multiplier_ = 1.0f;
scoreboard_->setColor(scoreboard_normal_color);
break;
@@ -1620,7 +1633,7 @@ void Game::initDifficultyVars()
case GameDifficulty::HARD:
{
default_balloon_speed_ = BALLOON_SPEED[4];
balloon_manager_->setDefaultBalloonSpeed(BALLOON_SPEED[4]);
difficulty_score_multiplier_ = 1.5f;
scoreboard_->setColor(scoreboard_hard_color);
break;
@@ -1630,7 +1643,7 @@ void Game::initDifficultyVars()
break;
}
balloon_speed_ = default_balloon_speed_;
balloon_manager_->resetBalloonSpeed();
}
// Inicializa los jugadores
@@ -1729,7 +1742,7 @@ void Game::updateGame()
if (auto_pop_balloons_ && state_ == GameState::PLAYING)
{
balloons_popped_ += 5;
increaseStageCurrentPower(5);
Stage::power += 5;
}
#endif
fade_->update();
@@ -1738,7 +1751,6 @@ void Game::updateGame()
updateScoreboard();
updateBackground();
balloon_manager_->update();
explosions_->update();
moveBullets();
updateItems();
updateStage();
@@ -1747,7 +1759,6 @@ void Game::updateGame()
updateSmartSprites();
updatePathSprites();
updateTimeStopped();
updateBalloonDeployCounter();
updateHelper();
checkBulletBalloonCollision();
updateMenace();
@@ -1770,8 +1781,8 @@ void Game::cleanVectors()
// Gestiona el nivel de amenaza
void Game::updateMenace()
{
const auto stage = balloon_formations_->getStage(current_stage_);
const float percent = current_power_ / stage.power_to_complete;
const auto stage = Stage::get(Stage::number);
const float percent = Stage::power / stage.power_to_complete;
const int difference = stage.max_menace - stage.min_menace;
// Aumenta el nivel de amenaza en función de la puntuación
@@ -1781,7 +1792,7 @@ void Game::updateMenace()
if (menace_current_ < menace_threshold_)
{
// Crea una formación de enemigos
balloon_manager_->deployBalloonFormation();
balloon_manager_->deployBalloonFormation(Stage::number);
// Recalcula el nivel de amenaza con el nuevo globo
evaluateAndSetMenace();
@@ -1791,7 +1802,24 @@ void Game::updateMenace()
// Calcula y establece el valor de amenaza en funcion de los globos activos
void Game::evaluateAndSetMenace()
{
menace_current_ = std::accumulate(
balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon)
{ return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
menace_current_ = balloon_manager_->getMenace();
}
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void Game::checkAndUpdateBalloonSpeed()
{
if (difficulty_ != GameDifficulty::NORMAL)
return;
const float percent = static_cast<float>(Stage::power) / Stage::get(Stage::number).power_to_complete;
const float thresholds[] = {0.2f, 0.4f, 0.6f, 0.8f};
for (size_t i = 0; i < std::size(thresholds); ++i)
{
if (balloon_manager_->getBalloonSpeed() == BALLOON_SPEED[i] && percent > thresholds[i])
{
balloon_manager_->setBalloonSpeed(BALLOON_SPEED[i + 1]);
break; // Salir del bucle una vez actualizada la velocidad y aplicada
}
}
}