From 5df85e1b1ac3aadd1032f9debc6d187a30f46b42 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Tue, 22 Oct 2024 09:24:19 +0200 Subject: [PATCH] Pasaeta de cppcheck, ale --- source/animated_sprite.cpp | 13 ++--- source/asset.cpp | 21 +++---- source/background.cpp | 2 +- source/balloon_formations.h | 2 +- source/director.cpp | 4 +- source/director.h | 3 +- source/explosions.cpp | 2 +- source/explosions.h | 4 +- source/game.cpp | 40 +++++++------ source/game.h | 2 +- source/hiscore_table.cpp | 2 +- source/intro.cpp | 2 +- source/logo.cpp | 20 +++---- source/manage_hiscore_table.cpp | 29 +++++---- source/notifier.cpp | 6 +- source/notifier.h | 4 +- source/options.cpp | 12 ++-- source/param.cpp | 3 +- source/resource.cpp | 100 ++++++++++++-------------------- source/resource.h | 2 +- source/scoreboard.cpp | 2 +- source/screen.cpp | 7 +-- source/screen.h | 2 +- source/text.cpp | 7 +-- source/texture.cpp | 14 ++--- source/title.cpp | 2 +- source/utils.cpp | 39 +++++++------ source/utils.h | 12 ++-- 28 files changed, 164 insertions(+), 194 deletions(-) diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index ec5787d..8dbbebd 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -260,12 +260,9 @@ std::vector AnimatedSprite::loadFromFile(const std::string &file_path { // Inicializa variables std::vector animations; - auto frames_per_row = 0; auto frame_width = 0; auto frame_height = 0; - auto max_tiles = 0; - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); std::ifstream file(file_path); std::string line; @@ -273,9 +270,11 @@ std::vector AnimatedSprite::loadFromFile(const std::string &file_path if (file.good()) { // Procesa el fichero linea a linea - std::cout << "Animation loaded: " << file_name << std::endl; + std::cout << "Animation loaded: " << getFileName(file_path) << std::endl; while (std::getline(file, line)) { + auto max_tiles = 0; + auto frames_per_row = 0; // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación if (line == "[animation]") { @@ -324,7 +323,7 @@ std::vector AnimatedSprite::loadFromFile(const std::string &file_path else { - std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; + std::cout << "Warning: file " << getFileName(file_path).c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } } } while (line != "[/animation]"); @@ -359,7 +358,7 @@ std::vector AnimatedSprite::loadFromFile(const std::string &file_path else { - std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; + std::cout << "Warning: file " << getFileName(file_path).c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; } // Normaliza valores @@ -384,7 +383,7 @@ std::vector AnimatedSprite::loadFromFile(const std::string &file_path // El fichero no se puede abrir else { - std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl; + std::cout << "Warning: Unable to open " << getFileName(file_path).c_str() << " file" << std::endl; } // Pone un valor por defecto diff --git a/source/asset.cpp b/source/asset.cpp index 54d8b3d..95238f0 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -4,6 +4,8 @@ #include // for SDL_max #include // for size_t #include // for basic_ostream, operator<<, cout, endl +#include +#include // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado Asset *Asset::asset_ = nullptr; @@ -42,8 +44,7 @@ void Asset::add(const std::string &file, AssetType type, bool required, bool abs ai.required = required; file_list_.push_back(ai); - const std::string file_name = file.substr(file.find_last_of("\\/") + 1); - longest_name_ = SDL_max(longest_name_, file_name.size()); + longest_name_ = SDL_max(longest_name_, getFileName(file).size()); } // Devuelve el fichero de un elemento de la lista a partir de una cadena @@ -114,20 +115,12 @@ bool Asset::check() const // Comprueba que existe un fichero bool Asset::checkFile(const std::string &path) const { - auto success = false; + std::ifstream file(path); + bool success = file.good(); + file.close(); - // Comprueba si existe el fichero - auto file = SDL_RWFromFile(path.c_str(), "rb"); - - if (file) - { - success = true; - SDL_RWclose(file); - } - - const std::string file_name = path.substr(path.find_last_of("\\/") + 1); if (!success) - printWithDots("Checking file : ", file_name, (success ? " [ OK ]" : " [ ERROR ]")); + printWithDots("Checking file : ", getFileName(path), "[ ERROR ]"); return success; } diff --git a/source/background.cpp b/source/background.cpp index 9ad7daf..956fecc 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -29,7 +29,7 @@ Background::Background() src_rect_({0, 0, 320, 240}), dst_rect_({0, 0, 320, 240}), base_(rect_.h), - color_({param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b}), + color_(Color(param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b)), alpha_color_text_(param.background.attenuate_alpha), alpha_color_text_temp_(param.background.attenuate_alpha) diff --git a/source/balloon_formations.h b/source/balloon_formations.h index 936fafa..fc1a05a 100644 --- a/source/balloon_formations.h +++ b/source/balloon_formations.h @@ -13,7 +13,7 @@ struct BalloonFormationParams int creation_counter = 0; // Temporizador para la creación del enemigo // Constructor que inicializa todos los campos con valores proporcionados o predeterminados - BalloonFormationParams(int x_val = 0, int y_val = 0, float vel_x_val = 0.0f, int kind_val = 0, int creation_counter_val = 0) + explicit BalloonFormationParams(int x_val = 0, int y_val = 0, float vel_x_val = 0.0f, int kind_val = 0, int creation_counter_val = 0) : x(x_val), y(y_val), vel_x(vel_x_val), kind(kind_val), creation_counter(creation_counter_val) {} }; diff --git a/source/director.cpp b/source/director.cpp index 735ca64..6d9e522 100644 --- a/source/director.cpp +++ b/source/director.cpp @@ -752,6 +752,7 @@ std::string Director::getLangFile(lang::Code code) return Asset::get()->get("en_UK.txt"); } +#ifdef ARCADE // Apaga el sistema void Director::shutdownSystem() { @@ -768,4 +769,5 @@ void Director::shutdownSystem() // Sistema operativo no compatible #error "Sistema operativo no soportado" #endif -} \ No newline at end of file +} +#endif //ARCADE \ No newline at end of file diff --git a/source/director.h b/source/director.h index 061944c..ec6d5e8 100644 --- a/source/director.h +++ b/source/director.h @@ -70,9 +70,10 @@ private: // Obtiene una fichero a partir de un lang::Code std::string getLangFile(lang::Code code); - +#ifdef ARCADE // Apaga el sistema void shutdownSystem(); +#endif public: // Constructor diff --git a/source/explosions.cpp b/source/explosions.cpp index 0a56c35..cdbb3db 100644 --- a/source/explosions.cpp +++ b/source/explosions.cpp @@ -38,7 +38,7 @@ void Explosions::render() } // Añade texturas al objeto -void Explosions::addTexture(int size, std::shared_ptr texture, std::vector &animation) +void Explosions::addTexture(int size, std::shared_ptr texture, const std::vector &animation) { textures_.emplace_back(ExplosionTexture(size, texture, animation)); } diff --git a/source/explosions.h b/source/explosions.h index 9e2f178..98ae8d3 100644 --- a/source/explosions.h +++ b/source/explosions.h @@ -13,7 +13,7 @@ struct ExplosionTexture std::vector animation; // Animación para la textura // Constructor - ExplosionTexture(int sz, std::shared_ptr tex, std::vector anim) + ExplosionTexture(int sz, std::shared_ptr tex, const std::vector &anim) : size(sz), texture(tex), animation(anim) {} }; @@ -45,7 +45,7 @@ public: void render(); // Añade texturas al objeto - void addTexture(int size, std::shared_ptr texture, std::vector &animation); + void addTexture(int size, std::shared_ptr texture, const std::vector &animation); // Añade una explosión void add(int x, int y, int size); diff --git a/source/game.cpp b/source/game.cpp index 2cc4680..b1f8401 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -194,10 +194,12 @@ Game::Game(int player_id, int current_stage, bool demo) if (demo_.enabled) { // Selecciona una pantalla al azar - constexpr auto demos = 3; - const auto demo = rand() % demos; - const int stages[demos] = {0, 3, 5}; - current_stage_ = stages[demo]; + { + constexpr auto demos = 3; + const auto demo = rand() % demos; + const int stages[demos] = {0, 3, 5}; + current_stage_ = stages[demo]; + } // Actualiza el numero de globos explotados según la fase de la demo for (int i = 0; i < current_stage_; ++i) @@ -2007,26 +2009,28 @@ void Game::checkPlayersStatusPlaying() // Obtiene un jugador a partir de su "id" std::shared_ptr Game::getPlayer(int id) { - for (const auto &player : players_) - { - if (player->getId() == id) - { - return player; - } - } + auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player) + { return player->getId() == id; }); + if (it != players_.end()) + { + return *it; + } return nullptr; } // Obtiene un controlador a partir del "id" del jugador int Game::getController(int player_id) { - for (int i = 0; i < (int)options.controller.size(); ++i) + auto it = std::find_if(options.controller.begin(), options.controller.end(), + [player_id](const auto &controller) + { + return controller.player_id == player_id; + }); + + if (it != options.controller.end()) { - if (options.controller[i].player_id == player_id) - { - return i; - } + return std::distance(options.controller.begin(), it); } return -1; @@ -2067,7 +2071,7 @@ void Game::checkPauseInput() void Game::handleDemoMode() { int i = 0; - for (auto &player : players_) + for (const auto &player : players_) { if (player->isPlaying()) { @@ -2119,7 +2123,7 @@ void Game::handleFireInput(const std::shared_ptr &player, BulletType bul // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo). void Game::handlePlayersInput() { - for (auto &player : players_) + for (const auto &player : players_) { if (player->isPlaying()) { diff --git a/source/game.h b/source/game.h index 5e9be12..1634251 100644 --- a/source/game.h +++ b/source/game.h @@ -78,7 +78,7 @@ private: int item_coffee_machine_odds; // Probabilidad de aparición del objeto // Constructor con valores predeterminados - Helper(bool nc = false, bool ncm = false, bool npb = false, int c = 0, int ido = 0, int igo = 0, int ipo = 0, int ico = 0, int icoffo = 0, int icmo = 0) + explicit Helper(bool nc = false, bool ncm = false, bool npb = false, int c = 0, int ido = 0, int igo = 0, int ipo = 0, int ico = 0, int icoffo = 0, int icmo = 0) : need_coffee(nc), need_coffee_machine(ncm), need_power_ball(npb), counter(c), item_disk_odds(ido), item_gavina_odds(igo), item_pacmar_odds(ipo), item_clock_odds(ico), item_coffee_odds(icoffo), item_coffee_machine_odds(icmo) {} diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index f7572c1..001b067 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -87,7 +87,7 @@ void HiScoreTable::update() if (counter_ == 150) { - background_->setColor({0, 0, 0}); + background_->setColor(Color(0, 0, 0)); background_->setAlpha(96); } diff --git a/source/intro.cpp b/source/intro.cpp index 34b2eea..d383a5b 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -21,9 +21,9 @@ struct JA_Music_t; // lines 19-19 // Constructor Intro::Intro() + : texture_(Resource::get()->getTexture("intro.png")) { // Reserva memoria para los objetos - texture_ = Resource::get()->getTexture("intro.png"); text_ = std::make_shared(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt")); // Inicializa variables diff --git a/source/logo.cpp b/source/logo.cpp index 0777ede..8919c41 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -19,13 +19,13 @@ Logo::Logo() : since_texture_(Resource::get()->getTexture("logo_since_1998.png")), since_sprite_(std::make_unique(since_texture_)), - jail_texture_(Resource::get()->getTexture("logo_jailgames.png")) + jail_texture_(Resource::get()->getTexture("logo_jailgames.png")), + ticks_(0) { // Inicializa variables counter_ = 0; section::name = section::Name::LOGO; - ticks_ = 0; dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2; dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2; since_sprite_->setPosition({(param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight()}); @@ -45,14 +45,14 @@ Logo::Logo() } // Inicializa el vector de colores - color_.push_back({0x00, 0x00, 0x00}); // Black - color_.push_back({0x00, 0x00, 0xd8}); // Blue - color_.push_back({0xd8, 0x00, 0x00}); // Red - color_.push_back({0xd8, 0x00, 0xd8}); // Magenta - color_.push_back({0x00, 0xd8, 0x00}); // Green - color_.push_back({0x00, 0xd8, 0xd8}); // Cyan - color_.push_back({0xd8, 0xd8, 0x00}); // Yellow - color_.push_back({0xFF, 0xFF, 0xFF}); // Bright white + color_.push_back(Color(0x00, 0x00, 0x00)); // Black + color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue + color_.push_back(Color(0xd8, 0x00, 0x00)); // Red + color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta + color_.push_back(Color(0x00, 0xd8, 0x00)); // Green + color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan + color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow + color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white } // Recarga todas las texturas diff --git a/source/manage_hiscore_table.cpp b/source/manage_hiscore_table.cpp index 80ecf96..f29d636 100644 --- a/source/manage_hiscore_table.cpp +++ b/source/manage_hiscore_table.cpp @@ -13,16 +13,16 @@ void ManageHiScoreTable::clear() table_.clear(); // Añade 10 entradas predefinidas - table_.push_back({"Bry", 1000000}); - table_.push_back({"Usufondo", 500000}); - table_.push_back({"G.Lucas", 100000}); - table_.push_back({"P.Delgat", 50000}); - table_.push_back({"P.Arrabalera", 10000}); - table_.push_back({"Pelechano", 5000}); - table_.push_back({"Sahuquillo", 1000}); - table_.push_back({"Bacteriol", 500}); - table_.push_back({"Pepe", 200}); - table_.push_back({"Rosita", 100}); + table_.push_back(HiScoreEntry("Bry", 1000000)); + table_.push_back(HiScoreEntry("Usufondo", 500000)); + table_.push_back(HiScoreEntry("G.Lucas", 100000)); + table_.push_back(HiScoreEntry("P.Delgat", 50000)); + table_.push_back(HiScoreEntry("P.Arrabalera", 10000)); + table_.push_back(HiScoreEntry("Pelechano", 5000)); + table_.push_back(HiScoreEntry("Sahuquillo", 1000)); + table_.push_back(HiScoreEntry("Bacteriol", 500)); + table_.push_back(HiScoreEntry("Pepe", 200)); + table_.push_back(HiScoreEntry("Rosita", 100)); } // Añade un elemento a la tabla @@ -61,8 +61,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) if (file) { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); - std::cout << "Reading file: " << file_name << std::endl; + std::cout << "Reading file: " << getFileName(file_path) << std::endl; for (auto &entry : table_) { @@ -105,7 +104,6 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path) // Guarda la tabla en un fichero bool ManageHiScoreTable::saveToFile(const std::string &file_path) { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); auto success = true; auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); @@ -120,13 +118,12 @@ bool ManageHiScoreTable::saveToFile(const std::string &file_path) SDL_RWwrite(file, table_.at(i).name.c_str(), nameSize, 1); } - std::cout << "Writing file: " << file_name.c_str() << std::endl; - // Cierra el fichero + std::cout << "Writing file: " << getFileName(file_path).c_str() << std::endl; SDL_RWclose(file); } else { - std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl; + std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl; } return success; } \ No newline at end of file diff --git a/source/notifier.cpp b/source/notifier.cpp index ddf3103..9a01dc4 100644 --- a/source/notifier.cpp +++ b/source/notifier.cpp @@ -14,7 +14,7 @@ Notifier *Notifier::notifier_ = nullptr; // [SINGLETON] Crearemos el objeto screen con esta función estática -void Notifier::init(std::string icon_file, std::shared_ptr text, const std::string &sound_file) +void Notifier::init(const std::string &icon_file, std::shared_ptr text, const std::string &sound_file) { Notifier::notifier_ = new Notifier(icon_file, text, sound_file); } @@ -165,7 +165,7 @@ void Notifier::clearFinishedNotifications() } } -void Notifier::showText(std::string text1, std::string text2, int icon, std::string code) +void Notifier::showText(std::string text1, std::string text2, int icon, const std::string &code) { // Cuenta el número de textos a mostrar const int num_texts = !text1.empty() + !text2.empty(); @@ -286,7 +286,7 @@ void Notifier::showText(std::string text1, std::string text2, int icon, std::str } // Escribe el texto de la notificación - Color color = {255, 255, 255}; + Color color{255, 255, 255}; if (num_texts == 2) { // Dos lineas de texto text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color); diff --git a/source/notifier.h b/source/notifier.h index 4527fbf..1c7befd 100644 --- a/source/notifier.h +++ b/source/notifier.h @@ -89,7 +89,7 @@ private: public: // [SINGLETON] Crearemos el objeto notifier con esta función estática - static void init(std::string icon_file, std::shared_ptr text, const std::string &sound_file); + static void init(const std::string &icon_file, std::shared_ptr text, const std::string &sound_file); // [SINGLETON] Destruiremos el objeto notifier con esta función estática static void destroy(); @@ -111,7 +111,7 @@ public: * @param icon Icono opcional para mostrar (valor predeterminado: -1). * @param code Permite asignar un código a la notificación (valor predeterminado: cadena vacía). */ - void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, std::string code = std::string()); + void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, const std::string &code = std::string()); // Indica si hay notificaciones activas bool isActive(); diff --git a/source/options.cpp b/source/options.cpp index 657611d..d5026a2 100644 --- a/source/options.cpp +++ b/source/options.cpp @@ -86,14 +86,13 @@ bool loadOptionsFile(std::string file_path) bool success = true; // Variables para manejar el fichero - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); std::ifstream file(file_path); // Si el fichero se puede abrir if (file.good()) { // Procesa el fichero linea a linea - std::cout << "Reading file: " << file_name << std::endl; + std::cout << "Reading file: " << getFileName(file_path) << std::endl; std::string line; while (std::getline(file, line)) { @@ -105,14 +104,12 @@ bool loadOptionsFile(std::string file_path) // Procesa las dos subcadenas if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length()))) { - std::cout << "Warning: file " << file_name << std::endl; + std::cout << "Warning: file " << getFileName(file_path) << std::endl; std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl; success = false; } } } - - // Cierra el fichero file.close(); } @@ -146,16 +143,15 @@ bool loadOptionsFile(std::string file_path) // Guarda el fichero de configuración bool saveOptionsFile(std::string file_path) { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); std::ofstream file(file_path); if (!file.good()) { - std::cout << file_name << " can't be opened" << std::endl; + std::cout << getFileName(file_path) << " can't be opened" << std::endl; return false; } - std::cout << "Writing file: " << file_name << std::endl; + std::cout << "Writing file: " << getFileName(file_path) << std::endl; // Opciones de video const auto value_video_mode_winow = std::to_string(static_cast(ScreenVideoMode::WINDOW)); diff --git a/source/param.cpp b/source/param.cpp index 41accd5..8e0fbd0 100644 --- a/source/param.cpp +++ b/source/param.cpp @@ -78,8 +78,7 @@ void loadParamsFromFile(const std::string &file_path) throw std::runtime_error("No se pudo abrir el archivo: " + file_path); } - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); - std::cout << "Reading file: " << file_name << std::endl; + std::cout << "Reading file: " << getFileName(file_path) << std::endl; std::string line, param1, param2; while (std::getline(file, line)) diff --git a/source/resource.cpp b/source/resource.cpp index 931c908..51746ce 100644 --- a/source/resource.cpp +++ b/source/resource.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include "resource.h" #include "asset.h" @@ -51,13 +53,14 @@ Resource::~Resource() // Obtiene el sonido a partir de un nombre JA_Sound_t *Resource::getSound(const std::string &name) { - for (const auto &s : sounds_) + auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s) + { return s.name == name; }); + + if (it != sounds_.end()) { - if (s.name == name) - { - return s.sound; - } + return it->sound; } + std::cerr << "Error: Sonido no encontrado " << name << std::endl; throw std::runtime_error("Sonido no encontrado: " + name); } @@ -65,13 +68,14 @@ JA_Sound_t *Resource::getSound(const std::string &name) // Obtiene la música a partir de un nombre JA_Music_t *Resource::getMusic(const std::string &name) { - for (const auto &m : musics_) + auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m) + { return m.name == name; }); + + if (it != musics_.end()) { - if (m.name == name) - { - return m.music; - } + return it->music; } + std::cerr << "Error: Música no encontrada " << name << std::endl; throw std::runtime_error("Música no encontrada: " + name); } @@ -79,13 +83,14 @@ JA_Music_t *Resource::getMusic(const std::string &name) // Obtiene la textura a partir de un nombre std::shared_ptr Resource::getTexture(const std::string &name) { - for (const auto &t : textures_) + auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t) + { return t.name == name; }); + + if (it != textures_.end()) { - if (t.name == name) - { - return t.texture; - } + return it->texture; } + std::cerr << "Error: Imagen no encontrada " << name << std::endl; throw std::runtime_error("Imagen no encontrada: " + name); } @@ -93,13 +98,14 @@ std::shared_ptr Resource::getTexture(const std::string &name) // Obtiene el fichero de texto a partir de un nombre std::shared_ptr Resource::getTextFile(const std::string &name) { - for (const auto &t : text_files_) + auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t) + { return t.name == name; }); + + if (it != text_files_.end()) { - if (t.name == name) - { - return t.text_file; - } + return it->text_file; } + std::cerr << "Error: TextFile no encontrado " << name << std::endl; throw std::runtime_error("TextFile no encontrado: " + name); } @@ -107,13 +113,14 @@ std::shared_ptr Resource::getTextFile(const std::string &name) // Obtiene la animación a partir de un nombre Animations &Resource::getAnimation(const std::string &name) { - for (auto &a : animations_) + auto it = std::find_if(animations_.begin(), animations_.end(), [&name](auto &a) + { return a.name == name; }); + + if (it != animations_.end()) { - if (a.name == name) - { - return a.animation; - } + return it->animation; } + std::cerr << "Error: Animación no encontrada " << name << std::endl; throw std::runtime_error("Animación no encontrada: " + name); } @@ -128,19 +135,12 @@ DemoData &Resource::getDemoData(int index) void Resource::loadSounds() { std::cout << "\n>> SOUND FILES" << std::endl; - - // Obtiene la lista con las rutas a los ficheros de sonidos auto list = Asset::get()->getListByType(AssetType::SOUND); sounds_.clear(); for (const auto &l : list) { - // Encuentra el último índice de '/' - auto last_index = l.find_last_of('/') + 1; - - // Obtiene la subcadena desde el último '/' - auto name = l.substr(last_index); - + auto name = getFileName(l); sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str()))); printWithDots("Sound : ", name, "[ LOADED ]"); } @@ -150,19 +150,12 @@ void Resource::loadSounds() void Resource::loadMusics() { std::cout << "\n>> MUSIC FILES" << std::endl; - - // Obtiene la lista con las rutas a los ficheros musicales auto list = Asset::get()->getListByType(AssetType::MUSIC); musics_.clear(); for (const auto &l : list) { - // Encuentra el último índice de '/' - auto last_index = l.find_last_of('/') + 1; - - // Obtiene la subcadena desde el último '/' - auto name = l.substr(last_index); - + auto name = getFileName(l); musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str()))); printWithDots("Music : ", name, "[ LOADED ]"); } @@ -172,19 +165,12 @@ void Resource::loadMusics() void Resource::loadTextures() { std::cout << "\n>> TEXTURES" << std::endl; - - // Obtiene la lista con las rutas a los ficheros png auto list = Asset::get()->getListByType(AssetType::BITMAP); textures_.clear(); for (const auto &l : list) { - // Encuentra el último índice de '/' - auto last_index = l.find_last_of('/') + 1; - - // Obtiene la subcadena desde el último '/' - auto name = l.substr(last_index); - + auto name = getFileName(l); textures_.emplace_back(ResourceTexture(name, std::make_shared(Screen::get()->getRenderer(), l))); } } @@ -193,18 +179,12 @@ void Resource::loadTextures() void Resource::loadTextFiles() { std::cout << "\n>> TEXT FILES" << std::endl; - // Obtiene la lista con las rutas a los ficheros png auto list = Asset::get()->getListByType(AssetType::FONT); text_files_.clear(); for (const auto &l : list) { - // Encuentra el último índice de '/' - auto last_index = l.find_last_of('/') + 1; - - // Obtiene la subcadena desde el último '/' - auto name = l.substr(last_index); - + auto name = getFileName(l); text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l))); } } @@ -213,18 +193,12 @@ void Resource::loadTextFiles() void Resource::loadAnimations() { std::cout << "\n>> ANIMATIONS" << std::endl; - // Obtiene la lista con las rutas a los ficheros ani auto list = Asset::get()->getListByType(AssetType::ANIMATION); animations_.clear(); for (const auto &l : list) { - // Encuentra el último índice de '/' - auto last_index = l.find_last_of('/') + 1; - - // Obtiene la subcadena desde el último '/' - auto name = l.substr(last_index); - + auto name = getFileName(l); animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); } } diff --git a/source/resource.h b/source/resource.h index 502d454..f46ce17 100644 --- a/source/resource.h +++ b/source/resource.h @@ -61,7 +61,7 @@ struct ResourceAnimation Animations animation; // Objeto con las animaciones // Constructor - ResourceAnimation(const std::string &name, Animations animation) + ResourceAnimation(const std::string &name, const Animations &animation) : name(name), animation(animation) {} }; diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 585117d..18d2f66 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -46,7 +46,7 @@ Scoreboard::Scoreboard() hi_score_(0), power_(0), hi_score_name_(std::string()), - color_({0, 0, 0}), + color_(Color(0, 0, 0)), rect_({0, 0, 320, 40}), ticks_(SDL_GetTicks()), counter_(0) diff --git a/source/screen.cpp b/source/screen.cpp index 23453cb..d7d7c18 100644 --- a/source/screen.cpp +++ b/source/screen.cpp @@ -52,7 +52,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) src_rect_({0, 0, param.game.width, param.game.height}), dst_rect_({0, 0, param.game.width, param.game.height}), - border_color_({0x00, 0x00, 0x00}), + border_color_(Color(0x00, 0x00, 0x00)), attenuate_effect_(false), fps_ticks_(0), fps_counter_(0), @@ -67,7 +67,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) flash_effect_.enabled = false; flash_effect_.counter = 0; flash_effect_.lenght = 0; - flash_effect_.color = {0xFF, 0xFF, 0xFF}; + flash_effect_.color = Color(0xFF, 0xFF, 0xFF); shake_effect_.enabled = false; shake_effect_.desp = 2; shake_effect_.delay = 3; @@ -481,8 +481,7 @@ void Screen::displayInfo() dbg_print(0, 0, info_resolution_.c_str(), 255, 255, 0); // Contador de service_pressed_counter - const int counter = globalInputs::service_pressed_counter[0]; - if (counter > 0) + if (const int counter = globalInputs::service_pressed_counter[0]; counter > 0) dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255); } } diff --git a/source/screen.h b/source/screen.h index 7a21884..f25e397 100644 --- a/source/screen.h +++ b/source/screen.h @@ -111,7 +111,7 @@ public: void checkInput(); // Limpia la pantalla - void clean(Color color = {0x00, 0x00, 0x00}); + void clean(Color color = Color(0x00, 0x00, 0x00)); // Prepara para empezar a dibujar en la textura de juego void start(); diff --git a/source/text.cpp b/source/text.cpp index 47f0998..3b59a3f 100644 --- a/source/text.cpp +++ b/source/text.cpp @@ -23,7 +23,6 @@ std::shared_ptr loadTextFile(const std::string &file_path) } // Abre el fichero para leer los valores - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str(); std::ifstream file(file_path); if (file.is_open() && file.good()) @@ -56,15 +55,15 @@ std::shared_ptr loadTextFile(const std::string &file_path) }; // Cierra el fichero - printWithDots("Text File : ", file_name, "[ LOADED ]"); + printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]"); file.close(); } // El fichero no se puede abrir else { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; - throw std::runtime_error("Fichero no encontrado: " + file_path); + std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } // Establece las coordenadas para cada caracter ascii de la cadena y su ancho diff --git a/source/texture.cpp b/source/texture.cpp index 21dd582..4191add 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -69,13 +69,12 @@ bool Texture::loadFromFile(const std::string &file_path) unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format); if (!data) { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; - throw std::runtime_error("Fichero no encontrado: " + file_path); + std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } else { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); - printWithDots("Image : ", file_name, "[ LOADED ]"); + printWithDots("Image : ", getFileName(file_path), "[ LOADED ]"); } int depth, pitch; @@ -320,13 +319,12 @@ std::vector Texture::loadPaletteFromFile(const std::string &file_path) FILE *f = fopen(file_path.c_str(), "rb"); if (!f) { - std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; - throw std::runtime_error("Fichero no encontrado: " + file_path); + std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl; + throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path)); } else { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); - printWithDots("Image : ", file_name, "[ LOADED ]"); + printWithDots("Image : ", getFileName(file_path), "[ LOADED ]"); } fseek(f, 0, SEEK_END); diff --git a/source/title.cpp b/source/title.cpp index f948ff2..7d3cd1e 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -138,7 +138,7 @@ void Title::render() if (section::options == section::Options::TITLE_2) { - constexpr Color shadow = {0x14, 0x87, 0xc4}; + constexpr Color shadow = Color(0x14, 0x87, 0xc4); // 'PRESS TO PLAY' if (counter_ % 50 > 14 && !define_buttons_->isEnabled()) diff --git a/source/utils.cpp b/source/utils.cpp index b572a79..4de79b9 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -1,4 +1,5 @@ #include "utils.h" +#include #include #include #include // for min, clamp, find_if_not, transform @@ -12,16 +13,16 @@ struct JA_Sound_t; // lines 8-8 Overrides overrides = Overrides(); // Colores -const Color bg_color = {0x27, 0x27, 0x36}; -const Color no_color = {0xFF, 0xFF, 0xFF}; -const Color shdw_txt_color = {0x43, 0x43, 0x4F}; -const Color separator_color = {0x0D, 0x1A, 0x2B}; -const Color scoreboard_easy_color = {0x4B, 0x69, 0x2F}; -const Color scoreboard_normal_color = {0x2E, 0x3F, 0x47}; -const Color scoreboard_hard_color = {0x76, 0x42, 0x8A}; -const Color flash_color = {0xFF, 0xFF, 0xFF}; -const Color fade_color = {0x27, 0x27, 0x36}; -const Color orange_color = {0xFF, 0x7A, 0x00}; +const Color bg_color = Color(0x27, 0x27, 0x36); +const Color no_color = Color(0xFF, 0xFF, 0xFF); +const Color shdw_txt_color = Color(0x43, 0x43, 0x4F); +const Color separator_color = Color(0x0D, 0x1A, 0x2B); +const Color scoreboard_easy_color = Color(0x4B, 0x69, 0x2F); +const Color scoreboard_normal_color = Color(0x2E, 0x3F, 0x47); +const Color scoreboard_hard_color = Color(0x76, 0x42, 0x8A); +const Color flash_color = Color(0xFF, 0xFF, 0xFF); +const Color fade_color = Color(0x27, 0x27, 0x36); +const Color orange_color = Color(0xFF, 0x7A, 0x00); // Calcula el cuadrado de la distancia entre dos puntos double distanceSquared(int x1, int y1, int x2, int y2) @@ -220,8 +221,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path) } else { - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); - printWithDots("DemoData : ", file_name, "[ LOADED ]"); + printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]"); // Lee todos los datos del fichero y los deja en el destino for (int i = 0; i < TOTAL_DEMO_DATA; ++i) @@ -243,7 +243,6 @@ DemoData loadDemoDataFromFile(const std::string &file_path) bool saveDemoFile(const std::string &file_path, const DemoData &dd) { auto success = true; - const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); if (file) @@ -253,24 +252,30 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd) { if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1) { - std::cerr << "Error al escribir el fichero " << file_name << std::endl; + std::cerr << "Error al escribir el fichero " << getFileName(file_path) << std::endl; success = false; break; } } if (success) { - std::cout << "Writing file " << file_name.c_str() << std::endl; + std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl; } // Cierra el fichero SDL_RWclose(file); } else { - std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl; + std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl; success = false; } return success; } -#endif // RECORDING \ No newline at end of file +#endif // RECORDING + +// Obtiene el nombre de un fichero a partir de una ruta +std::string getFileName(const std::string &path) +{ + return std::filesystem::path(path).filename().string(); +} diff --git a/source/utils.h b/source/utils.h index 5300c35..44448be 100644 --- a/source/utils.h +++ b/source/utils.h @@ -53,7 +53,8 @@ struct Circle struct Color { Uint8 r, g, b; - constexpr Color(int red = 255, int green = 255, int blue = 255) : r(red), g(green), b(blue) {} + constexpr Color() : r(0), g(0), b(0) {} + explicit constexpr Color(int red, int green, int blue) : r(red), g(green), b(blue) {} }; // Posiciones de las notificaciones @@ -72,8 +73,8 @@ struct HiScoreEntry std::string name; // Nombre int score; // Puntuación -// Constructor - HiScoreEntry(const std::string &n = "", int s = 0) + // Constructor + explicit HiScoreEntry(const std::string &n = "", int s = 0) : name(n), score(s) {} }; @@ -87,7 +88,7 @@ struct DemoKeys Uint8 fire_right; // Constructor que inicializa todos los campos - DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0) + explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0) : left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {} }; @@ -315,6 +316,9 @@ DemoData loadDemoDataFromFile(const std::string &file_path); bool saveDemoFile(const std::string &file_path, const DemoData &dd); #endif +// Obtiene el nombre de un fichero a partir de una ruta +std::string getFileName(const std::string &path); + // Colores extern const Color bg_color; extern const Color no_color;