From 3e3d764b253a1675c2858c6a7e42ae278fe4134e Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Tue, 8 Oct 2024 20:32:24 +0200 Subject: [PATCH] Commitet pa gastar el Cppcheck --- source/director.cpp | 48 +++------- source/director.h | 6 -- source/game_logo.cpp | 192 ++++++++++++++++++--------------------- source/game_logo.h | 51 +++++------ source/global_inputs.cpp | 2 +- source/hiscore_table.cpp | 97 ++++++-------------- source/hiscore_table.h | 6 -- source/main.cpp | 4 +- source/notify.cpp | 110 ++++++++++------------ source/notify.h | 85 ++++++----------- source/scoreboard.cpp | 43 ++------- source/scoreboard.h | 2 +- 12 files changed, 241 insertions(+), 405 deletions(-) diff --git a/source/director.cpp b/source/director.cpp index ec17cc1..33e7694 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -117,11 +117,11 @@ Director::~Director() Asset::destroy(); Input::destroy(); - //Screen::destroy(); + Screen::destroy(); OnScreenHelp::destroy(); - deleteSounds(); - deleteMusics(); + sounds.clear(); + musics.clear(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); @@ -593,30 +593,10 @@ void Director::loadMusics() } } -// Libera la memoria usada por los sonidos del juego -void Director::deleteSounds() -{ - for (auto s : sounds) - { - JA_DeleteSound(s.file); - } - sounds.clear(); -} - -// Libera la memoria usada por las músicas del juego -void Director::deleteMusics() -{ - for (auto m : musics) - { - JA_DeleteMusic(m.file); - } - musics.clear(); -} - // Ejecuta la sección con el logo void Director::runLogo() { - Logo *logo = new Logo(); + auto *logo = new Logo(); logo->run(); delete logo; } @@ -624,7 +604,7 @@ void Director::runLogo() // Ejecuta la sección con la secuencia de introducción void Director::runIntro() { - Intro *intro = new Intro(getMusic(musics, "intro.ogg")); + auto *intro = new Intro(getMusic(musics, "intro.ogg")); intro->run(); delete intro; } @@ -632,7 +612,7 @@ void Director::runIntro() // Ejecuta la sección con el titulo del juego void Director::runTitle() { - Title *title = new Title(getMusic(musics, "title.ogg")); + auto *title = new Title(getMusic(musics, "title.ogg")); title->run(); delete title; } @@ -640,9 +620,9 @@ void Director::runTitle() // Ejecuta la sección donde se juega al juego void Director::runGame() { - const int playerID = section::options == section::OPTIONS_GAME_PLAY_1P ? 1 : 2; - const int currentStage = 0; - Game *game = new Game(playerID, currentStage, GAME_MODE_DEMO_OFF, getMusic(musics, "playing.ogg")); + const auto playerID = section::options == section::OPTIONS_GAME_PLAY_1P ? 1 : 2; + constexpr auto currentStage = 0; + auto *game = new Game(playerID, currentStage, GAME_MODE_DEMO_OFF, getMusic(musics, "playing.ogg")); game->run(); delete game; } @@ -650,7 +630,7 @@ void Director::runGame() // Ejecuta la sección donde se muestran las instrucciones void Director::runInstructions() { - Instructions *instructions = new Instructions(getMusic(musics, "title.ogg")); + auto *instructions = new Instructions(getMusic(musics, "title.ogg")); instructions->run(); delete instructions; } @@ -658,7 +638,7 @@ void Director::runInstructions() // Ejecuta la sección donde se muestra la tabla de puntuaciones void Director::runHiScoreTable() { - HiScoreTable *hiScoreTable = new HiScoreTable(getMusic(musics, "title.ogg")); + auto *hiScoreTable = new HiScoreTable(getMusic(musics, "title.ogg")); hiScoreTable->run(); delete hiScoreTable; } @@ -666,9 +646,9 @@ void Director::runHiScoreTable() // Ejecuta el juego en modo demo void Director::runDemoGame() { - const int playerID = (rand() % 2) + 1; - const int currentStage = 0; - Game *game = new Game(playerID, currentStage, GAME_MODE_DEMO_ON, nullptr); + const auto playerID = (rand() % 2) + 1; + constexpr auto currentStage = 0; + auto *game = new Game(playerID, currentStage, GAME_MODE_DEMO_ON, nullptr); game->run(); delete game; } diff --git a/source/director.h b/source/director.h index 03ed13f..023dc5f 100644 --- a/source/director.h +++ b/source/director.h @@ -45,12 +45,6 @@ private: // Carga las musicas del juego void loadMusics(); - // Libera la memoria usada por los sonidos del juego - void deleteSounds(); - - // Libera la memoria usada por las músicas del juego - void deleteMusics(); - // Comprueba los parametros del programa void checkProgramArguments(int argc, char *argv[]); diff --git a/source/game_logo.cpp b/source/game_logo.cpp index fd6b8ec..8b9ab6f 100644 --- a/source/game_logo.cpp +++ b/source/game_logo.cpp @@ -1,40 +1,36 @@ #include "game_logo.h" #include // for max #include // for basic_string -#include "animated_sprite.h" // for AnimatedSprite +#include "animated_sprite.h" // for AnimatedSprite #include "asset.h" // for Asset #include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_PlaySound #include "param.h" // for param #include "screen.h" // for Screen -#include "smart_sprite.h" // for SmartSprite +#include "smart_sprite.h" // for SmartSprite #include "sprite.h" // for Sprite #include "texture.h" // for Texture #include "utils.h" // for param_t, paramGame_t, paramTitle_t // Constructor GameLogo::GameLogo(int x, int y) + : x(x), y(y) { - // Copia los punteros - screen = Screen::get(); - renderer = screen->getRenderer(); - asset = Asset::get(); - this->x = x; - this->y = y; - // Crea los objetos - dustTexture = new Texture(renderer, asset->get("title_dust.png")); - coffeeTexture = new Texture(renderer, asset->get("title_coffee.png")); - crisisTexture = new Texture(renderer, asset->get("title_crisis.png")); - arcadeEditionTexture = new Texture(renderer, asset->get("title_arcade_edition.png")); + dustTexture = std::make_unique(Screen::get()->getRenderer(), Asset::get()->get("title_dust.png")); + coffeeTexture = std::make_unique(Screen::get()->getRenderer(), Asset::get()->get("title_coffee.png")); + crisisTexture = std::make_unique(Screen::get()->getRenderer(), Asset::get()->get("title_crisis.png")); + arcadeEditionTexture = std::make_unique(Screen::get()->getRenderer(), Asset::get()->get("title_arcade_edition.png")); - coffeeBitmap = new SmartSprite(coffeeTexture); - crisisBitmap = new SmartSprite(crisisTexture); - arcadeEditionBitmap = new Sprite((param.game.width - arcadeEditionTexture->getWidth()) / 2, param.title.arcadeEditionPosition, arcadeEditionTexture->getWidth(), arcadeEditionTexture->getHeight(), arcadeEditionTexture); - dustBitmapL = new AnimatedSprite(dustTexture, asset->get("title_dust.ani")); - dustBitmapR = new AnimatedSprite(dustTexture, asset->get("title_dust.ani")); + coffeeSprite = std::make_unique(coffeeTexture.get()); + crisisSprite = std::make_unique(crisisTexture.get()); + + arcadeEditionSprite = std::make_unique((param.game.width - arcadeEditionTexture->getWidth()) / 2, param.title.arcadeEditionPosition, arcadeEditionTexture->getWidth(), arcadeEditionTexture->getHeight(), arcadeEditionTexture.get()); + + dustLSprite = std::make_unique(dustTexture.get(), Asset::get()->get("title_dust.ani")); + dustRSprite = std::make_unique(dustTexture.get(), Asset::get()->get("title_dust.ani")); // Sonidos - crashSound = JA_LoadSound(asset->get("title.wav").c_str()); + crashSound = JA_LoadSound(Asset::get()->get("title.wav").c_str()); // Inicializa las variables init(); @@ -43,28 +39,17 @@ GameLogo::GameLogo(int x, int y) // Destructor GameLogo::~GameLogo() { - delete dustTexture; - delete coffeeTexture; - delete crisisTexture; - delete arcadeEditionTexture; - - delete coffeeBitmap; - delete crisisBitmap; - delete arcadeEditionBitmap; - delete dustBitmapL; - delete dustBitmapR; - JA_DeleteSound(crashSound); } // Inicializa las variables void GameLogo::init() { - const int xp = x - coffeeBitmap->getWidth() / 2; - const int desp = getInitialVerticalDesp(); - + const auto xp = x - coffeeSprite->getWidth() / 2; + const auto desp = getInitialVerticalDesp(); + // Variables - status = disabled; + status = Status::DISABLED; shake.desp = 1; shake.delay = 2; shake.lenght = 8; @@ -73,90 +58,89 @@ void GameLogo::init() shake.origin = xp; // Inicializa el bitmap de 'Coffee' - coffeeBitmap->init(); - coffeeBitmap->setPosX(xp); - coffeeBitmap->setPosY(y - coffeeTexture->getHeight() - desp); - coffeeBitmap->setWidth(coffeeTexture->getWidth()); - coffeeBitmap->setHeight(coffeeTexture->getHeight()); - coffeeBitmap->setVelX(0.0f); - coffeeBitmap->setVelY(2.5f); - coffeeBitmap->setAccelX(0.0f); - coffeeBitmap->setAccelY(0.1f); - coffeeBitmap->setSpriteClip(0, 0, coffeeTexture->getWidth(), coffeeTexture->getHeight()); - coffeeBitmap->setEnabled(true); - coffeeBitmap->setEnabledCounter(0); - coffeeBitmap->setDestX(xp); - coffeeBitmap->setDestY(y - coffeeTexture->getHeight()); + coffeeSprite->init(); + coffeeSprite->setPosX(xp); + coffeeSprite->setPosY(y - coffeeTexture->getHeight() - desp); + coffeeSprite->setWidth(coffeeTexture->getWidth()); + coffeeSprite->setHeight(coffeeTexture->getHeight()); + coffeeSprite->setVelX(0.0f); + coffeeSprite->setVelY(2.5f); + coffeeSprite->setAccelX(0.0f); + coffeeSprite->setAccelY(0.1f); + coffeeSprite->setSpriteClip(0, 0, coffeeTexture->getWidth(), coffeeTexture->getHeight()); + coffeeSprite->setEnabled(true); + coffeeSprite->setEnabledCounter(0); + coffeeSprite->setDestX(xp); + coffeeSprite->setDestY(y - coffeeTexture->getHeight()); // Inicializa el bitmap de 'Crisis' - crisisBitmap->init(); - crisisBitmap->setPosX(xp + 15); - crisisBitmap->setPosY(y + desp); - crisisBitmap->setWidth(crisisTexture->getWidth()); - crisisBitmap->setHeight(crisisTexture->getHeight()); - crisisBitmap->setVelX(0.0f); - crisisBitmap->setVelY(-2.5f); - crisisBitmap->setAccelX(0.0f); - crisisBitmap->setAccelY(-0.1f); - crisisBitmap->setSpriteClip(0, 0, crisisTexture->getWidth(), crisisTexture->getHeight()); - crisisBitmap->setEnabled(true); - crisisBitmap->setEnabledCounter(0); - crisisBitmap->setDestX(xp + 15); - crisisBitmap->setDestY(y); + crisisSprite->init(); + crisisSprite->setPosX(xp + 15); + crisisSprite->setPosY(y + desp); + crisisSprite->setWidth(crisisTexture->getWidth()); + crisisSprite->setHeight(crisisTexture->getHeight()); + crisisSprite->setVelX(0.0f); + crisisSprite->setVelY(-2.5f); + crisisSprite->setAccelX(0.0f); + crisisSprite->setAccelY(-0.1f); + crisisSprite->setSpriteClip(0, 0, crisisTexture->getWidth(), crisisTexture->getHeight()); + crisisSprite->setEnabled(true); + crisisSprite->setEnabledCounter(0); + crisisSprite->setDestX(xp + 15); + crisisSprite->setDestY(y); // Inicializa el bitmap de 'DustRight' - dustBitmapR->resetAnimation(); - dustBitmapR->setPosX(coffeeBitmap->getPosX() + coffeeBitmap->getWidth()); - dustBitmapR->setPosY(y); - dustBitmapR->setWidth(16); - dustBitmapR->setHeight(16); - dustBitmapR->setFlip(SDL_FLIP_HORIZONTAL); + dustRSprite->resetAnimation(); + dustRSprite->setPosX(coffeeSprite->getPosX() + coffeeSprite->getWidth()); + dustRSprite->setPosY(y); + dustRSprite->setWidth(16); + dustRSprite->setHeight(16); + dustRSprite->setFlip(SDL_FLIP_HORIZONTAL); // Inicializa el bitmap de 'DustLeft' - dustBitmapL->resetAnimation(); - dustBitmapL->setPosX(coffeeBitmap->getPosX() - 16); - dustBitmapL->setPosY(y); - dustBitmapL->setWidth(16); - dustBitmapL->setHeight(16); + dustLSprite->resetAnimation(); + dustLSprite->setPosX(coffeeSprite->getPosX() - 16); + dustLSprite->setPosY(y); + dustLSprite->setWidth(16); + dustLSprite->setHeight(16); } // Pinta la clase en pantalla void GameLogo::render() { // Dibuja el logo - coffeeBitmap->render(); - crisisBitmap->render(); + coffeeSprite->render(); + crisisSprite->render(); - if (status == finished) - arcadeEditionBitmap->render(); + if (status == Status::FINISHED) + { + arcadeEditionSprite->render(); + } // Dibuja el polvillo del logo - dustBitmapR->render(); - dustBitmapL->render(); + dustRSprite->render(); + dustLSprite->render(); } // Actualiza la lógica de la clase void GameLogo::update() { - if (status == moving) + if (status == Status::MOVING) { - coffeeBitmap->update(); - crisisBitmap->update(); + coffeeSprite->update(); + crisisSprite->update(); // Si los objetos han llegado a su destino, cambiamos de Sección - if (coffeeBitmap->hasFinished() && crisisBitmap->hasFinished()) + if (coffeeSprite->hasFinished() && crisisSprite->hasFinished()) { - status = shaking; - - // Pantallazo blanco - //screen->flash(flashColor, 10); + status = Status::SHAKING; // Reproduce el efecto sonoro JA_PlaySound(crashSound); } } - else if (status == shaking) + else if (status == Status::SHAKING) { // Agita el logo if (shake.remaining > 0) @@ -168,27 +152,27 @@ void GameLogo::update() else { shake.counter = shake.delay; - const int desp = shake.remaining % 2 == 0 ? shake.desp * (-1) : shake.desp; - coffeeBitmap->setPosX(shake.origin + desp); - crisisBitmap->setPosX(shake.origin + desp + 15); + const auto desp = shake.remaining % 2 == 0 ? shake.desp * (-1) : shake.desp; + coffeeSprite->setPosX(shake.origin + desp); + crisisSprite->setPosX(shake.origin + desp + 15); shake.remaining--; } } else { - coffeeBitmap->setPosX(shake.origin); - crisisBitmap->setPosX(shake.origin + 15); - status = finished; + coffeeSprite->setPosX(shake.origin); + crisisSprite->setPosX(shake.origin + 15); + status = Status::FINISHED; } - dustBitmapR->update(); - dustBitmapL->update(); + dustRSprite->update(); + dustLSprite->update(); } - else if (status == finished) + else if (status == Status::FINISHED) { - dustBitmapR->update(); - dustBitmapL->update(); + dustRSprite->update(); + dustLSprite->update(); } } @@ -196,13 +180,13 @@ void GameLogo::update() void GameLogo::enable() { init(); - status = moving; + status = Status::MOVING; } // Indica si ha terminado la animación -bool GameLogo::hasFinished() +bool GameLogo::hasFinished() const { - return (status == finished); + return status == Status::FINISHED; } // Recarga las texturas @@ -216,8 +200,8 @@ void GameLogo::reLoad() // Calcula el desplazamiento vertical inicial int GameLogo::getInitialVerticalDesp() { - int despUp = y; - int despDown = param.game.height - y; + auto despUp = y; + auto despDown = param.game.height - y; return std::max(despUp, despDown); } \ No newline at end of file diff --git a/source/game_logo.h b/source/game_logo.h index c67e744..71029e2 100644 --- a/source/game_logo.h +++ b/source/game_logo.h @@ -1,12 +1,13 @@ #pragma once -#include // for SDL_Renderer -class AnimatedSprite; -class Asset; -class Screen; -class SmartSprite; -class Sprite; -class Texture; +#include // for SDL_Renderer +#include + +#include "texture.h" +#include "animated_sprite.h" +#include "smart_sprite.h" +#include "sprite.h" + struct JA_Sound_t; // Clase GameLogo @@ -14,22 +15,18 @@ class GameLogo { private: // Objetos y punteros - SDL_Renderer *renderer; // El renderizador de la ventana - Screen *screen; // Objeto encargado de dibujar en pantalla - Asset *asset; // Objeto que gestiona todos los ficheros de recursos + std::unique_ptr dustTexture; // Textura con los graficos del polvo + std::unique_ptr coffeeTexture; // Textura con los graficos de la palabra "COFFEE" + std::unique_ptr crisisTexture; // Textura con los graficos de la plabra "CRISIS" + std::unique_ptr arcadeEditionTexture; // Textura con los graficos de "Arcade Edition" - Texture *dustTexture; // Textura con los graficos del polvo - Texture *coffeeTexture; // Textura con los graficos de la palabra "COFFEE" - Texture *crisisTexture; // Textura con los graficos de la plabra "CRISIS" - Texture *arcadeEditionTexture; // Textura con los graficos de "Arcade Edition" + std::unique_ptr dustLSprite; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo + std::unique_ptr dustRSprite; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo - AnimatedSprite *dustBitmapL; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo - AnimatedSprite *dustBitmapR; // Sprite con la el polvo que aparece al colisionar el texto de la pantalla de titulo + std::unique_ptr coffeeSprite; // Sprite con la palabra "COFFEE" para la pantalla de titulo + std::unique_ptr crisisSprite; // Sprite con la palabra "CRISIS" para la pantalla de titulo - SmartSprite *coffeeBitmap; // Sprite con la palabra "COFFEE" para la pantalla de titulo - SmartSprite *crisisBitmap; // Sprite con la palabra "CRISIS" para la pantalla de titulo - - Sprite *arcadeEditionBitmap; // Sprite con los graficos de "Arcade Edition" + std::unique_ptr arcadeEditionSprite; // Sprite con los graficos de "Arcade Edition" JA_Sound_t *crashSound; // Sonido con el impacto del título @@ -37,15 +34,15 @@ private: int x; // Posición donde dibujar el logo int y; // Posición donde dibujar el logo - enum status_e + enum class Status { - disabled, - moving, - shaking, - finished + DISABLED, + MOVING, + SHAKING, + FINISHED, } status; // Estado en el que se encuentra la clase - struct shake_t + struct Shake { int desp; // Pixels de desplazamiento para agitar la pantalla en el eje x int delay; // Retraso entre cada desplazamiento de la pantalla al agitarse @@ -78,7 +75,7 @@ public: void enable(); // Indica si ha terminado la animación - bool hasFinished(); + bool hasFinished() const; // Recarga las texturas void reLoad(); diff --git a/source/global_inputs.cpp b/source/global_inputs.cpp index 0dfce60..ac9afdb 100644 --- a/source/global_inputs.cpp +++ b/source/global_inputs.cpp @@ -17,7 +17,7 @@ namespace globalInputs // Inicializa variables void init() { - const int numInputs = Input::get()->getNumControllers() + 1; + const auto numInputs = Input::get()->getNumControllers() + 1; servicePressedCounter.reserve(numInputs); for (int i = 0; i < numInputs; ++i) { diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index 0d2c632..242f75f 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -5,20 +5,21 @@ #include // for SDL_WINDOWEVENT_SIZE_CHANGED #include // for max #include // for vector -#include "asset.h" // for Asset -#include "background.h" // for Background -#include "global_inputs.h" // for globalInputs::check -#include "input.h" // for Input -#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state -#include "lang.h" // for getText -#include "options.h" // for options -#include "param.h" // for param -#include "screen.h" // for Screen -#include "text.h" // for Text, TXT_CENTER, TXT_SHADOW, TXT_COLOR -#include "utils.h" // for param_t, paramGame_t, hiScoreEntry_t +#include "asset.h" // for Asset +#include "background.h" // for Background +#include "global_inputs.h" // for globalInputs::check +#include "input.h" // for Input +#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state +#include "lang.h" // for getText +#include "options.h" // for options +#include "param.h" // for param +#include "screen.h" // for Screen +#include "text.h" // for Text, TXT_CENTER, TXT_SHADOW, TXT_COLOR +#include "utils.h" // for param_t, paramGame_t, hiScoreEntry_t // Constructor -HiScoreTable::HiScoreTable(JA_Music_t *music) : music(music) +HiScoreTable::HiScoreTable(JA_Music_t *music) + : music(music) { // Copia punteros renderer = Screen::get()->getRenderer(); @@ -74,7 +75,9 @@ void HiScoreTable::update() // Mantiene la música sonando if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) + { JA_PlayMusic(music); + } // Actualiza el objeto screen Screen::get()->update(); @@ -105,14 +108,14 @@ void HiScoreTable::update() void HiScoreTable::fillTexture() { // hay 27 letras - 7 de puntos quedan 20 caracteres 20 - nameLenght 0 numDots - const int maxNames = 10; - const int spaceBetweenHeader = 32; - const int spaceBetweenLines = text->getCharacterSize() * 2.0f; - const int size = spaceBetweenHeader + spaceBetweenLines * (maxNames - 1) + text->getCharacterSize(); - const int firstLine = (param.game.height - size) / 2; + constexpr auto maxNames = 10; + constexpr auto spaceBetweenHeader = 32; + const auto spaceBetweenLines = text->getCharacterSize() * 2.0f; + const auto size = spaceBetweenHeader + spaceBetweenLines * (maxNames - 1) + text->getCharacterSize(); + const auto firstLine = (param.game.height - size) / 2; // Pinta en el backbuffer el texto y los sprites - SDL_Texture *temp = SDL_GetRenderTarget(renderer); + auto *temp = SDL_GetRenderTarget(renderer); SDL_SetRenderTarget(renderer, backbuffer); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); SDL_RenderClear(renderer); @@ -123,16 +126,16 @@ void HiScoreTable::fillTexture() // Escribe los nombres de la tabla de puntuaciones for (int i = 0; i < maxNames; ++i) { - const int nameLenght = options.game.hiScoreTable[i].name.length(); - const std::string score = format(options.game.hiScoreTable[i].score); - const int scoreLenght = score.size(); - const int numDots = 25 - nameLenght - scoreLenght; + const auto nameLenght = options.game.hiScoreTable[i].name.length(); + const auto score = format(options.game.hiScoreTable[i].score); + const auto scoreLenght = score.size(); + const auto numDots = 25 - nameLenght - scoreLenght; std::string dots = ""; - for (int j = 0; j < numDots; ++j) + for (int j = 0; j < (int)numDots; ++j) { dots = dots + "."; } - const std::string line = options.game.hiScoreTable[i].name + dots + score; + const auto line = options.game.hiScoreTable[i].name + dots + score; text->writeDX(TXT_CENTER | TXT_SHADOW, param.game.gameArea.centerX, (i * spaceBetweenLines) + firstLine + spaceBetweenHeader, line, 1, orangeColor, 1, shdwTxtColor); } @@ -158,6 +161,7 @@ void HiScoreTable::render() // Copia el backbuffer al renderizador SDL_RenderCopy(renderer, backbuffer, nullptr, &viewArea); + // Renderiza el fade fade->render(); // Vuelca el contenido del renderizador en pantalla @@ -226,47 +230,6 @@ void HiScoreTable::run() } } -// Transforma un valor numérico en una cadena de 6 cifras -std::string HiScoreTable::scoreToString(int num) -{ - if ((num >= 0) && (num <= 9)) - { - return ("000000" + std::to_string(num)); - } - - if ((num >= 10) && (num <= 99)) - { - return ("00000" + std::to_string(num)); - } - - if ((num >= 100) && (num <= 999)) - { - return ("0000" + std::to_string(num)); - } - - if ((num >= 1000) && (num <= 9999)) - { - return ("000" + std::to_string(num)); - } - - if ((num >= 010000) && (num <= 99999)) - { - return ("00" + std::to_string(num)); - } - - if ((num >= 100000) && (num <= 999999)) - { - return ("0" + std::to_string(num)); - } - - if ((num >= 1000000) && (num <= 9999999)) - { - return (std::to_string(num)); - } - - return (std::to_string(num)); -} - // Gestiona el fade void HiScoreTable::updateFade() { @@ -291,9 +254,9 @@ std::string HiScoreTable::format(int number) const std::string separator = "."; const std::string score = std::to_string(number); - int index = (int)score.size() - 1; + auto index = (int)score.size() - 1; std::string result = ""; - int i = 0; + auto i = 0; while (index >= 0) { result = score.at(index) + result; diff --git a/source/hiscore_table.h b/source/hiscore_table.h index 83c6bfd..d7a6010 100644 --- a/source/hiscore_table.h +++ b/source/hiscore_table.h @@ -60,9 +60,6 @@ private: // Convierte un entero a un string con separadores de miles std::string format(int number); - // Transforma un valor numérico en una cadena de 6 cifras - std::string scoreToString(int num); - // Crea el contenido de la textura con la lista de puntuaciones void fillTexture(); @@ -72,9 +69,6 @@ private: // Gestiona el fade void updateFade(); - // Termina - void quit(section::options_e code); - public: // Constructor HiScoreTable(JA_Music_t *music); diff --git a/source/main.cpp b/source/main.cpp index f7ffbb4..d075286 100644 --- a/source/main.cpp +++ b/source/main.cpp @@ -19,12 +19,12 @@ int main(int argc, char *argv[]) Director *director = new Director(argc, argv); // Bucle principal - const int exit = director->run(); + const auto exit = director->run(); // Destruye el objeto Director delete director; - const std::string endType = exit == 0 ? "keyboard" : "controller"; + const auto endType = exit == 0 ? "keyboard" : "controller"; std::cout << "\nGame end with " << endType << std::endl; return exit; diff --git a/source/notify.cpp b/source/notify.cpp index 1e20e67..49e8acf 100644 --- a/source/notify.cpp +++ b/source/notify.cpp @@ -54,7 +54,7 @@ void Notify::update() // Si la notificación anterior está "saliendo", no hagas nada if (i > 0) { - if (notifications[i - 1].state == ns_rising) + if (notifications[i - 1].status == NotificationStatus::RISING) { break; } @@ -67,7 +67,7 @@ void Notify::update() { if (options.notification.sound) { - if (notifications[i].state == ns_rising) + if (notifications[i].status == NotificationStatus::RISING) { // Reproduce el sonido de la notificación JA_PlaySound(sound); } @@ -75,7 +75,7 @@ void Notify::update() } // Comprueba los estados - if (notifications[i].state == ns_rising) + if (notifications[i].status == NotificationStatus::RISING) { const float step = ((float)notifications[i].counter / notifications[i].travelDist); const int alpha = 255 * step; @@ -92,21 +92,21 @@ void Notify::update() if (notifications[i].rect.y == notifications[i].y) { - notifications[i].state = ns_stay; + notifications[i].status = NotificationStatus::STAY; notifications[i].texture->setAlpha(255); notifications[i].counter = 0; } } - else if (notifications[i].state == ns_stay) + else if (notifications[i].status == NotificationStatus::STAY) { if (notifications[i].counter == waitTime) { - notifications[i].state = ns_vanishing; + notifications[i].status = NotificationStatus::VANISHING; notifications[i].counter = 0; } } - else if (notifications[i].state == ns_vanishing) + else if (notifications[i].status == NotificationStatus::VANISHING) { const float step = (notifications[i].counter / (float)notifications[i].travelDist); @@ -124,7 +124,7 @@ void Notify::update() if (notifications[i].rect.y == notifications[i].y - notifications[i].travelDist) { - notifications[i].state = ns_finished; + notifications[i].status = NotificationStatus::FINISHED; } } @@ -139,7 +139,7 @@ void Notify::clearFinishedNotifications() { for (int i = (int)notifications.size() - 1; i >= 0; --i) { - if (notifications[i].state == ns_finished) + if (notifications[i].status == NotificationStatus::FINISHED) { notifications.erase(notifications.begin() + i); } @@ -150,15 +150,7 @@ void Notify::clearFinishedNotifications() void Notify::showText(std::string text1, std::string text2, int icon) { // Cuenta el número de textos a mostrar - int numTexts = 0; - if (text1 != "") - { - numTexts++; - } - if (text2 != "") - { - numTexts++; - } + const int numTexts = (text1 != "") + (text2 != ""); // Si no hay texto, acaba if (numTexts == 0) @@ -179,17 +171,17 @@ void Notify::showText(std::string text1, std::string text2, int icon) } // Inicializa variables - constexpr int iconSize = 16; - constexpr int paddingOut = 1; - const int paddingIn = text->getCharacterSize() / 2; - const int iconSpace = icon >= 0 ? iconSize + paddingIn : 0; + constexpr auto iconSize = 16; + constexpr auto paddingOut = 1; + const auto paddingIn = text->getCharacterSize() / 2; + const auto iconSpace = icon >= 0 ? iconSize + paddingIn : 0; const std::string txt = text1.length() > text2.length() ? text1 : text2; - const int width = text->lenght(txt) + (paddingIn * 2) + iconSpace; - const int height = (text->getCharacterSize() * numTexts) + (paddingIn * 2); - const notification_shape_t shape = notification_shape_squared; + const auto width = text->lenght(txt) + (paddingIn * 2) + iconSpace; + const auto height = (text->getCharacterSize() * numTexts) + (paddingIn * 2); + const auto shape = NotificationShape::SQUARED; // Posición horizontal - int despH = 0; + auto despH = 0; if (options.notification.posH == pos_left) { despH = paddingOut; @@ -204,20 +196,11 @@ void Notify::showText(std::string text1, std::string text2, int icon) } // Posición vertical - int despV = 0; - if (options.notification.posV == pos_top) - { - despV = paddingOut; - } - else - { - despV = param.game.height - height - paddingOut; - } - - const int travelDist = height + paddingOut; + const int despV = (options.notification.posV == pos_top) ? paddingOut : (param.game.height - height - paddingOut); // Offset - int offset = 0; + const auto travelDist = height + paddingOut; + auto offset = 0; if (options.notification.posV == pos_top) { offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV; @@ -227,18 +210,32 @@ void Notify::showText(std::string text1, std::string text2, int icon) offset = (int)notifications.size() > 0 ? notifications.back().y - travelDist : despV; } - // Crea la textura de fondo de la notificación - auto texture = std::make_unique(renderer); - texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); - texture->setBlendMode(SDL_BLENDMODE_BLEND); + // Crea la notificacion + Notification n; + + // Inicializa variables + n.y = offset; + n.travelDist = travelDist; + n.counter = 0; + n.status = NotificationStatus::RISING; + n.text1 = text1; + n.text2 = text2; + n.shape = shape; + auto yPos = offset + (options.notification.posV == pos_top ? -travelDist : travelDist); + n.rect = {despH, yPos, width, height}; + + // Crea la textura + n.texture = new Texture(renderer); + n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); + n.texture->setBlendMode(SDL_BLENDMODE_BLEND); // Prepara para dibujar en la textura - texture->setAsRenderTarget(renderer); + n.texture->setAsRenderTarget(renderer); - // Dibuja fondo de la notificación sobre la textura + // Dibuja el fondo de la notificación SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255); SDL_Rect rect; - if (shape == notification_shape_rounded) + if (shape == NotificationShape::ROUNDED) { rect = {4, 0, width - (4 * 2), height}; SDL_RenderFillRect(renderer, &rect); @@ -253,7 +250,7 @@ void Notify::showText(std::string text1, std::string text2, int icon) SDL_RenderFillRect(renderer, &rect); } - else if (shape == notification_shape_squared) + else if (shape == NotificationShape::SQUARED) { SDL_RenderClear(renderer); } @@ -283,28 +280,13 @@ void Notify::showText(std::string text1, std::string text2, int icon) SDL_SetRenderTarget(renderer, nullptr); // Crea el sprite de la notificación - auto sprite = std::make_unique((SDL_Rect){despH, 50, width, height}, texture.get()); - - // Crea la notificacion - notification_t n(std::move(texture), std::move(sprite)); - - // Inicializa variables - n.y = offset; - n.travelDist = travelDist; - n.counter = 0; - n.state = ns_rising; - n.text1 = text1; - n.text2 = text2; - n.shape = shape; - const int yPos = offset + (options.notification.posV == pos_top ? -travelDist : travelDist); - n.rect = {despH, yPos, width, height}; - n.sprite->setPos(n.rect); + n.sprite = new Sprite(n.rect, n.texture); // Deja la notificación invisible n.texture->setAlpha(0); // Añade la notificación a la lista - notifications.push_back(std::move(n)); + notifications.push_back(n); } // Indica si hay notificaciones activas @@ -323,7 +305,7 @@ void Notify::clearNotifications() { for (int i = 0; i < (int)notifications.size(); ++i) { - notifications[i].state = ns_finished; + notifications[i].status = NotificationStatus::FINISHED; } clearFinishedNotifications(); diff --git a/source/notify.h b/source/notify.h index 3350c89..6629ba5 100644 --- a/source/notify.h +++ b/source/notify.h @@ -14,72 +14,45 @@ struct JA_Sound_t; class Notify { private: - enum notification_state_e + enum class NotificationStatus { - ns_rising, - ns_stay, - ns_vanishing, - ns_finished + RISING, + STAY, + VANISHING, + FINISHED, }; - enum notification_position_e + enum class NotificationPosition { - upperLeft, - upperCenter, - upperRight, - middleLeft, - middleRight, - bottomLeft, - bottomCenter, - bottomRight + UPPERLEFT, + UPPERCENTER, + UPPERRIGHT, + MIDDLELEFT, + MIDDLERIGHT, + BOTTOMLEFT, + BOTTOMCENTER, + BOTTOMRIGHT, }; - enum notification_shape_t + enum class NotificationShape { - notification_shape_rounded, - notification_shape_squared, + ROUNDED, + SQUARED, }; - struct notification_t + struct Notification { - std::unique_ptr texture; - std::unique_ptr sprite; + Texture *texture; + Sprite *sprite; std::string text1; std::string text2; int counter; - notification_state_e state; - notification_position_e position; + NotificationStatus status; + NotificationPosition position; + NotificationShape shape; SDL_Rect rect; int y; int travelDist; - notification_shape_t shape; - - // Constructor - notification_t(std::unique_ptr texture, std::unique_ptr sprite) - : texture(std::move(texture)), sprite(std::move(sprite)) {} - - // Constructor de movimiento - notification_t(notification_t &&other) noexcept - : texture(std::move(other.texture)), sprite(std::move(other.sprite)) - { - // Mover otros miembros si es necesario - } - - // Operador de asignación por movimiento - notification_t &operator=(notification_t &&other) noexcept - { - if (this != &other) - { - texture = std::move(other.texture); - sprite = std::move(other.sprite); - // Mover otros miembros si es necesario - } - return *this; - } - - // Deshabilitar el constructor de copia y operador de asignación por copia - notification_t(const notification_t &) = delete; - notification_t &operator=(const notification_t &) = delete; }; // Objetos y punteros @@ -89,12 +62,12 @@ private: std::unique_ptr text; // Objeto para dibujar texto // Variables - color_t bgColor; // Color de fondo de las notificaciones - int waitTime; // Tiempo que se ve la notificación - std::vector notifications; // La lista de notificaciones activas - JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación - bool stack; // Indica si las notificaciones se apilan - bool hasIcons; // Indica si el notificador tiene textura para iconos + color_t bgColor; // Color de fondo de las notificaciones + int waitTime; // Tiempo que se ve la notificación + std::vector notifications; // La lista de notificaciones activas + JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación + bool stack; // Indica si las notificaciones se apilan + bool hasIcons; // Indica si el notificador tiene textura para iconos // Elimina las notificaciones finalizadas void clearFinishedNotifications(); diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index cc428ce..cf31388 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -3,6 +3,8 @@ #include // for SDL_PIXELFORMAT_RGBA8888 #include // for SDL_GetTicks #include // for roundf +#include +#include #include "asset.h" // for Asset #include "lang.h" // for getText #include "sprite.h" // for Sprite @@ -96,44 +98,11 @@ Scoreboard::~Scoreboard() } // Transforma un valor numérico en una cadena de 6 cifras -std::string Scoreboard::updateScoreText(Uint32 num) +std::string Scoreboard::updateScoreText(int num) { - if ((num >= 0) && (num <= 9)) - { - return ("000000" + std::to_string(num)); - } - - if ((num >= 10) && (num <= 99)) - { - return ("00000" + std::to_string(num)); - } - - if ((num >= 100) && (num <= 999)) - { - return ("0000" + std::to_string(num)); - } - - if ((num >= 1000) && (num <= 9999)) - { - return ("000" + std::to_string(num)); - } - - if ((num >= 010000) && (num <= 99999)) - { - return ("00" + std::to_string(num)); - } - - if ((num >= 100000) && (num <= 999999)) - { - return ("0" + std::to_string(num)); - } - - if ((num >= 1000000) && (num <= 9999999)) - { - return (std::to_string(num)); - } - - return (std::to_string(num)); + std::ostringstream oss; + oss << std::setw(8) << std::setfill('0') << num; + return oss.str(); } // Actualiza el contador diff --git a/source/scoreboard.h b/source/scoreboard.h index 7004255..ae9fe59 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -80,7 +80,7 @@ private: void recalculateAnchors(); // Transforma un valor numérico en una cadena de 6 cifras - std::string updateScoreText(Uint32 num); + std::string updateScoreText(int num); // Crea la textura de fondo void createBackgroundTexture();