Pasaeta de cppcheck, ale

This commit is contained in:
2024-10-22 09:24:19 +02:00
parent 1d0c2e01a5
commit 5df85e1b1a
28 changed files with 164 additions and 194 deletions

View File

@@ -260,12 +260,9 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
{ {
// Inicializa variables // Inicializa variables
std::vector<Animation> animations; std::vector<Animation> animations;
auto frames_per_row = 0;
auto frame_width = 0; auto frame_width = 0;
auto frame_height = 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::ifstream file(file_path);
std::string line; std::string line;
@@ -273,9 +270,11 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // 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)) 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 // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") if (line == "[animation]")
{ {
@@ -324,7 +323,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
else 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]"); } while (line != "[/animation]");
@@ -359,7 +358,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
else 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 // Normaliza valores
@@ -384,7 +383,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
// El fichero no se puede abrir // El fichero no se puede abrir
else 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 // Pone un valor por defecto

View File

@@ -4,6 +4,8 @@
#include <SDL2/SDL_stdinc.h> // for SDL_max #include <SDL2/SDL_stdinc.h> // for SDL_max
#include <stddef.h> // for size_t #include <stddef.h> // for size_t
#include <iostream> // for basic_ostream, operator<<, cout, endl #include <iostream> // for basic_ostream, operator<<, cout, endl
#include <fstream>
#include <string>
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset *Asset::asset_ = nullptr; Asset *Asset::asset_ = nullptr;
@@ -42,8 +44,7 @@ void Asset::add(const std::string &file, AssetType type, bool required, bool abs
ai.required = required; ai.required = required;
file_list_.push_back(ai); file_list_.push_back(ai);
const std::string file_name = file.substr(file.find_last_of("\\/") + 1); longest_name_ = SDL_max(longest_name_, getFileName(file).size());
longest_name_ = SDL_max(longest_name_, file_name.size());
} }
// Devuelve el fichero de un elemento de la lista a partir de una cadena // 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 // Comprueba que existe un fichero
bool Asset::checkFile(const std::string &path) const 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) if (!success)
printWithDots("Checking file : ", file_name, (success ? " [ OK ]" : " [ ERROR ]")); printWithDots("Checking file : ", getFileName(path), "[ ERROR ]");
return success; return success;
} }

View File

@@ -29,7 +29,7 @@ Background::Background()
src_rect_({0, 0, 320, 240}), src_rect_({0, 0, 320, 240}),
dst_rect_({0, 0, 320, 240}), dst_rect_({0, 0, 320, 240}),
base_(rect_.h), 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_(param.background.attenuate_alpha),
alpha_color_text_temp_(param.background.attenuate_alpha) alpha_color_text_temp_(param.background.attenuate_alpha)

View File

@@ -13,7 +13,7 @@ struct BalloonFormationParams
int creation_counter = 0; // Temporizador para la creación del enemigo int creation_counter = 0; // Temporizador para la creación del enemigo
// Constructor que inicializa todos los campos con valores proporcionados o predeterminados // 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) {} : x(x_val), y(y_val), vel_x(vel_x_val), kind(kind_val), creation_counter(creation_counter_val) {}
}; };

View File

@@ -752,6 +752,7 @@ std::string Director::getLangFile(lang::Code code)
return Asset::get()->get("en_UK.txt"); return Asset::get()->get("en_UK.txt");
} }
#ifdef ARCADE
// Apaga el sistema // Apaga el sistema
void Director::shutdownSystem() void Director::shutdownSystem()
{ {
@@ -768,4 +769,5 @@ void Director::shutdownSystem()
// Sistema operativo no compatible // Sistema operativo no compatible
#error "Sistema operativo no soportado" #error "Sistema operativo no soportado"
#endif #endif
} }
#endif //ARCADE

View File

@@ -70,9 +70,10 @@ private:
// Obtiene una fichero a partir de un lang::Code // Obtiene una fichero a partir de un lang::Code
std::string getLangFile(lang::Code code); std::string getLangFile(lang::Code code);
#ifdef ARCADE
// Apaga el sistema // Apaga el sistema
void shutdownSystem(); void shutdownSystem();
#endif
public: public:
// Constructor // Constructor

View File

@@ -38,7 +38,7 @@ void Explosions::render()
} }
// Añade texturas al objeto // Añade texturas al objeto
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> &animation) void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation)
{ {
textures_.emplace_back(ExplosionTexture(size, texture, animation)); textures_.emplace_back(ExplosionTexture(size, texture, animation));
} }

View File

@@ -13,7 +13,7 @@ struct ExplosionTexture
std::vector<std::string> animation; // Animación para la textura std::vector<std::string> animation; // Animación para la textura
// Constructor // Constructor
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, std::vector<std::string> anim) ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
: size(sz), texture(tex), animation(anim) {} : size(sz), texture(tex), animation(anim) {}
}; };
@@ -45,7 +45,7 @@ public:
void render(); void render();
// Añade texturas al objeto // Añade texturas al objeto
void addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> &animation); void addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
// Añade una explosión // Añade una explosión
void add(int x, int y, int size); void add(int x, int y, int size);

View File

@@ -194,10 +194,12 @@ Game::Game(int player_id, int current_stage, bool demo)
if (demo_.enabled) if (demo_.enabled)
{ {
// Selecciona una pantalla al azar // Selecciona una pantalla al azar
constexpr auto demos = 3; {
const auto demo = rand() % demos; constexpr auto demos = 3;
const int stages[demos] = {0, 3, 5}; const auto demo = rand() % demos;
current_stage_ = stages[demo]; const int stages[demos] = {0, 3, 5};
current_stage_ = stages[demo];
}
// Actualiza el numero de globos explotados según la fase de la demo // Actualiza el numero de globos explotados según la fase de la demo
for (int i = 0; i < current_stage_; ++i) for (int i = 0; i < current_stage_; ++i)
@@ -2007,26 +2009,28 @@ void Game::checkPlayersStatusPlaying()
// Obtiene un jugador a partir de su "id" // Obtiene un jugador a partir de su "id"
std::shared_ptr<Player> Game::getPlayer(int id) std::shared_ptr<Player> Game::getPlayer(int id)
{ {
for (const auto &player : players_) auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player)
{ { return player->getId() == id; });
if (player->getId() == id)
{
return player;
}
}
if (it != players_.end())
{
return *it;
}
return nullptr; return nullptr;
} }
// Obtiene un controlador a partir del "id" del jugador // Obtiene un controlador a partir del "id" del jugador
int Game::getController(int player_id) 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 std::distance(options.controller.begin(), it);
{
return i;
}
} }
return -1; return -1;
@@ -2067,7 +2071,7 @@ void Game::checkPauseInput()
void Game::handleDemoMode() void Game::handleDemoMode()
{ {
int i = 0; int i = 0;
for (auto &player : players_) for (const auto &player : players_)
{ {
if (player->isPlaying()) if (player->isPlaying())
{ {
@@ -2119,7 +2123,7 @@ void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bul
// Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo). // Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
void Game::handlePlayersInput() void Game::handlePlayersInput()
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
if (player->isPlaying()) if (player->isPlaying())
{ {

View File

@@ -78,7 +78,7 @@ private:
int item_coffee_machine_odds; // Probabilidad de aparición del objeto int item_coffee_machine_odds; // Probabilidad de aparición del objeto
// Constructor con valores predeterminados // 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), : 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_disk_odds(ido), item_gavina_odds(igo), item_pacmar_odds(ipo), item_clock_odds(ico),
item_coffee_odds(icoffo), item_coffee_machine_odds(icmo) {} item_coffee_odds(icoffo), item_coffee_machine_odds(icmo) {}

View File

@@ -87,7 +87,7 @@ void HiScoreTable::update()
if (counter_ == 150) if (counter_ == 150)
{ {
background_->setColor({0, 0, 0}); background_->setColor(Color(0, 0, 0));
background_->setAlpha(96); background_->setAlpha(96);
} }

View File

@@ -21,9 +21,9 @@ struct JA_Music_t; // lines 19-19
// Constructor // Constructor
Intro::Intro() Intro::Intro()
: texture_(Resource::get()->getTexture("intro.png"))
{ {
// Reserva memoria para los objetos // Reserva memoria para los objetos
texture_ = Resource::get()->getTexture("intro.png");
text_ = std::make_shared<Text>(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt")); text_ = std::make_shared<Text>(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt"));
// Inicializa variables // Inicializa variables

View File

@@ -19,13 +19,13 @@
Logo::Logo() Logo::Logo()
: since_texture_(Resource::get()->getTexture("logo_since_1998.png")), : since_texture_(Resource::get()->getTexture("logo_since_1998.png")),
since_sprite_(std::make_unique<Sprite>(since_texture_)), since_sprite_(std::make_unique<Sprite>(since_texture_)),
jail_texture_(Resource::get()->getTexture("logo_jailgames.png")) jail_texture_(Resource::get()->getTexture("logo_jailgames.png")),
ticks_(0)
{ {
// Inicializa variables // Inicializa variables
counter_ = 0; counter_ = 0;
section::name = section::Name::LOGO; section::name = section::Name::LOGO;
ticks_ = 0;
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2; dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2;
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 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()}); 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 // Inicializa el vector de colores
color_.push_back({0x00, 0x00, 0x00}); // Black color_.push_back(Color(0x00, 0x00, 0x00)); // Black
color_.push_back({0x00, 0x00, 0xd8}); // Blue color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
color_.push_back({0xd8, 0x00, 0x00}); // Red color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
color_.push_back({0xd8, 0x00, 0xd8}); // Magenta color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
color_.push_back({0x00, 0xd8, 0x00}); // Green color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
color_.push_back({0x00, 0xd8, 0xd8}); // Cyan color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
color_.push_back({0xd8, 0xd8, 0x00}); // Yellow color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
color_.push_back({0xFF, 0xFF, 0xFF}); // Bright white color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
} }
// Recarga todas las texturas // Recarga todas las texturas

View File

@@ -13,16 +13,16 @@ void ManageHiScoreTable::clear()
table_.clear(); table_.clear();
// Añade 10 entradas predefinidas // Añade 10 entradas predefinidas
table_.push_back({"Bry", 1000000}); table_.push_back(HiScoreEntry("Bry", 1000000));
table_.push_back({"Usufondo", 500000}); table_.push_back(HiScoreEntry("Usufondo", 500000));
table_.push_back({"G.Lucas", 100000}); table_.push_back(HiScoreEntry("G.Lucas", 100000));
table_.push_back({"P.Delgat", 50000}); table_.push_back(HiScoreEntry("P.Delgat", 50000));
table_.push_back({"P.Arrabalera", 10000}); table_.push_back(HiScoreEntry("P.Arrabalera", 10000));
table_.push_back({"Pelechano", 5000}); table_.push_back(HiScoreEntry("Pelechano", 5000));
table_.push_back({"Sahuquillo", 1000}); table_.push_back(HiScoreEntry("Sahuquillo", 1000));
table_.push_back({"Bacteriol", 500}); table_.push_back(HiScoreEntry("Bacteriol", 500));
table_.push_back({"Pepe", 200}); table_.push_back(HiScoreEntry("Pepe", 200));
table_.push_back({"Rosita", 100}); table_.push_back(HiScoreEntry("Rosita", 100));
} }
// Añade un elemento a la tabla // Añade un elemento a la tabla
@@ -61,8 +61,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
if (file) if (file)
{ {
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); std::cout << "Reading file: " << getFileName(file_path) << std::endl;
std::cout << "Reading file: " << file_name << std::endl;
for (auto &entry : table_) for (auto &entry : table_)
{ {
@@ -105,7 +104,6 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
// Guarda la tabla en un fichero // Guarda la tabla en un fichero
bool ManageHiScoreTable::saveToFile(const std::string &file_path) 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 success = true;
auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); 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); SDL_RWwrite(file, table_.at(i).name.c_str(), nameSize, 1);
} }
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); SDL_RWclose(file);
} }
else 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; return success;
} }

View File

@@ -14,7 +14,7 @@
Notifier *Notifier::notifier_ = nullptr; Notifier *Notifier::notifier_ = nullptr;
// [SINGLETON] Crearemos el objeto screen con esta función estática // [SINGLETON] Crearemos el objeto screen con esta función estática
void Notifier::init(std::string icon_file, std::shared_ptr<Text> text, const std::string &sound_file) void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text, const std::string &sound_file)
{ {
Notifier::notifier_ = new Notifier(icon_file, text, 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 // Cuenta el número de textos a mostrar
const int num_texts = !text1.empty() + !text2.empty(); 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 // Escribe el texto de la notificación
Color color = {255, 255, 255}; Color color{255, 255, 255};
if (num_texts == 2) if (num_texts == 2)
{ // Dos lineas de texto { // Dos lineas de texto
text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color); text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color);

View File

@@ -89,7 +89,7 @@ private:
public: public:
// [SINGLETON] Crearemos el objeto notifier con esta función estática // [SINGLETON] Crearemos el objeto notifier con esta función estática
static void init(std::string icon_file, std::shared_ptr<Text> text, const std::string &sound_file); static void init(const std::string &icon_file, std::shared_ptr<Text> text, const std::string &sound_file);
// [SINGLETON] Destruiremos el objeto notifier con esta función estática // [SINGLETON] Destruiremos el objeto notifier con esta función estática
static void destroy(); static void destroy();
@@ -111,7 +111,7 @@ public:
* @param icon Icono opcional para mostrar (valor predeterminado: -1). * @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). * @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 // Indica si hay notificaciones activas
bool isActive(); bool isActive();

View File

@@ -86,14 +86,13 @@ bool loadOptionsFile(std::string file_path)
bool success = true; bool success = true;
// Variables para manejar el fichero // Variables para manejar el fichero
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(file_path); std::ifstream file(file_path);
// Si el fichero se puede abrir // Si el fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // 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; std::string line;
while (std::getline(file, line)) while (std::getline(file, line))
{ {
@@ -105,14 +104,12 @@ bool loadOptionsFile(std::string file_path)
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length()))) 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; std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false; success = false;
} }
} }
} }
// Cierra el fichero
file.close(); file.close();
} }
@@ -146,16 +143,15 @@ bool loadOptionsFile(std::string file_path)
// Guarda el fichero de configuración // Guarda el fichero de configuración
bool saveOptionsFile(std::string file_path) 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); std::ofstream file(file_path);
if (!file.good()) 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; return false;
} }
std::cout << "Writing file: " << file_name << std::endl; std::cout << "Writing file: " << getFileName(file_path) << std::endl;
// Opciones de video // Opciones de video
const auto value_video_mode_winow = std::to_string(static_cast<int>(ScreenVideoMode::WINDOW)); const auto value_video_mode_winow = std::to_string(static_cast<int>(ScreenVideoMode::WINDOW));

View File

@@ -78,8 +78,7 @@ void loadParamsFromFile(const std::string &file_path)
throw std::runtime_error("No se pudo abrir el archivo: " + 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: " << getFileName(file_path) << std::endl;
std::cout << "Reading file: " << file_name << std::endl;
std::string line, param1, param2; std::string line, param1, param2;
while (std::getline(file, line)) while (std::getline(file, line))

View File

@@ -1,3 +1,5 @@
#include <algorithm>
#include <stdexcept>
#include <iostream> #include <iostream>
#include "resource.h" #include "resource.h"
#include "asset.h" #include "asset.h"
@@ -51,13 +53,14 @@ Resource::~Resource()
// Obtiene el sonido a partir de un nombre // Obtiene el sonido a partir de un nombre
JA_Sound_t *Resource::getSound(const std::string &name) 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 it->sound;
{
return s.sound;
}
} }
std::cerr << "Error: Sonido no encontrado " << name << std::endl; std::cerr << "Error: Sonido no encontrado " << name << std::endl;
throw std::runtime_error("Sonido no encontrado: " + name); 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 // Obtiene la música a partir de un nombre
JA_Music_t *Resource::getMusic(const std::string &name) 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 it->music;
{
return m.music;
}
} }
std::cerr << "Error: Música no encontrada " << name << std::endl; std::cerr << "Error: Música no encontrada " << name << std::endl;
throw std::runtime_error("Música no encontrada: " + name); 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 // Obtiene la textura a partir de un nombre
std::shared_ptr<Texture> Resource::getTexture(const std::string &name) std::shared_ptr<Texture> 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 it->texture;
{
return t.texture;
}
} }
std::cerr << "Error: Imagen no encontrada " << name << std::endl; std::cerr << "Error: Imagen no encontrada " << name << std::endl;
throw std::runtime_error("Imagen no encontrada: " + name); throw std::runtime_error("Imagen no encontrada: " + name);
} }
@@ -93,13 +98,14 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
// Obtiene el fichero de texto a partir de un nombre // Obtiene el fichero de texto a partir de un nombre
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name) std::shared_ptr<TextFile> 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 it->text_file;
{
return t.text_file;
}
} }
std::cerr << "Error: TextFile no encontrado " << name << std::endl; std::cerr << "Error: TextFile no encontrado " << name << std::endl;
throw std::runtime_error("TextFile no encontrado: " + name); throw std::runtime_error("TextFile no encontrado: " + name);
} }
@@ -107,13 +113,14 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
// Obtiene la animación a partir de un nombre // Obtiene la animación a partir de un nombre
Animations &Resource::getAnimation(const std::string &name) 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 it->animation;
{
return a.animation;
}
} }
std::cerr << "Error: Animación no encontrada " << name << std::endl; std::cerr << "Error: Animación no encontrada " << name << std::endl;
throw std::runtime_error("Animación no encontrada: " + name); throw std::runtime_error("Animación no encontrada: " + name);
} }
@@ -128,19 +135,12 @@ DemoData &Resource::getDemoData(int index)
void Resource::loadSounds() void Resource::loadSounds()
{ {
std::cout << "\n>> SOUND FILES" << std::endl; 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); auto list = Asset::get()->getListByType(AssetType::SOUND);
sounds_.clear(); sounds_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
// Encuentra el último índice de '/' auto name = getFileName(l);
auto last_index = l.find_last_of('/') + 1;
// Obtiene la subcadena desde el último '/'
auto name = l.substr(last_index);
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str()))); sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
printWithDots("Sound : ", name, "[ LOADED ]"); printWithDots("Sound : ", name, "[ LOADED ]");
} }
@@ -150,19 +150,12 @@ void Resource::loadSounds()
void Resource::loadMusics() void Resource::loadMusics()
{ {
std::cout << "\n>> MUSIC FILES" << std::endl; std::cout << "\n>> MUSIC FILES" << std::endl;
// Obtiene la lista con las rutas a los ficheros musicales
auto list = Asset::get()->getListByType(AssetType::MUSIC); auto list = Asset::get()->getListByType(AssetType::MUSIC);
musics_.clear(); musics_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
// Encuentra el último índice de '/' auto name = getFileName(l);
auto last_index = l.find_last_of('/') + 1;
// Obtiene la subcadena desde el último '/'
auto name = l.substr(last_index);
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str()))); musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
printWithDots("Music : ", name, "[ LOADED ]"); printWithDots("Music : ", name, "[ LOADED ]");
} }
@@ -172,19 +165,12 @@ void Resource::loadMusics()
void Resource::loadTextures() void Resource::loadTextures()
{ {
std::cout << "\n>> TEXTURES" << std::endl; std::cout << "\n>> TEXTURES" << std::endl;
// Obtiene la lista con las rutas a los ficheros png
auto list = Asset::get()->getListByType(AssetType::BITMAP); auto list = Asset::get()->getListByType(AssetType::BITMAP);
textures_.clear(); textures_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
// Encuentra el último índice de '/' auto name = getFileName(l);
auto last_index = l.find_last_of('/') + 1;
// Obtiene la subcadena desde el último '/'
auto name = l.substr(last_index);
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l))); textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
} }
} }
@@ -193,18 +179,12 @@ void Resource::loadTextures()
void Resource::loadTextFiles() void Resource::loadTextFiles()
{ {
std::cout << "\n>> TEXT FILES" << std::endl; std::cout << "\n>> TEXT FILES" << std::endl;
// Obtiene la lista con las rutas a los ficheros png
auto list = Asset::get()->getListByType(AssetType::FONT); auto list = Asset::get()->getListByType(AssetType::FONT);
text_files_.clear(); text_files_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
// Encuentra el último índice de '/' auto name = getFileName(l);
auto last_index = l.find_last_of('/') + 1;
// Obtiene la subcadena desde el último '/'
auto name = l.substr(last_index);
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l))); text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
} }
} }
@@ -213,18 +193,12 @@ void Resource::loadTextFiles()
void Resource::loadAnimations() void Resource::loadAnimations()
{ {
std::cout << "\n>> ANIMATIONS" << std::endl; std::cout << "\n>> ANIMATIONS" << std::endl;
// Obtiene la lista con las rutas a los ficheros ani
auto list = Asset::get()->getListByType(AssetType::ANIMATION); auto list = Asset::get()->getListByType(AssetType::ANIMATION);
animations_.clear(); animations_.clear();
for (const auto &l : list) for (const auto &l : list)
{ {
// Encuentra el último índice de '/' auto name = getFileName(l);
auto last_index = l.find_last_of('/') + 1;
// Obtiene la subcadena desde el último '/'
auto name = l.substr(last_index);
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l))); animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
} }
} }

View File

@@ -61,7 +61,7 @@ struct ResourceAnimation
Animations animation; // Objeto con las animaciones Animations animation; // Objeto con las animaciones
// Constructor // Constructor
ResourceAnimation(const std::string &name, Animations animation) ResourceAnimation(const std::string &name, const Animations &animation)
: name(name), animation(animation) {} : name(name), animation(animation) {}
}; };

View File

@@ -46,7 +46,7 @@ Scoreboard::Scoreboard()
hi_score_(0), hi_score_(0),
power_(0), power_(0),
hi_score_name_(std::string()), hi_score_name_(std::string()),
color_({0, 0, 0}), color_(Color(0, 0, 0)),
rect_({0, 0, 320, 40}), rect_({0, 0, 320, 40}),
ticks_(SDL_GetTicks()), ticks_(SDL_GetTicks()),
counter_(0) counter_(0)

View File

@@ -52,7 +52,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
src_rect_({0, 0, param.game.width, param.game.height}), src_rect_({0, 0, param.game.width, param.game.height}),
dst_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), attenuate_effect_(false),
fps_ticks_(0), fps_ticks_(0),
fps_counter_(0), fps_counter_(0),
@@ -67,7 +67,7 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
flash_effect_.enabled = false; flash_effect_.enabled = false;
flash_effect_.counter = 0; flash_effect_.counter = 0;
flash_effect_.lenght = 0; flash_effect_.lenght = 0;
flash_effect_.color = {0xFF, 0xFF, 0xFF}; flash_effect_.color = Color(0xFF, 0xFF, 0xFF);
shake_effect_.enabled = false; shake_effect_.enabled = false;
shake_effect_.desp = 2; shake_effect_.desp = 2;
shake_effect_.delay = 3; shake_effect_.delay = 3;
@@ -481,8 +481,7 @@ void Screen::displayInfo()
dbg_print(0, 0, info_resolution_.c_str(), 255, 255, 0); dbg_print(0, 0, info_resolution_.c_str(), 255, 255, 0);
// Contador de service_pressed_counter // Contador de service_pressed_counter
const int counter = globalInputs::service_pressed_counter[0]; if (const int counter = globalInputs::service_pressed_counter[0]; counter > 0)
if (counter > 0)
dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255); dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255);
} }
} }

View File

@@ -111,7 +111,7 @@ public:
void checkInput(); void checkInput();
// Limpia la pantalla // 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 // Prepara para empezar a dibujar en la textura de juego
void start(); void start();

View File

@@ -23,7 +23,6 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
} }
// Abre el fichero para leer los valores // 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); std::ifstream file(file_path);
if (file.is_open() && file.good()) if (file.is_open() && file.good())
@@ -56,15 +55,15 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
}; };
// Cierra el fichero // Cierra el fichero
printWithDots("Text File : ", file_name, "[ LOADED ]"); printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]");
file.close(); file.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
else else
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho // Establece las coordenadas para cada caracter ascii de la cadena y su ancho

View File

@@ -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); unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
if (!data) if (!data)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }
else else
{ {
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
printWithDots("Image : ", file_name, "[ LOADED ]");
} }
int depth, pitch; int depth, pitch;
@@ -320,13 +319,12 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
FILE *f = fopen(file_path.c_str(), "rb"); FILE *f = fopen(file_path.c_str(), "rb");
if (!f) if (!f)
{ {
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl; std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
throw std::runtime_error("Fichero no encontrado: " + file_path); throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
} }
else else
{ {
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
printWithDots("Image : ", file_name, "[ LOADED ]");
} }
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);

View File

@@ -138,7 +138,7 @@ void Title::render()
if (section::options == section::Options::TITLE_2) if (section::options == section::Options::TITLE_2)
{ {
constexpr Color shadow = {0x14, 0x87, 0xc4}; constexpr Color shadow = Color(0x14, 0x87, 0xc4);
// 'PRESS TO PLAY' // 'PRESS TO PLAY'
if (counter_ % 50 > 14 && !define_buttons_->isEnabled()) if (counter_ % 50 > 14 && !define_buttons_->isEnabled())

View File

@@ -1,4 +1,5 @@
#include "utils.h" #include "utils.h"
#include <filesystem>
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <algorithm> // for min, clamp, find_if_not, transform #include <algorithm> // for min, clamp, find_if_not, transform
@@ -12,16 +13,16 @@ struct JA_Sound_t; // lines 8-8
Overrides overrides = Overrides(); Overrides overrides = Overrides();
// Colores // Colores
const Color bg_color = {0x27, 0x27, 0x36}; const Color bg_color = Color(0x27, 0x27, 0x36);
const Color no_color = {0xFF, 0xFF, 0xFF}; const Color no_color = Color(0xFF, 0xFF, 0xFF);
const Color shdw_txt_color = {0x43, 0x43, 0x4F}; const Color shdw_txt_color = Color(0x43, 0x43, 0x4F);
const Color separator_color = {0x0D, 0x1A, 0x2B}; const Color separator_color = Color(0x0D, 0x1A, 0x2B);
const Color scoreboard_easy_color = {0x4B, 0x69, 0x2F}; const Color scoreboard_easy_color = Color(0x4B, 0x69, 0x2F);
const Color scoreboard_normal_color = {0x2E, 0x3F, 0x47}; const Color scoreboard_normal_color = Color(0x2E, 0x3F, 0x47);
const Color scoreboard_hard_color = {0x76, 0x42, 0x8A}; const Color scoreboard_hard_color = Color(0x76, 0x42, 0x8A);
const Color flash_color = {0xFF, 0xFF, 0xFF}; const Color flash_color = Color(0xFF, 0xFF, 0xFF);
const Color fade_color = {0x27, 0x27, 0x36}; const Color fade_color = Color(0x27, 0x27, 0x36);
const Color orange_color = {0xFF, 0x7A, 0x00}; const Color orange_color = Color(0xFF, 0x7A, 0x00);
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2) double distanceSquared(int x1, int y1, int x2, int y2)
@@ -220,8 +221,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
} }
else else
{ {
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]");
printWithDots("DemoData : ", file_name, "[ LOADED ]");
// Lee todos los datos del fichero y los deja en el destino // Lee todos los datos del fichero y los deja en el destino
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) 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) bool saveDemoFile(const std::string &file_path, const DemoData &dd)
{ {
auto success = true; 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"); auto file = SDL_RWFromFile(file_path.c_str(), "w+b");
if (file) 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) 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; success = false;
break; break;
} }
} }
if (success) 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 // Cierra el fichero
SDL_RWclose(file); SDL_RWclose(file);
} }
else 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; success = false;
} }
return success; return success;
} }
#endif // RECORDING #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();
}

View File

@@ -53,7 +53,8 @@ struct Circle
struct Color struct Color
{ {
Uint8 r, g, b; 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 // Posiciones de las notificaciones
@@ -72,8 +73,8 @@ struct HiScoreEntry
std::string name; // Nombre std::string name; // Nombre
int score; // Puntuación int score; // Puntuación
// Constructor // Constructor
HiScoreEntry(const std::string &n = "", int s = 0) explicit HiScoreEntry(const std::string &n = "", int s = 0)
: name(n), score(s) {} : name(n), score(s) {}
}; };
@@ -87,7 +88,7 @@ struct DemoKeys
Uint8 fire_right; Uint8 fire_right;
// Constructor que inicializa todos los campos // 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) {} : 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); bool saveDemoFile(const std::string &file_path, const DemoData &dd);
#endif #endif
// Obtiene el nombre de un fichero a partir de una ruta
std::string getFileName(const std::string &path);
// Colores // Colores
extern const Color bg_color; extern const Color bg_color;
extern const Color no_color; extern const Color no_color;