Mes recomanacions de cppcheck

This commit is contained in:
2024-10-13 19:26:27 +02:00
parent 46540ad7c3
commit babf02226c
22 changed files with 291 additions and 369 deletions

View File

@@ -1,14 +1,15 @@
#include "game.h" #include "game.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_h #include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3, SDLK_h
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_R... #include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_R...
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_FOCUS_GAINED, SDL_... #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_FOCUS_GAINED, SDL_...
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include <algorithm> // for min #include <algorithm> // for min
#include <fstream> // for basic_ifstream #include <fstream> // for basic_ifstream
#include <iostream> // for char_traits, basic_istream, ifstream #include <iostream> // for char_traits, basic_istream, ifstream
#include <numeric>
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "background.h" // for Background #include "background.h" // for Background
#include "balloon.h" // for Balloon, BALLOON_SPEED_1, BALLOON_... #include "balloon.h" // for Balloon, BALLOON_SPEED_1, BALLOON_...
@@ -133,13 +134,13 @@ void Game::init(int player_id)
players_.push_back(std::move(player2)); players_.push_back(std::move(player2));
// Obtiene mediante "playerID" el jugador que va a empezar jugar // Obtiene mediante "playerID" el jugador que va a empezar jugar
auto player = getPlayer(player_id); auto main_player = getPlayer(player_id);
// Cambia el estado del jugador seleccionado // Cambia el estado del jugador seleccionado
player->setStatusPlaying(PlayerStatus::PLAYING); main_player->setStatusPlaying(PlayerStatus::PLAYING);
// Como es el principio del juego, empieza sin inmunidad // Como es el principio del juego, empieza sin inmunidad
player->setInvulnerable(false); main_player->setInvulnerable(false);
// Variables relacionadas con la dificultad // Variables relacionadas con la dificultad
switch (difficulty_) switch (difficulty_)
@@ -243,9 +244,9 @@ void Game::init(int player_id)
// Activa o no al otro jugador // Activa o no al otro jugador
if (rand() % 2 == 0) if (rand() % 2 == 0)
{ {
const auto otherPlayer = player_id == 1 ? 2 : 1; const auto other_player_id = player_id == 1 ? 2 : 1;
auto player = getPlayer(otherPlayer); auto other_player = getPlayer(other_player_id);
player->setStatusPlaying(PlayerStatus::PLAYING); other_player->setStatusPlaying(PlayerStatus::PLAYING);
} }
for (auto &player : players_) for (auto &player : players_)
@@ -707,7 +708,7 @@ bool Game::saveDemoFile(const std::string &file_path)
#endif // RECORDING #endif // RECORDING
// Crea una formación de enemigos // Crea una formación de enemigos
void Game::deployEnemyFormation() void Game::deployBalloonFormation()
{ {
// Solo despliega una formación enemiga si ha pasado cierto tiempo desde la última // Solo despliega una formación enemiga si ha pasado cierto tiempo desde la última
if (balloon_deploy_counter_ == 0) if (balloon_deploy_counter_ == 0)
@@ -1587,14 +1588,8 @@ void Game::killPlayer(std::shared_ptr<Player> &player)
// Calcula y establece el valor de amenaza en funcion de los globos activos // Calcula y establece el valor de amenaza en funcion de los globos activos
void Game::evaluateAndSetMenace() void Game::evaluateAndSetMenace()
{ {
menace_current_ = 0; menace_current_ = std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon)
for (auto &balloon : balloons_) { return sum + (balloon->isEnabled() ? balloon->getMenace() : 0); });
{
if (balloon->isEnabled())
{
menace_current_ += balloon->getMenace();
}
}
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -1645,11 +1640,11 @@ void Game::updateTimeStoppedCounter()
} }
// Actualiza la variable enemyDeployCounter // Actualiza la variable enemyDeployCounter
void Game::updateEnemyDeployCounter() void Game::updateBalloonDeployCounter()
{ {
if (balloon_deploy_counter_ > 0) if (balloon_deploy_counter_ > 0)
{ {
balloon_deploy_counter_--; --balloon_deploy_counter_;
} }
} }
@@ -1750,7 +1745,7 @@ void Game::update()
// Actualiza los contadores de estado y efectos // Actualiza los contadores de estado y efectos
updateTimeStoppedCounter(); updateTimeStoppedCounter();
updateEnemyDeployCounter(); updateBalloonDeployCounter();
// Actualiza el ayudante // Actualiza el ayudante
updateHelper(); updateHelper();
@@ -1872,7 +1867,7 @@ void Game::updateMenace()
if (menace_current_ < menace_threshold_) if (menace_current_ < menace_threshold_)
{ {
// Crea una formación de enemigos // Crea una formación de enemigos
deployEnemyFormation(); deployBalloonFormation();
// Recalcula el nivel de amenaza con el nuevo globo // Recalcula el nivel de amenaza con el nuevo globo
evaluateAndSetMenace(); evaluateAndSetMenace();
@@ -2248,28 +2243,14 @@ void Game::run()
// Indica si se puede crear una powerball // Indica si se puede crear una powerball
bool Game::canPowerBallBeCreated() bool Game::canPowerBallBeCreated()
{ {
if ((!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0)) return (!power_ball_enabled_) && (calculateScreenPower() > POWERBALL_SCREENPOWER_MINIMUM) && (power_ball_counter_ == 0);
{
return true;
}
return false;
} }
// Calcula el poder actual de los globos en pantalla // Calcula el poder actual de los globos en pantalla
int Game::calculateScreenPower() int Game::calculateScreenPower()
{ {
auto power = 0; return std::accumulate(balloons_.begin(), balloons_.end(), 0, [](int sum, const auto &balloon)
{ return sum + (balloon->isEnabled() ? balloon->getPower() : 0); });
for (auto &balloon : balloons_)
{
if (balloon->isEnabled())
{
power += balloon->getPower();
}
}
return power;
} }
// Inicializa las variables que contienen puntos de ruta para mover objetos // Inicializa las variables que contienen puntos de ruta para mover objetos
@@ -2354,7 +2335,7 @@ void Game::updateHelper()
// Solo ofrece ayuda cuando la amenaza es elevada // Solo ofrece ayuda cuando la amenaza es elevada
if (menace_current_ > 15) if (menace_current_ > 15)
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
helper_.need_coffee = (player->getCoffees() == 0); helper_.need_coffee = (player->getCoffees() == 0);
helper_.need_coffee_machine = (!player->isPowerUp()); helper_.need_coffee_machine = (!player->isPowerUp());
@@ -2370,7 +2351,7 @@ void Game::updateHelper()
bool Game::allPlayersAreWaitingOrGameOver() bool Game::allPlayersAreWaitingOrGameOver()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= player->isWaiting() || player->isGameOver(); success &= player->isWaiting() || player->isGameOver();
} }
@@ -2382,7 +2363,7 @@ bool Game::allPlayersAreWaitingOrGameOver()
bool Game::allPlayersAreGameOver() bool Game::allPlayersAreGameOver()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= player->isGameOver(); success &= player->isGameOver();
} }
@@ -2394,7 +2375,7 @@ bool Game::allPlayersAreGameOver()
bool Game::allPlayersAreNotPlaying() bool Game::allPlayersAreNotPlaying()
{ {
auto success = true; auto success = true;
for (auto &player : players_) for (const auto &player : players_)
{ {
success &= !player->isPlaying(); success &= !player->isPlaying();
} }
@@ -2566,7 +2547,7 @@ void Game::reloadTextures()
// Actualiza el marcador // Actualiza el marcador
void Game::updateScoreboard() void Game::updateScoreboard()
{ {
for (auto &player : players_) for (const auto &player : players_)
{ {
scoreboard_->setScore(player->getScoreBoardPanel(), player->getScore()); scoreboard_->setScore(player->getScoreBoardPanel(), player->getScore());
scoreboard_->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier()); scoreboard_->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier());
@@ -2590,7 +2571,7 @@ void Game::pause(bool value)
} }
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records
void Game::addScoreToScoreBoard(std::string name, int score) void Game::addScoreToScoreBoard(const std::string &name, int score)
{ {
const auto entry = (HiScoreEntry){trim(name), score}; const auto entry = (HiScoreEntry){trim(name), score};
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table); auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
@@ -2635,7 +2616,7 @@ 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 (auto &player : players_) for (const auto &player : players_)
{ {
if (player->getId() == id) if (player->getId() == id)
{ {

View File

@@ -233,7 +233,7 @@ private:
bool saveDemoFile(const std::string &file_path); bool saveDemoFile(const std::string &file_path);
#endif #endif
// Crea una formación de enemigos // Crea una formación de enemigos
void deployEnemyFormation(); void deployBalloonFormation();
// Aumenta el poder de la fase // Aumenta el poder de la fase
void increaseStageCurrentPower(int power); void increaseStageCurrentPower(int power);
@@ -362,7 +362,7 @@ private:
void incTimeStoppedCounter(int value); void incTimeStoppedCounter(int value);
// Actualiza la variable EnemyDeployCounter // Actualiza la variable EnemyDeployCounter
void updateEnemyDeployCounter(); void updateBalloonDeployCounter();
// Actualiza y comprueba el valor de la variable // Actualiza y comprueba el valor de la variable
void updateTimeStoppedCounter(); void updateTimeStoppedCounter();
@@ -431,7 +431,7 @@ private:
void checkMusicStatus(); void checkMusicStatus();
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records
void addScoreToScoreBoard(std::string name, int score); void addScoreToScoreBoard(const std::string &name, int score);
// Saca del estado de GAME OVER al jugador si el otro está activo // Saca del estado de GAME OVER al jugador si el otro está activo
void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index); void checkAndUpdatePlayerStatus(int active_player_index, int inactive_player_index);

View File

@@ -50,7 +50,7 @@ void ManageHiScoreTable::sort()
{ {
struct struct
{ {
bool operator()(HiScoreEntry &a, HiScoreEntry &b) const { return a.score > b.score; } bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
} custom_less; } custom_less;
std::sort(table_->begin(), table_->end(), custom_less); std::sort(table_->begin(), table_->end(), custom_less);

View File

@@ -10,7 +10,7 @@
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Constructor // Constructor
Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile) Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile)
: renderer(renderer), : renderer(renderer),
text(std::make_unique<Text>(bitmapFile, textFile, renderer)), text(std::make_unique<Text>(bitmapFile, textFile, renderer)),
bgColor(param.notification.color), bgColor(param.notification.color),

View File

@@ -77,7 +77,7 @@ private:
public: public:
// Constructor // Constructor
Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, std::string soundFile); Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile);
// Destructor // Destructor
~Notify(); ~Notify();

View File

@@ -13,7 +13,7 @@
Options options; Options options;
// Declaraciones // Declaraciones
bool setOptions(std::string var, const std::string &value); bool setOptions(const std::string &var, const std::string &value);
// Inicializa las opciones del programa // Inicializa las opciones del programa
void initOptions() void initOptions()
@@ -244,7 +244,7 @@ bool saveOptionsFile(std::string file_path)
} }
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool setOptions(std::string var, const std::string &value) bool setOptions(const std::string &var, const std::string &value)
{ {
// Indicador de éxito en la asignación // Indicador de éxito en la asignación
auto success = true; auto success = true;

View File

@@ -1,7 +1,10 @@
#include "param.h" #include "param.h"
#include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi... #include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi...
#include <iostream> // for cout #include <iostream> // for cout
#include "utils.h" // for Param, ParamGame, Zone, ParamBalloon #include <sstream>
#include <string>
#include <stdexcept>
#include "utils.h" // for Param, ParamGame, Zone, ParamBalloon
Param param; Param param;
@@ -40,7 +43,7 @@ void initParam()
param.title.title_c_c_position = 11; param.title.title_c_c_position = 11;
// BACKGROUND // BACKGROUND
param.background.attenuate_color = {255, 255, 255}; param.background.attenuate_color = (Color){255, 255, 255};
param.background.attenuate_alpha = 32; param.background.attenuate_alpha = 32;
// BALLOONS // BALLOONS
@@ -52,10 +55,18 @@ void initParam()
param.balloon_3.grav = 0.10f; param.balloon_3.grav = 0.10f;
param.balloon_4.vel = 4.95f; param.balloon_4.vel = 4.95f;
param.balloon_4.grav = 0.10f; param.balloon_4.grav = 0.10f;
// NOTIFICATION
param.notification.pos_v = NotifyPosition::TOP;
param.notification.pos_h = NotifyPosition::LEFT;
param.notification.sound = false;
param.notification.color.r = 48;
param.notification.color.g = 48;
param.notification.color.b = 48;
} }
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
void loadParamsFromFile(std::string file_path) /*void loadParamsFromFile(std::string file_path)
{ {
// Pone valores por defecto a las variables // Pone valores por defecto a las variables
initParam(); initParam();
@@ -80,8 +91,15 @@ void loadParamsFromFile(std::string file_path)
param1.clear(); param1.clear();
param2.clear(); param2.clear();
// Elimina los comentarios // Elimina los comentarios al final de una linea
line = line.substr(0, line.find("#")); {
// line = line.substr(0, line.find("#"));
auto pos = line.find("#");
if (pos != std::string::npos)
{
line.resize(pos);
}
}
// Ignora los espacios en blanco // Ignora los espacios en blanco
int pos = 0; int pos = 0;
@@ -148,6 +166,50 @@ void loadParamsFromFile(std::string file_path)
std::cout << "Failed to load file: " << file_path << std::endl; std::cout << "Failed to load file: " << file_path << std::endl;
#endif #endif
precalculateZones();
}*/
void loadParamsFromFile(const std::string &file_path)
{
// Inicializa los parámetros con valores por defecto
initParam();
// Abre el archivo
std::ifstream file(file_path);
if (!file.is_open())
{
#ifdef VERBOSE
std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl;
#endif
throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
}
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::cout << "Reading file: " << file_name << std::endl;
#endif
std::string line, param1, param2;
while (std::getline(file, line))
{
// Elimina comentarios
auto comment_pos = line.find('#');
if (comment_pos != std::string::npos)
{
line = line.substr(0, comment_pos);
}
// Usa un stream para separar palabras
std::istringstream iss(line);
if (iss >> param1 >> param2)
{
setParams(param1, param2);
}
}
// Cierra el archivo
file.close();
// Realiza cálculos adicionales después de cargar los parámetros
precalculateZones(); precalculateZones();
} }

View File

@@ -6,4 +6,4 @@ struct Param;
extern Param param; extern Param param;
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
void loadParamsFromFile(std::string file_path); void loadParamsFromFile(const std::string &file_path);

View File

@@ -12,30 +12,29 @@
// Constructor // Constructor
Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations) Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations)
: player_sprite_(std::make_unique<AnimatedSprite>(texture[0], "", animations[0])),
power_sprite_(std::make_unique<AnimatedSprite>(texture[1], "", animations[1])),
enter_name_(std::make_unique<EnterName>()),
play_area_(play_area),
id_(id),
pos_x_(x),
pos_y_(y),
default_pos_x_(x),
default_pos_y_(y),
status_playing_(PlayerStatus::WAITING),
scoreboard_panel_(0),
name_(std::string()),
controller_index_(0),
demo_(demo)
{ {
// Reserva memoria para los objetos // Reserva memoria para los objetos
player_sprite_ = std::make_unique<AnimatedSprite>(texture[0], "", animations[0]);
power_sprite_ = std::make_unique<AnimatedSprite>(texture[1], "", animations[1]);
power_sprite_->getTexture()->setAlpha(224); power_sprite_->getTexture()->setAlpha(224);
enter_name_ = std::make_unique<EnterName>();
// Rectangulo con la zona de juego
play_area_ = play_area;
// Establece la posición inicial del jugador
default_pos_x_ = pos_x_ = x;
default_pos_y_ = pos_y_ = y;
// Establece los offsets para el sprite de PowerUp // Establece los offsets para el sprite de PowerUp
power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2; power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight())); power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight()));
// Inicializa variables // Inicializa variables
id_ = id;
demo_ = demo;
status_playing_ = PlayerStatus::WAITING;
scoreboard_panel_ = 0;
name_.clear();
setRecordName(enter_name_->getName()); setRecordName(enter_name_->getName());
init(); init();
} }
@@ -237,21 +236,13 @@ void Player::render()
// Establece el estado del jugador cuando camina // Establece el estado del jugador cuando camina
void Player::setWalkingStatus(PlayerStatus status) void Player::setWalkingStatus(PlayerStatus status)
{ {
// Si cambiamos de estado, reiniciamos la animación status_walking_ = status;
if (status_walking_ != status)
{
status_walking_ = status;
}
} }
// Establece el estado del jugador cuando dispara // Establece el estado del jugador cuando dispara
void Player::setFiringStatus(PlayerStatus status) void Player::setFiringStatus(PlayerStatus status)
{ {
// Si cambiamos de estado, reiniciamos la animación status_firing_ = status;
if (status_firing_ != status)
{
status_firing_ = status;
}
} }
// Establece la animación correspondiente al estado // Establece la animación correspondiente al estado
@@ -694,7 +685,7 @@ void Player::shiftColliders()
} }
// Pone las texturas del jugador // Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture) void Player::setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture)
{ {
player_sprite_->setTexture(texture[0]); player_sprite_->setTexture(texture[0]);
power_sprite_->setTexture(texture[1]); power_sprite_->setTexture(texture[1]);
@@ -736,7 +727,7 @@ int Player::getScoreBoardPanel() const
void Player::decContinueCounter() void Player::decContinueCounter()
{ {
continue_ticks_ = SDL_GetTicks(); continue_ticks_ = SDL_GetTicks();
continue_counter_--; --continue_counter_;
if (continue_counter_ < 0) if (continue_counter_ < 0)
{ {
setStatusPlaying(PlayerStatus::GAME_OVER); setStatusPlaying(PlayerStatus::GAME_OVER);
@@ -744,13 +735,13 @@ void Player::decContinueCounter()
} }
// Establece el nombre del jugador // Establece el nombre del jugador
void Player::setName(std::string name) void Player::setName(const std::string &name)
{ {
name_ = name; name_ = name;
} }
// Establece el nombre del jugador para la tabla de mejores puntuaciones // Establece el nombre del jugador para la tabla de mejores puntuaciones
void Player::setRecordName(std::string record_name) void Player::setRecordName(const std::string &record_name)
{ {
record_name_ = record_name.substr(0, 8); record_name_ = record_name.substr(0, 8);
} }

View File

@@ -118,7 +118,7 @@ public:
void render(); void render();
// Pone las texturas del jugador // Pone las texturas del jugador
void setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture); void setPlayerTextures(const std::vector<std::shared_ptr<Texture>> &texture);
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
void setInput(InputType input); void setInput(InputType input);
@@ -271,10 +271,10 @@ public:
void decContinueCounter(); void decContinueCounter();
// Establece el nombre del jugador // Establece el nombre del jugador
void setName(std::string name); void setName(const std::string &name);
// Establece el nombre del jugador para la tabla de mejores puntuaciones // Establece el nombre del jugador para la tabla de mejores puntuaciones
void setRecordName(std::string record_name); void setRecordName(const std::string &record_name);
// Obtiene el nombre del jugador // Obtiene el nombre del jugador
std::string getName() const; std::string getName() const;

View File

@@ -34,13 +34,21 @@ Scoreboard *Scoreboard::get()
// Constructor // Constructor
Scoreboard::Scoreboard(SDL_Renderer *renderer) Scoreboard::Scoreboard(SDL_Renderer *renderer)
: renderer_(renderer) : renderer_(renderer),
game_power_meter_texture_(std::make_shared<Texture>(renderer, Asset::get()->get("game_power_meter.png"))),
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
text_scoreboard_(std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer)),
stage_(1),
hi_score_(0),
power_(0),
hi_score_name_(std::string()),
color_({0, 0, 0}),
rect_({0, 0, 320, 40}),
ticks_(SDL_GetTicks()),
counter_(0)
{ {
// Inicializa punteros
game_power_meter_texture_ = nullptr;
power_meter_sprite_ = nullptr;
text_scoreboard_ = nullptr;
// Inicializa variables // Inicializa variables
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i) for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
{ {
@@ -51,25 +59,14 @@ Scoreboard::Scoreboard(SDL_Renderer *renderer)
mult_[i] = 0; mult_[i] = 0;
continue_counter_[i] = 0; continue_counter_[i] = 0;
} }
stage_ = 1;
hi_score_ = 0;
power_ = 0;
hi_score_name_.clear();
color_ = {0, 0, 0};
rect_ = {0, 0, 320, 40};
panel_[SCOREBOARD_LEFT_PANEL].mode = ScoreboardMode::SCORE; panel_[SCOREBOARD_LEFT_PANEL].mode = ScoreboardMode::SCORE;
panel_[SCOREBOARD_RIGHT_PANEL].mode = ScoreboardMode::SCORE; panel_[SCOREBOARD_RIGHT_PANEL].mode = ScoreboardMode::SCORE;
panel_[SCOREBOARD_CENTER_PANEL].mode = ScoreboardMode::STAGE_INFO; panel_[SCOREBOARD_CENTER_PANEL].mode = ScoreboardMode::STAGE_INFO;
ticks_ = SDL_GetTicks();
counter_ = 0;
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
recalculateAnchors(); recalculateAnchors();
power_meter_sprite_->setPos({slot4_2_.x - 20, slot4_2_.y, 40, 7});
// Crea objetos
game_power_meter_texture_ = std::make_shared<Texture>(renderer_, Asset::get()->get("game_power_meter.png"));
power_meter_sprite_ = std::make_unique<Sprite>(slot4_2_.x - 20, slot4_2_.y, 40, 7, game_power_meter_texture_);
text_scoreboard_ = std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer_);
// Crea la textura de fondo // Crea la textura de fondo
background_ = nullptr; background_ = nullptr;
@@ -130,13 +127,13 @@ void Scoreboard::render()
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setName(int panel_, std::string name_) void Scoreboard::setName(int panel_, const std::string &name_)
{ {
this->name_[panel_] = name_; this->name_[panel_] = name_;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setRecordName(int panel_, std::string record_name_) void Scoreboard::setRecordName(int panel_, const std::string &record_name_)
{ {
this->record_name_[panel_] = record_name_; this->record_name_[panel_] = record_name_;
} }
@@ -184,7 +181,7 @@ void Scoreboard::setPower(float power_)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setHiScoreName(std::string name_) void Scoreboard::setHiScoreName(const std::string &name_)
{ {
hi_score_name_ = name_; hi_score_name_ = name_;
} }
@@ -323,7 +320,7 @@ void Scoreboard::fillPanelTextures()
// ENTER NAME // ENTER NAME
text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106)); text_scoreboard_->writeCentered(slot4_3_.x, slot4_3_.y, lang::getText(106));
SDL_Rect rect_ = {enter_name_pos_.x, enter_name_pos_.y, 5, 7}; SDL_Rect rect = {enter_name_pos_.x, enter_name_pos_.y, 5, 7};
SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255); SDL_SetRenderDrawColor(renderer_, 0xFF, 0xFF, 0xEB, 255);
for (int j = 0; j < (int)record_name_[i].size(); ++j) for (int j = 0; j < (int)record_name_[i].size(); ++j)
{ {
@@ -331,16 +328,16 @@ void Scoreboard::fillPanelTextures()
{ // La letra seleccionada se pinta de forma intermitente { // La letra seleccionada se pinta de forma intermitente
if (counter_ % 3 > 0) if (counter_ % 3 > 0)
{ {
SDL_RenderDrawLine(renderer_, rect_.x, rect_.y + rect_.h, rect_.x + rect_.w, rect_.y + rect_.h); SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
text_scoreboard_->write(rect_.x, rect_.y, record_name_[i].substr(j, 1)); text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1));
} }
} }
else else
{ {
SDL_RenderDrawLine(renderer_, rect_.x, rect_.y + rect_.h, rect_.x + rect_.w, rect_.y + rect_.h); SDL_RenderDrawLine(renderer_, rect.x, rect.y + rect.h, rect.x + rect.w, rect.y + rect.h);
text_scoreboard_->write(rect_.x, rect_.y, record_name_[i].substr(j, 1)); text_scoreboard_->write(rect.x, rect.y, record_name_[i].substr(j, 1));
} }
rect_.x += 7; rect.x += 7;
} }
break; break;
} }

View File

@@ -50,9 +50,9 @@ private:
std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase std::shared_ptr<Texture> game_power_meter_texture_; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
SDL_Texture *background_; // Textura para dibujar el marcador SDL_Texture *background_; // Textura para dibujar el marcador
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
// Variables // Variables
@@ -125,10 +125,10 @@ public:
void render(); void render();
// Establece el valor de la variable // Establece el valor de la variable
void setName(int panel, std::string name); void setName(int panel, const std::string &name);
// Establece el valor de la variable // Establece el valor de la variable
void setRecordName(int panel, std::string record_name); void setRecordName(int panel, const std::string &record_name);
// Establece el valor de la variable // Establece el valor de la variable
void setSelectorPos(int panel, int pos); void setSelectorPos(int panel, int pos);
@@ -152,7 +152,7 @@ public:
void setPower(float power); void setPower(float power);
// Establece el valor de la variable // Establece el valor de la variable
void setHiScoreName(std::string name); void setHiScoreName(const std::string &name);
// Establece el valor de la variable // Establece el valor de la variable
void setColor(Color color); void setColor(Color color);

View File

@@ -44,12 +44,27 @@ Screen *Screen::get()
// Constructor // Constructor
Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
: window_(window), renderer_(renderer) : window_(window),
renderer_(renderer),
notify_(std::make_unique<Notify>(renderer_, std::string(), Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"))),
game_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
shader_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, 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}),
border_color_({0x00, 0x00, 0x00}),
attenuate_effect_(false),
fps_ticks_(0),
fps_counter_(0),
fps_(0),
#ifdef DEBUG
show_info_(true)
#else
show_info_(false)
#endif
{ {
// Inicializa variables // Inicializa variables
src_rect_ = {0, 0, param.game.width, param.game.height};
dst_rect_ = {0, 0, param.game.width, param.game.height};
border_color_ = {0, 0, 0};
flash_effect_.enabled = false; flash_effect_.enabled = false;
flash_effect_.counter = 0; flash_effect_.counter = 0;
flash_effect_.lenght = 0; flash_effect_.lenght = 0;
@@ -62,29 +77,10 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
shake_effect_.remaining = 0; shake_effect_.remaining = 0;
shake_effect_.originalPos = 0; shake_effect_.originalPos = 0;
shake_effect_.originalWidth = param.game.width; shake_effect_.originalWidth = param.game.width;
attenuate_effect_ = false;
fps_ticks_ = 0;
fps_counter_ = 0;
fps_ = 0;
#ifdef DEBUG
show_info_ = true;
#else
show_info_ = false;
#endif
SDL_DisplayMode DM; SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM); SDL_GetCurrentDisplayMode(0, &DM);
info_resolution_ = std::to_string(DM.w) + " X " + std::to_string(DM.h) + " AT " + std::to_string(DM.refresh_rate) + " HZ"; info_resolution_ = std::to_string(DM.w) + " X " + std::to_string(DM.h) + " AT " + std::to_string(DM.refresh_rate) + " HZ";
// Crea los objetos
notify_ = std::make_unique<Notify>(renderer_, "", Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"));
// Define el color del borde para el modo de pantalla completa
border_color_ = {0x00, 0x00, 0x00};
// Crea las textura donde se dibujan los graficos del juego
game_canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
shader_canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
// Establece el modo de video // Establece el modo de video
setVideoMode(options.video.mode); setVideoMode(options.video.mode);
@@ -183,9 +179,10 @@ void Screen::blit()
// Establece el modo de video // Establece el modo de video
void Screen::setVideoMode(ScreenVideoMode videoMode) void Screen::setVideoMode(ScreenVideoMode videoMode)
{ {
options.video.mode = videoMode;
#ifdef ARCADE #ifdef ARCADE
options.video.mode = ScreenVideoMode::WINDOW; options.video.mode = ScreenVideoMode::WINDOW;
#else
options.video.mode = videoMode;
#endif #endif
switch (options.video.mode) switch (options.video.mode)
@@ -455,7 +452,7 @@ void Screen::attenuate(bool value)
} }
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void Screen::showNotification(std::string text1, std::string text2, int icon) void Screen::showNotification(const std::string &text1, const std::string &text2, int icon)
{ {
notify_->showText(text1, text2, icon); notify_->showText(text1, text2, icon);
} }

View File

@@ -152,7 +152,7 @@ public:
void attenuate(bool value); void attenuate(bool value);
// Muestra una notificación de texto por pantalla; // Muestra una notificación de texto por pantalla;
void showNotification(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1); void showNotification(const std::string &text1 = std::string(), const std::string &text2 = std::string(), int icon = -1);
// Indica si hay alguna notificación activa en pantalla // Indica si hay alguna notificación activa en pantalla
bool notificationsAreActive() const; bool notificationsAreActive() const;

View File

@@ -21,7 +21,9 @@ TextFile LoadTextFile(std::string file_path)
} }
// Abre el fichero para leer los valores // Abre el fichero para leer los valores
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str(); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str();
#endif
std::ifstream file(file_path); std::ifstream file(file_path);
if (file.is_open() && file.good()) if (file.is_open() && file.good())
@@ -55,7 +57,7 @@ TextFile LoadTextFile(std::string file_path)
// Cierra el fichero // Cierra el fichero
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Text loaded: " << file_name.c_str() << std::endl; std::cout << "Text loaded: " << file_name << std::endl;
#endif #endif
file.close(); file.close();
} }
@@ -64,7 +66,7 @@ TextFile LoadTextFile(std::string file_path)
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name << " file" << std::endl;
#endif #endif
} }
@@ -146,7 +148,7 @@ Text::Text(TextFile *text_file, std::shared_ptr<Texture> texture)
} }
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, int lenght) void Text::write(int x, int y, const std::string &text, int kerning, int lenght)
{ {
auto shift = 0; auto shift = 0;
@@ -169,7 +171,7 @@ void Text::write(int x, int y, std::string text, int kerning, int lenght)
} }
// Escribe el texto con colores // Escribe el texto con colores
void Text::writeColored(int x, int y, std::string text, Color color, int kerning, int lenght) void Text::writeColored(int x, int y, const std::string &text, Color color, int kerning, int lenght)
{ {
sprite_->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
@@ -177,7 +179,7 @@ void Text::writeColored(int x, int y, std::string text, Color color, int kerning
} }
// Escribe el texto con sombra // Escribe el texto con sombra
void Text::writeShadowed(int x, int y, std::string text, Color color, Uint8 shadow_distance, int kerning, int lenght) void Text::writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance, int kerning, int lenght)
{ {
sprite_->getTexture()->setColor(color.r, color.g, color.b); sprite_->getTexture()->setColor(color.r, color.g, color.b);
write(x + shadow_distance, y + shadow_distance, text, kerning, lenght); write(x + shadow_distance, y + shadow_distance, text, kerning, lenght);
@@ -186,14 +188,14 @@ void Text::writeShadowed(int x, int y, std::string text, Color color, Uint8 shad
} }
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void Text::writeCentered(int x, int y, std::string text, int kerning, int lenght) void Text::writeCentered(int x, int y, const std::string &text, int kerning, int lenght)
{ {
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
} }
// Escribe texto con extras // Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght) void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, Color textColor, Uint8 shadow_distance, Color shadow_color, int lenght)
{ {
const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER); const auto centered = ((flags & TEXT_CENTER) == TEXT_CENTER);
const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW); const auto shadowed = ((flags & TEXT_SHADOW) == TEXT_SHADOW);
@@ -235,7 +237,7 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, Col
} }
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int Text::lenght(std::string text, int kerning) const int Text::lenght(const std::string &text, int kerning) const
{ {
auto shift = 0; auto shift = 0;
@@ -267,7 +269,7 @@ void Text::setFixedWidth(bool value)
} }
// Carga una paleta de colores para el texto // Carga una paleta de colores para el texto
void Text::addPalette(std::string path) void Text::addPalette(const std::string &path)
{ {
texture_->addPalette(path); texture_->addPalette(path);
} }

View File

@@ -52,22 +52,22 @@ public:
~Text() = default; ~Text() = default;
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, std::string text, Color color, int kerning = 1, int lenght = -1); void writeColored(int x, int y, const std::string &text, Color color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra // Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1); void writeShadowed(int x, int y, const std::string &text, Color color, Uint8 shadow_distance = 1, int kerning = 1, int lenght = -1);
// Escribe el texto centrado en un punto x // Escribe el texto centrado en un punto x
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, Color textColor = {255, 255, 255}, Uint8 shadow_distance = 1, Color shadow_color = {0, 0, 0}, int lenght = -1); void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, Color textColor = {255, 255, 255}, Uint8 shadow_distance = 1, Color shadow_color = {0, 0, 0}, int lenght = -1);
// Obtiene la longitud en pixels de una cadena // Obtiene la longitud en pixels de una cadena
int lenght(std::string text, int kerning = 1) const; int lenght(const std::string &text, int kerning = 1) const;
// Devuelve el valor de la variable // Devuelve el valor de la variable
int getCharacterSize() const; int getCharacterSize() const;
@@ -79,7 +79,7 @@ public:
void setFixedWidth(bool value); void setFixedWidth(bool value);
// Carga una paleta de colores para el texto // Carga una paleta de colores para el texto
void addPalette(std::string path); void addPalette(const std::string &path);
// Establece una paleta de colores para el texto // Establece una paleta de colores para el texto
void setPalette(int index); void setPalette(int index);

View File

@@ -11,7 +11,7 @@
#include "stb_image.h" // for stbi_failure_reason, stbi_image_free #include "stb_image.h" // for stbi_failure_reason, stbi_image_free
// Constructor // Constructor
Texture::Texture(SDL_Renderer *renderer, std::string path) Texture::Texture(SDL_Renderer *renderer, const std::string &path)
: renderer_(renderer), path_(path) : renderer_(renderer), path_(path)
{ {
// Inicializa // Inicializa
@@ -37,8 +37,8 @@ Texture::Texture(SDL_Renderer *renderer, std::string path)
// .gif // .gif
else if (extension == "gif") else if (extension == "gif")
{ {
surface_ = loadSurface(path_.c_str()); surface_ = loadSurface(path_);
addPalette(path_.c_str()); addPalette(path_);
setPaletteColor(0, 0, 0x00000000); setPaletteColor(0, 0, 0x00000000);
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
@@ -54,13 +54,13 @@ Texture::~Texture()
} }
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
bool Texture::loadFromFile(std::string path) bool Texture::loadFromFile(const std::string &path)
{ {
const std::string file_name = path.substr(path.find_last_of("\\/") + 1); const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int width, height, orig_format; int width, height, orig_format;
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
if (data == nullptr) if (!data)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl; std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl;
@@ -70,19 +70,19 @@ bool Texture::loadFromFile(std::string path)
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Image loaded: " << file_name.c_str() << std::endl; std::cout << "Image loaded: " << file_name << std::endl;
#endif #endif
} }
int depth, pitch; int depth, pitch;
Uint32 pixel_format; Uint32 pixel_format;
if (req_format == STBI_rgb) /*if (req_format == STBI_rgb)
{ {
depth = 24; depth = 24;
pitch = 3 * width; // 3 bytes por pixel * pixels por linea pitch = 3 * width; // 3 bytes por pixel * pixels por linea
pixel_format = SDL_PIXELFORMAT_RGB24; pixel_format = SDL_PIXELFORMAT_RGB24;
} }
else else*/
{ // STBI_rgb_alpha (RGBA) { // STBI_rgb_alpha (RGBA)
depth = 32; depth = 32;
pitch = 4 * width; pitch = 4 * width;
@@ -96,11 +96,11 @@ bool Texture::loadFromFile(std::string path)
SDL_Texture *newTexture = nullptr; SDL_Texture *newTexture = nullptr;
// Carga la imagen desde una ruta específica // Carga la imagen desde una ruta específica
SDL_Surface *loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom((void *)data, width, height, depth, pitch, pixel_format); auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void*>(data), width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr) if (loadedSurface == nullptr)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Unable to load image " << path.c_str() << std::endl; std::cout << "Unable to load image " << path << std::endl;
#endif #endif
} }
else else
@@ -110,7 +110,7 @@ bool Texture::loadFromFile(std::string path)
if (newTexture == nullptr) if (newTexture == nullptr)
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Unable to create texture from " << path.c_str() << "! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create texture from " << path << "! SDL Error: " << SDL_GetError() << std::endl;
#endif #endif
} }
else else
@@ -241,10 +241,10 @@ SDL_Texture *Texture::getSDLTexture()
// Crea una nueva surface // Crea una nueva surface
Surface Texture::newSurface(int w, int h) Surface Texture::newSurface(int w, int h)
{ {
Surface surf = (Surface)malloc(sizeof(surface_s)); Surface surf = static_cast<Surface>(malloc(sizeof(surface_s)));
surf->w = w; surf->w = w;
surf->h = h; surf->h = h;
surf->data = (Uint8 *)malloc(w * h); surf->data = static_cast<Uint8 *>(malloc(w * h));
return surf; return surf;
} }
@@ -265,29 +265,29 @@ void Texture::deleteSurface(Surface surface)
} }
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface Texture::loadSurface(const char *file_name) Surface Texture::loadSurface(const std::string &file_name)
{ {
FILE *f = fopen(file_name, "rb"); FILE *f = fopen(file_name.c_str(), "rb");
if (!f) if (!f)
{ {
return NULL; return nullptr;
} }
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long size = ftell(f); long size = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size); Uint8 *buffer = static_cast<Uint8 *>(malloc(size));
fread(buffer, size, 1, f); fread(buffer, size, 1, f);
fclose(f); fclose(f);
Uint16 w, h; Uint16 w, h;
Uint8 *pixels = LoadGif(buffer, &w, &h); Uint8 *pixels = LoadGif(buffer, &w, &h);
if (pixels == NULL) if (pixels == nullptr)
{ {
return NULL; return nullptr;
} }
Surface surface = (Surface)malloc(sizeof(surface_s)); Surface surface = static_cast<Surface>(malloc(sizeof(surface_s)));
surface->w = w; surface->w = w;
surface->h = h; surface->h = h;
surface->data = pixels; surface->data = pixels;
@@ -312,7 +312,7 @@ void Texture::flipSurface()
// Vuelca los datos // Vuelca los datos
Uint32 *pixels; Uint32 *pixels;
int pitch; int pitch;
SDL_LockTexture(texture_, nullptr, (void **)&pixels, &pitch); SDL_LockTexture(texture_, nullptr, reinterpret_cast<void**>(&pixels), &pitch);
for (int i = 0; i < width_ * height_; ++i) for (int i = 0; i < width_ * height_; ++i)
{ {
pixels[i] = palettes_[paletteIndex_][surface_->data[i]]; pixels[i] = palettes_[paletteIndex_][surface_->data[i]];
@@ -327,11 +327,11 @@ void Texture::setPaletteColor(int palette, int index, Uint32 color)
} }
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> Texture::loadPal(const char *file_name) std::vector<Uint32> Texture::loadPal(const std::string &file_name)
{ {
std::vector<Uint32> palette; std::vector<Uint32> palette;
FILE *f = fopen(file_name, "rb"); FILE *f = fopen(file_name.c_str(), "rb");
if (!f) if (!f)
{ {
return palette; return palette;
@@ -340,12 +340,12 @@ std::vector<Uint32> Texture::loadPal(const char *file_name)
fseek(f, 0, SEEK_END); fseek(f, 0, SEEK_END);
long size = ftell(f); long size = ftell(f);
fseek(f, 0, SEEK_SET); fseek(f, 0, SEEK_SET);
Uint8 *buffer = (Uint8 *)malloc(size); Uint8 *buffer = static_cast<Uint8 *>(malloc(size));
fread(buffer, size, 1, f); fread(buffer, size, 1, f);
fclose(f); fclose(f);
Uint32 *pal = LoadPalette(buffer); auto pal = LoadPalette(buffer);
if (pal == nullptr) if (!pal)
{ {
return palette; return palette;
} }

View File

@@ -39,23 +39,23 @@ private:
void deleteSurface(Surface surface); void deleteSurface(Surface surface);
// Crea una surface desde un fichero .gif // Crea una surface desde un fichero .gif
Surface loadSurface(const char *file_name); Surface loadSurface(const std::string &file_name);
// Vuelca la surface en la textura // Vuelca la surface en la textura
void flipSurface(); void flipSurface();
// Carga una paleta desde un fichero // Carga una paleta desde un fichero
std::vector<Uint32> loadPal(const char *file_name); std::vector<Uint32> loadPal(const std::string &file_name);
public: public:
// Constructor // Constructor
explicit Texture(SDL_Renderer *renderer, std::string path = std::string()); explicit Texture(SDL_Renderer *renderer, const std::string &path = std::string());
// Destructor // Destructor
~Texture(); ~Texture();
// Carga una imagen desde un fichero // Carga una imagen desde un fichero
bool loadFromFile(std::string path); bool loadFromFile(const std::string &path);
// Crea una textura en blanco // Crea una textura en blanco
bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING); bool createBlank(int width, int height, SDL_PixelFormatEnum format = SDL_PIXELFORMAT_RGBA8888, SDL_TextureAccess = SDL_TEXTUREACCESS_STREAMING);

View File

@@ -315,9 +315,9 @@ void Title::resetCounter()
// Intercambia la asignación de mandos a los jugadores // Intercambia la asignación de mandos a los jugadores
void Title::swapControllers() void Title::swapControllers()
{ {
const int num_controllers_ = input_->getNumControllers(); const auto num_controllers = input_->getNumControllers();
if (num_controllers_ == 0) if (num_controllers == 0)
{ {
return; return;
} }

View File

@@ -29,210 +29,112 @@ double distanceSquared(int x1, int y1, int x2, int y2)
} }
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(Circle &a, Circle &b) bool checkCollision(const Circle &a, const Circle &b)
{ {
// Calcula el radio total al cuadrado // Calcula el radio total al cuadrado
int total_radius_squared = a.r + b.r; int total_radius_squared = (a.r + b.r) * (a.r + b.r);
total_radius_squared = total_radius_squared * total_radius_squared;
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios // Comprueba si la distancia entre los centros de los círculos es inferior a la suma de sus radios
if (distanceSquared(a.x, a.y, b.x, b.y) < (total_radius_squared)) return distanceSquared(a.x, a.y, b.x, b.y) < total_radius_squared;
{
// Los circulos han colisionado
return true;
}
// En caso contrario
return false;
} }
// Detector de colisiones entre un circulo y un rectangulo // Detector de colisiones entre un circulo y un rectangulo
bool checkCollision(Circle &a, SDL_Rect &b) bool checkCollision(const Circle &a, const SDL_Rect &b)
{ {
// Closest point on collision box // Encuentra el punto más cercano en el rectángulo
int cX, cY; int cX = std::clamp(a.x, b.x, b.x + b.w);
int cY = std::clamp(a.y, b.y, b.y + b.h);
// Find closest x offset // Si el punto más cercano está dentro del círculo
if (a.x < b.x) return distanceSquared(a.x, a.y, cX, cY) < a.r * a.r;
{
cX = b.x;
}
else if (a.x > b.x + b.w)
{
cX = b.x + b.w;
}
else
{
cX = a.x;
}
// Find closest y offset
if (a.y < b.y)
{
cY = b.y;
}
else if (a.y > b.y + b.h)
{
cY = b.y + b.h;
}
else
{
cY = a.y;
}
// If the closest point is inside the Circle
if (distanceSquared(a.x, a.y, cX, cY) < a.r * a.r)
{
// This box and the Circle have collided
return true;
}
// If the shapes have not collided
return false;
} }
// Detector de colisiones entre dos rectangulos // Detector de colisiones entre dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b) bool checkCollision(const SDL_Rect &a, const SDL_Rect &b)
{ {
// Calcula las caras del rectangulo a const int leftA = a.x, rightA = a.x + a.w, topA = a.y, bottomA = a.y + a.h;
const int leftA = a.x; const int leftB = b.x, rightB = b.x + b.w, topB = b.y, bottomB = b.y + b.h;
const int rightA = a.x + a.w;
const int topA = a.y;
const int bottomA = a.y + a.h;
// Calcula las caras del rectangulo b
const int leftB = b.x;
const int rightB = b.x + b.w;
const int topB = b.y;
const int bottomB = b.y + b.h;
// Si cualquiera de las caras de a está fuera de b
if (bottomA <= topB) if (bottomA <= topB)
{
return false; return false;
}
if (topA >= bottomB) if (topA >= bottomB)
{
return false; return false;
}
if (rightA <= leftB) if (rightA <= leftB)
{
return false; return false;
}
if (leftA >= rightB) if (leftA >= rightB)
{
return false; return false;
}
// Si ninguna de las caras está fuera de b
return true; return true;
} }
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r) bool checkCollision(const SDL_Point &p, const SDL_Rect &r)
{ {
// Comprueba si el punto está a la izquierda del rectangulo if (p.x < r.x || p.x > r.x + r.w)
if (p.x < r.x)
{
return false; return false;
} if (p.y < r.y || p.y > r.y + r.h)
// Comprueba si el punto está a la derecha del rectangulo
if (p.x > r.x + r.w)
{
return false; return false;
}
// Comprueba si el punto está por encima del rectangulo
if (p.y < r.y)
{
return false;
}
// Comprueba si el punto está por debajo del rectangulo
if (p.y > r.y + r.h)
{
return false;
}
// Si no está fuera, es que está dentro
return true; return true;
} }
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(std::string str) bool stringToBool(const std::string &str)
{ {
return str == "true" ? true : false; return str == "true";
} }
// Convierte un valor booleano en una cadena // Convierte un valor booleano en una cadena
std::string boolToString(bool value) std::string boolToString(bool value)
{ {
return value == true ? "true" : "false"; return value ? "true" : "false";
} }
// Convierte un valor booleano en una cadena "on" o "off" // Convierte un valor booleano en una cadena "on" o "off"
std::string boolToOnOff(bool value) std::string boolToOnOff(bool value)
{ {
return value == true ? "on" : "off"; return value ? "on" : "off";
} }
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str) std::string toLower(const std::string &str)
{ {
const char *original = str.c_str(); std::string result = str;
char *lower = (char *)malloc(str.size() + 1); std::transform(result.begin(), result.end(), result.begin(),
for (int i = 0; i < (int)str.size(); ++i) [](unsigned char c)
{ { return std::tolower(c); });
char c = original[i]; return result;
lower[i] = (c >= 65 && c <= 90) ? c + 32 : c;
}
lower[str.size()] = 0;
std::string nova(lower);
free(lower);
return nova;
} }
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name) JA_Sound_t *getSound(const std::vector<SoundFile> &sounds, const std::string &name)
{ {
for (auto s : sounds) for (const auto &s : sounds)
{ {
if (s.name == name) if (s.name == name)
{ {
return s.file; return s.file;
} }
} }
return nullptr; return nullptr;
} }
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name) JA_Music_t *getMusic(const std::vector<MusicFile> &music, const std::string &name)
{ {
for (auto m : music) for (const auto &m : music)
{ {
if (m.name == name) if (m.name == name)
{ {
return m.file; return m.file;
} }
} }
return nullptr; return nullptr;
} }
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2) HiScoreEntry sortHiScoreTable(const HiScoreEntry &entry1, const HiScoreEntry &entry2)
{ {
if (entry1.score > entry2.score) return (entry1.score > entry2.score) ? entry1 : entry2;
{
return entry1;
}
return entry2;
} }
// Dibuja un circulo // Dibuja un circulo
@@ -275,41 +177,31 @@ void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_
} }
// Aclara el color // Aclara el color
Color lightenColor(Color color, int amount) Color lightenColor(const Color &color, int amount)
{ {
Color newColor; Color newColor;
newColor.r = std::min(255, (int)color.r + amount); newColor.r = std::min(255, color.r + amount);
newColor.g = std::min(255, (int)color.g + amount); newColor.g = std::min(255, color.g + amount);
newColor.b = std::min(255, (int)color.b + amount); newColor.b = std::min(255, color.b + amount);
return newColor; return newColor;
} }
// Oscurece el color // Oscurece el color
Color DarkenColor(Color color, int amount) Color DarkenColor(const Color &color, int amount)
{ {
Color newColor; Color newColor;
newColor.r = std::max(0, (int)color.r - amount); newColor.r = std::min(255, color.r - +amount);
newColor.g = std::max(0, (int)color.g - amount); newColor.g = std::min(255, color.g - +amount);
newColor.b = std::max(0, (int)color.b - amount); newColor.b = std::min(255, color.b - +amount);
return newColor; return newColor;
} }
// Quita los espacioes en un string // Quita los espacioes en un string
std::string trim(const std::string &str) std::string trim(const std::string &str)
{ {
auto start = str.begin(); auto start = std::find_if_not(str.begin(), str.end(), ::isspace);
while (start != str.end() && std::isspace(*start)) auto end = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
{ return (start < end ? std::string(start, end) : std::string());
start++;
}
auto end = str.end();
do
{
end--;
} while (std::distance(start, end) > 0 && std::isspace(*end));
return std::string(start, end + 1);
} }
// Función de suavizado // Función de suavizado

View File

@@ -235,19 +235,19 @@ struct MusicFile
double distanceSquared(int x1, int y1, int x2, int y2); double distanceSquared(int x1, int y1, int x2, int y2);
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(Circle &a, Circle &b); bool checkCollision(const Circle &a, const Circle &b);
// Detector de colisiones entre un circulo y un rectangulo // Detector de colisiones entre un circulo y un rectangulo
bool checkCollision(Circle &a, SDL_Rect &b); bool checkCollision(const Circle &a, const SDL_Rect &b);
// Detector de colisiones entre un dos rectangulos // Detector de colisiones entre un dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b); bool checkCollision(const SDL_Rect &a, const SDL_Rect &b);
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r); bool checkCollision(const SDL_Point &p, const SDL_Rect &r);
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(std::string str); bool stringToBool(const std::string &str);
// Convierte un valor booleano en una cadena // Convierte un valor booleano en una cadena
std::string boolToString(bool value); std::string boolToString(bool value);
@@ -256,25 +256,25 @@ std::string boolToString(bool value);
std::string boolToOnOff(bool value); std::string boolToOnOff(bool value);
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str); std::string toLower(const std::string &str);
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name); JA_Sound_t *getSound(const std::vector<SoundFile> &sounds, const std::string &name);
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name); JA_Music_t *getMusic(const std::vector<MusicFile> &music, const std::string &name);
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2); HiScoreEntry sortHiScoreTable(const HiScoreEntry &entry1, const HiScoreEntry &entry2);
// Dibuja un circulo // Dibuja un circulo
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius); void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
// Aclara el color // Aclara el color
Color lightenColor(Color color, int amount); Color lightenColor(const Color &color, int amount);
// Oscurece el color // Oscurece el color
Color DarkenColor(Color color, int amount); Color DarkenColor(const Color &color, int amount);
// Quita los espacioes en un string // Quita los espacioes en un string
std::string trim(const std::string &str); std::string trim(const std::string &str);

View File

@@ -4,7 +4,7 @@
#include <memory> #include <memory>
#include "text.h" #include "text.h"
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un bitmap // Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
class Writer class Writer
{ {
private: private: