diff --git a/source/asset.cpp b/source/asset.cpp index 95238f0..8091181 100644 --- a/source/asset.cpp +++ b/source/asset.cpp @@ -28,34 +28,19 @@ Asset *Asset::get() return Asset::asset_; } -// Constructor -Asset::Asset(const std::string &executable_path) - : executable_path_(executable_path.substr(0, executable_path.find_last_of("\\/"))) -{ - longest_name_ = 0; -} - // Añade un elemento a la lista void Asset::add(const std::string &file, AssetType type, bool required, bool absolute) { - AssetItem ai; - ai.file = absolute ? file : executable_path_ + file; - ai.type = type; - ai.required = required; - file_list_.push_back(ai); - - longest_name_ = SDL_max(longest_name_, getFileName(file).size()); + file_list_.emplace_back(absolute ? file : executable_path_ + file, type, required); + longest_name_ = std::max(longest_name_, static_cast(file_list_.back().file.size())); } -// Devuelve el fichero de un elemento de la lista a partir de una cadena +// Devuelve la ruta completa a un fichero a partir de una cadena std::string Asset::get(const std::string &text) const { for (const auto &f : file_list_) { - const size_t last_index = f.file.find_last_of("/") + 1; - const std::string file = f.file.substr(last_index, std::string::npos); - - if (file == text) + if (getFileName(f.file) == text) { return f.file; } diff --git a/source/asset.h b/source/asset.h index fa1eb11..d863bcc 100644 --- a/source/asset.h +++ b/source/asset.h @@ -2,6 +2,7 @@ #include // for string, basic_string #include // for vector +#include "utils.h" enum class AssetType : int { @@ -27,14 +28,17 @@ private: // Estructura para definir un item struct AssetItem { - std::string file; // Ruta del fichero desde la raiz del directorio - enum AssetType type; // Indica el tipo de recurso - bool required; // Indica si es un fichero que debe de existir - // bool absolute; // Indica si la ruta que se ha proporcionado es una ruta absoluta + std::string file; // Ruta del fichero desde la raíz del directorio + AssetType type; // Indica el tipo de recurso + bool required; // Indica si es un fichero que debe de existir + + // Constructor + AssetItem(const std::string &filePath, AssetType assetType, bool isRequired) + : file(filePath), type(assetType), required(isRequired) {} }; // Variables - int longest_name_; // Contiene la longitud del nombre de fichero mas largo + int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo std::vector file_list_; // Listado con todas las rutas a los ficheros std::string executable_path_; // Ruta al ejecutable @@ -45,7 +49,8 @@ private: std::string getTypeName(AssetType type) const; // Constructor - explicit Asset(const std::string &executable_path); + explicit Asset(const std::string &executable_path) + : executable_path_(getPath(executable_path)) {} // Destructor ~Asset() = default; @@ -63,7 +68,7 @@ public: // Añade un elemento a la lista void add(const std::string &file, AssetType type, bool required = true, bool absolute = false); - // Devuelve un elemento de la lista a partir de una cadena + // Devuelve la ruta completa a un fichero a partir de una cadena std::string get(const std::string &text) const; // Comprueba que existen todos los elementos diff --git a/source/background.cpp b/source/background.cpp index 956fecc..e886fd4 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -20,11 +20,6 @@ Background::Background() grass_texture_(Resource::get()->getTexture("game_grass.png")), gradients_texture_(Resource::get()->getTexture("game_sky_colors.png")), - gradient_number_(0), - alpha_(0), - clouds_speed_(0), - transition_(0), - counter_(0), rect_({0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2}), src_rect_({0, 0, 320, 240}), dst_rect_({0, 0, 320, 240}), diff --git a/source/background.h b/source/background.h index 7b64ee7..7d472e5 100644 --- a/source/background.h +++ b/source/background.h @@ -74,11 +74,11 @@ private: SDL_Rect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo SDL_Rect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba SDL_Rect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo - int gradient_number_; // Indica el número de degradado de fondo que se va a dibujar - int alpha_; // Transparencia entre los dos degradados - float clouds_speed_; // Velocidad a la que se desplazan las nubes - float transition_; // Nivel de transición del fondo 0..1 - int counter_; // Contador interno + int gradient_number_ = 0; // Indica el número de degradado de fondo que se va a dibujar + int alpha_ = 0; // Transparencia entre los dos degradados + float clouds_speed_ = 0; // Velocidad a la que se desplazan las nubes + float transition_ = 0; // Nivel de transición del fondo 0..1 + int counter_ = 0; // Contador interno SDL_Rect rect_; // Tamaño del objeto fondo SDL_Rect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla SDL_Rect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla diff --git a/source/balloon.cpp b/source/balloon.cpp index 76d99a7..96f1485 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -13,17 +13,10 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16 pos_y_(y), vel_x_(vel_x), being_created_(creation_timer > 0), - blinking_(false), - enabled_(true), invulnerable_(creation_timer > 0), - stopped_(true), - visible_(true), creation_counter_(creation_timer), creation_counter_ini_(creation_timer), - stopped_counter_(0), kind_(kind), - counter_(0), - travel_y_(1.0f), speed_(speed) { @@ -227,23 +220,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16 break; } - // Valores para el efecto de rebote - bouncing_.enabled = false; - bouncing_.counter = 0; - bouncing_.speed = 2; - bouncing_.zoomW = 1.0f; - bouncing_.zoomH = 1.0f; - bouncing_.despX = 0.0f; - bouncing_.despY = 0.0f; - bouncing_.w = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; - bouncing_.h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; - // Configura el sprite sprite_->setPos({static_cast(pos_x_), static_cast(pos_y_), width_, height_}); - // Tamaño del circulo de colisión - collider_.r = width_ / 2; - // Alinea el circulo de colisión con el objeto updateColliders(); } @@ -726,8 +705,8 @@ Circle &Balloon::getCollider() // Alinea el circulo de colisión con la posición del objeto globo void Balloon::updateColliders() { - collider_.x = Uint16(pos_x_ + collider_.r); - collider_.y = pos_y_ + collider_.r; + collider_.x = static_cast(pos_x_ + collider_.r); + collider_.y = static_cast(pos_y_ + collider_.r); } // Obtiene le valor de la variable diff --git a/source/balloon.h b/source/balloon.h index ed93dd0..c050a38 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -74,49 +74,53 @@ private: // Estructura para las variables para el efecto de los rebotes struct Bouncing { - bool enabled; // Si el efecto está activo - Uint8 counter; // Countador para el efecto - Uint8 speed; // Velocidad a la que transcurre el efecto - float zoomW; // Zoom aplicado a la anchura - float zoomH; // Zoom aplicado a la altura - float despX; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom - float despY; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom - std::vector w; // Vector con los valores de zoom para el ancho del globo - std::vector h; // Vector con los valores de zoom para el alto del globo + bool enabled = false; // Si el efecto está activo + Uint8 counter = 0; // Countador para el efecto + Uint8 speed = 2; // Velocidad a la que transcurre el efecto + float zoomW = 1.0f; // Zoom aplicado a la anchura + float zoomH = 1.0f; // Zoom aplicado a la altura + float despX = 0.0f; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom + float despY = 0.0f; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom + + std::vector w = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Vector con los valores de zoom para el ancho del globo + std::vector h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Vector con los valores de zoom para el alto del globo + + // Constructor por defecto + Bouncing() {} }; // Objetos y punteros std::unique_ptr sprite_; // Sprite del objeto globo // Variables - float pos_x_; // Posición en el eje X - float pos_y_; // Posición en el eje Y - Uint8 width_; // Ancho - Uint8 height_; // Alto - float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - float gravity_; // Aceleración en el eje Y. Modifica la velocidad - float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo - float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y - bool being_created_; // Indica si el globo se está creando - bool blinking_; // Indica si el globo está intermitente - bool enabled_; // Indica si el globo esta activo - bool invulnerable_; // Indica si el globo es invulnerable - bool stopped_; // Indica si el globo está parado - bool visible_; // Indica si el globo es visible - Circle collider_; // Circulo de colisión del objeto - Uint16 creation_counter_; // Temporizador para controlar el estado "creandose" - Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose" - Uint16 score_; // Puntos que da el globo al ser destruido - Uint16 stopped_counter_; // Contador para controlar el estado "parado" - Uint8 kind_; // Tipo de globo - Uint8 menace_; // Cantidad de amenaza que genera el globo - Uint32 counter_; // Contador interno - float travel_y_; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad - float speed_; // Velocidad a la que se mueven los globos - Uint8 size_; // Tamaño del globo - Uint8 power_; // Cantidad de poder que alberga el globo - Bouncing bouncing_; // Contiene las variables para el efecto de rebote + float pos_x_; // Posición en el eje X + float pos_y_; // Posición en el eje Y + Uint8 width_; // Ancho + Uint8 height_; // Alto + float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + float gravity_; // Aceleración en el eje Y. Modifica la velocidad + float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo + float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y + bool being_created_; // Indica si el globo se está creando + bool blinking_ = false; // Indica si el globo está intermitente + bool enabled_ = true; // Indica si el globo esta activo + bool invulnerable_; // Indica si el globo es invulnerable + bool stopped_ = true; // Indica si el globo está parado + bool visible_ = true; // Indica si el globo es visible + Circle collider_ = Circle(0, 0, width_ / 2); // Circulo de colisión del objeto + Uint16 creation_counter_; // Temporizador para controlar el estado "creandose" + Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose" + Uint16 score_; // Puntos que da el globo al ser destruido + Uint16 stopped_counter_ = 0; // Contador para controlar el estado "parado" + Uint8 kind_; // Tipo de globo + Uint8 menace_; // Cantidad de amenaza que genera el globo + Uint32 counter_ = 0; // Contador interno + float travel_y_ = 1.0f; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad + float speed_; // Velocidad a la que se mueven los globos + Uint8 size_; // Tamaño del globo + Uint8 power_; // Cantidad de poder que alberga el globo + Bouncing bouncing_ = Bouncing(); // Contiene las variables para el efecto de rebote // Alinea el circulo de colisión con la posición del objeto globo void updateColliders(); diff --git a/source/game.cpp b/source/game.cpp index 444f3ab..292f183 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -87,15 +87,18 @@ Game::Game(int player_id, int current_stage, bool demo) SDL_SetTextureBlendMode(canvas_, SDL_BLENDMODE_BLEND); // Crea los dos jugadores - players_.emplace_back(std::make_unique(1, (param.game.play_area.first_quarter_x * ((0 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo_.enabled, ¶m.game.play_area.rect, player_textures_[0], player_animations_)); - players_.back()->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL); - players_.back()->setName(lang::getText(53)); - players_.back()->setController(getController(players_.back()->getId())); + { + const int y = param.game.play_area.rect.h - 30; + players_.emplace_back(std::make_unique(1, param.game.play_area.first_quarter_x - 15, y, demo_.enabled, param.game.play_area.rect, player_textures_[0], player_animations_)); + players_.back()->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL); + players_.back()->setName(lang::getText(53)); + players_.back()->setController(getController(players_.back()->getId())); - players_.emplace_back(std::make_unique(2, (param.game.play_area.first_quarter_x * ((1 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo_.enabled, ¶m.game.play_area.rect, player_textures_[1], player_animations_)); - players_.back()->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL); - players_.back()->setName(lang::getText(54)); - players_.back()->setController(getController(players_.back()->getId())); + players_.emplace_back(std::make_unique(2, param.game.play_area.third_quarter_x - 15, y, demo_.enabled, param.game.play_area.rect, player_textures_[1], player_animations_)); + players_.back()->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL); + players_.back()->setName(lang::getText(54)); + players_.back()->setController(getController(players_.back()->getId())); + } // Activa el jugador que coincide con el "player_id" { @@ -1132,7 +1135,7 @@ ItemType Game::dropItem() // Crea un objeto item void Game::createItem(ItemType type, float x, float y) { - items_.emplace_back(std::make_unique(type, x, y, &(param.game.play_area.rect), item_textures_[static_cast(type) - 1], item_animations_[static_cast(type) - 1])); + items_.emplace_back(std::make_unique(type, x, y, param.game.play_area.rect, item_textures_[static_cast(type) - 1], item_animations_[static_cast(type) - 1])); } // Vacia el vector de items @@ -1327,8 +1330,9 @@ void Game::updateBalloonDeployCounter() // Actualiza el juego void Game::update() { - // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego - if (SDL_GetTicks() - ticks_ > TICKS_SPEED_) + constexpr int TICKS_SPEED = 15; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); diff --git a/source/game.h b/source/game.h index 1634251..f1e18df 100644 --- a/source/game.h +++ b/source/game.h @@ -93,7 +93,6 @@ private: static constexpr int GAME_COMPLETED_END_ = 700; static constexpr int GAME_OVER_COUNTER_ = 350; static constexpr int TIME_STOPPED_COUNTER_ = 300; - static constexpr int TICKS_SPEED_ = 15; // Porcentaje de aparición de los objetos static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10; diff --git a/source/hiscore_table.cpp b/source/hiscore_table.cpp index 001b067..5a738b9 100644 --- a/source/hiscore_table.cpp +++ b/source/hiscore_table.cpp @@ -61,8 +61,9 @@ HiScoreTable::~HiScoreTable() // Actualiza las variables void HiScoreTable::update() { - // Actualiza las variables - if (SDL_GetTicks() - ticks_ > TICKS_SPEED_) + constexpr int TICKS_SPEED = 15; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); diff --git a/source/hiscore_table.h b/source/hiscore_table.h index faa3a10..062e902 100644 --- a/source/hiscore_table.h +++ b/source/hiscore_table.h @@ -26,7 +26,6 @@ class HiScoreTable private: // Constantes static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador - static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa // Objetos y punteros SDL_Renderer *renderer_; // El renderizador de la ventana diff --git a/source/instructions.cpp b/source/instructions.cpp index e2a923a..33cfc39 100644 --- a/source/instructions.cpp +++ b/source/instructions.cpp @@ -25,32 +25,22 @@ struct JA_Music_t; // lines 22-22 // Constructor Instructions::Instructions() + : renderer_(Screen::get()->getRenderer()), + texture_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), + backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), + text_(std::make_unique(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"))), + tiled_bg_(std::make_unique((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::STATIC)), + fade_(std::make_unique()) { - // Copia los punteros - renderer_ = Screen::get()->getRenderer(); - - // Crea objetos - text_ = std::make_unique(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt")); - tiled_bg_ = std::make_unique((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::STATIC); - fade_ = std::make_unique(); - // Crea un backbuffer para el renderizador - backbuffer_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height); SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND); // Crea una textura para el texto fijo - texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height); SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); // Inicializa variables section::name = section::Name::INSTRUCTIONS; - ticks_ = 0; - ticks_speed_ = 15; - counter_ = 0; - counter_end_ = 700; view_ = {0, 0, param.game.width, param.game.height}; - sprite_pos_ = {0, 0}; - item_space_ = 2; // Inicializa objetos fade_->setColor(fade_color.r, fade_color.g, fade_color.b); @@ -214,8 +204,9 @@ void Instructions::fillBackbuffer() // Actualiza las variables void Instructions::update() { - // Actualiza las variables - if (SDL_GetTicks() - ticks_ > ticks_speed_) + constexpr int TICKS_SPEED = 15; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); diff --git a/source/instructions.h b/source/instructions.h index 5d060c0..cf1d145 100644 --- a/source/instructions.h +++ b/source/instructions.h @@ -30,24 +30,23 @@ class Instructions { private: // Objetos y punteros + SDL_Renderer *renderer_; // El renderizador de la ventana + SDL_Texture *texture_; // Textura fija con el texto + SDL_Texture *backbuffer_; // Textura para usar como backbuffer + std::vector> item_textures_; // Vector con las texturas de los items std::vector> sprites_; // Vector con los sprites de los items std::unique_ptr text_; // Objeto para escribir texto std::unique_ptr tiled_bg_; // Objeto para dibujar el mosaico animado de fondo std::unique_ptr fade_; // Objeto para renderizar fades - SDL_Renderer *renderer_; // El renderizador de la ventana - SDL_Texture *texture_; // Textura fija con el texto - SDL_Texture *backbuffer_; // Textura para usar como backbuffer - // Variables - int counter_; // Contador - int counter_end_; // Valor final para el contador - Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa - SDL_Rect view_; // Vista del backbuffer que se va amostrar por pantalla - SDL_Point sprite_pos_; // Posición del primer sprite - int item_space_; // Espacio entre los items + int counter_ = 0; // Contador + int counter_end_ = 700; // Valor final para el contador + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + SDL_Rect view_; // Vista del backbuffer que se va amostrar por pantalla + SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite + int item_space_ = 2; // Espacio entre los items // Actualiza las variables void update(); diff --git a/source/intro.cpp b/source/intro.cpp index d383a5b..bb32210 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -21,17 +21,13 @@ struct JA_Music_t; // lines 19-19 // Constructor Intro::Intro() - : texture_(Resource::get()->getTexture("intro.png")) + : texture_(Resource::get()->getTexture("intro.png")), + text_(std::make_shared(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt"))) { - // Reserva memoria para los objetos - text_ = std::make_shared(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt")); // Inicializa variables section::name = section::Name::INTRO; section::options = section::Options::NONE; - ticks_ = 0; - ticks_speed_ = 15; - scene_ = 1; // Inicializa los bitmaps de la intro constexpr int totalBitmaps = 6; @@ -372,7 +368,9 @@ void Intro::updateScenes() // Actualiza las variables del objeto void Intro::update() { - if (SDL_GetTicks() - ticks_ > ticks_speed_) + constexpr int TICKS_SPEED = 15; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks ticks_ = SDL_GetTicks(); diff --git a/source/intro.h b/source/intro.h index eb0e739..441b286 100644 --- a/source/intro.h +++ b/source/intro.h @@ -26,9 +26,8 @@ private: std::vector> texts_; // Textos de la intro // Variables - Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa - Uint8 ticks_speed_; // Velocidad a la que se repiten los bucles del programa - int scene_; // Indica que escena está activa + Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa + int scene_ = 1; // Indica que escena está activa // Actualiza las variables del objeto void update(); diff --git a/source/item.cpp b/source/item.cpp index 0e4fb06..c35e8eb 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -5,27 +5,26 @@ class Texture; // Constructor -Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr texture, const std::vector &animation) +Item::Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr texture, const std::vector &animation) : sprite_(std::make_unique(texture, animation)), - accel_x_(0.0f), - floor_collision_(false), type_(type), - enabled_(true), - play_area_(play_area), - time_to_live_(600) + play_area_(play_area) { - if (type == ItemType::COFFEE_MACHINE) + switch (type) + { + case ItemType::COFFEE_MACHINE: { width_ = 28; height_ = 37; - pos_x_ = (((int)x + (play_area->w / 2)) % (play_area->w - width_ - 5)) + 2; + pos_x_ = ((static_cast(x) + (play_area.w / 2)) % (play_area.w - width_ - 5)) + 2; pos_y_ = -height_; vel_x_ = 0.0f; vel_y_ = -0.1f; accel_y_ = 0.1f; collider_.r = 10; + break; } - else + default: { width_ = 20; height_ = 20; @@ -35,6 +34,8 @@ Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr vel_y_ = -4.0f; accel_y_ = 0.2f; collider_.r = width_ / 2; + break; + } } sprite_->setPosX(pos_x_); @@ -45,20 +46,20 @@ Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr // Centra el objeto en la posición X void Item::allignTo(int x) { - pos_x_ = float(x - (width_ / 2)); + pos_x_ = static_cast(x - (width_ / 2)); if (pos_x_ < param.game.play_area.rect.x) { pos_x_ = param.game.play_area.rect.x + 1; } - else if ((pos_x_ + width_) > play_area_->w) + else if (pos_x_ + width_ > play_area_.w) { - pos_x_ = float(play_area_->w - width_ - 1); + pos_x_ = static_cast(play_area_.w - width_ - 1); } // Posición X,Y del sprite - sprite_->setPosX(int(pos_x_)); - sprite_->setPosY(int(pos_y_)); + sprite_->setPosX(pos_x_); + sprite_->setPosY(pos_y_); // Alinea el circulo de colisión con el objeto shiftColliders(); @@ -94,7 +95,7 @@ void Item::move() vel_y_ += accel_y_; // Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido - if ((pos_x_ < param.game.play_area.rect.x) || (pos_x_ + width_ > play_area_->w)) + if ((pos_x_ < param.game.play_area.rect.x) || (pos_x_ + width_ > play_area_.w)) { // Corregir posición pos_x_ -= vel_x_; @@ -114,14 +115,14 @@ void Item::move() } // Si el objeto se sale por la parte inferior - if (pos_y_ + height_ > play_area_->h) + if (pos_y_ + height_ > play_area_.h) { // Detiene el objeto vel_y_ = 0; vel_x_ = 0; accel_x_ = 0; accel_y_ = 0; - pos_y_ = play_area_->h - height_; + pos_y_ = play_area_.h - height_; if (type_ == ItemType::COFFEE_MACHINE) { floor_collision_ = true; diff --git a/source/item.h b/source/item.h index 5c951d5..c774dfc 100644 --- a/source/item.h +++ b/source/item.h @@ -29,20 +29,20 @@ private: std::unique_ptr sprite_; // Sprite con los graficos del objeto // Variables - float pos_x_; // Posición X del objeto - float pos_y_; // Posición Y del objeto - int width_; // Ancho del objeto - int height_; // Alto del objeto - float vel_x_; // Velocidad en el eje X - float vel_y_; // Velocidad en el eje Y - float accel_x_; // Aceleración en el eje X - float accel_y_; // Aceleración en el eje Y - bool floor_collision_; // Indica si el objeto colisiona con el suelo - ItemType type_; // Especifica el tipo de objeto que es - bool enabled_; // Especifica si el objeto está habilitado - Circle collider_; // Circulo de colisión del objeto - SDL_Rect *play_area_; // Rectangulo con la zona de juego - Uint16 time_to_live_; // Temporizador con el tiempo que el objeto está presente + float pos_x_; // Posición X del objeto + float pos_y_; // Posición Y del objeto + int width_; // Ancho del objeto + int height_; // Alto del objeto + float vel_x_; // Velocidad en el eje X + float vel_y_; // Velocidad en el eje Y + float accel_x_ = 0.0f; // Aceleración en el eje X + float accel_y_; // Aceleración en el eje Y + bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo + ItemType type_; // Especifica el tipo de objeto que es + bool enabled_ = true; // Especifica si el objeto está habilitado + Circle collider_; // Circulo de colisión del objeto + SDL_Rect play_area_; // Rectangulo con la zona de juego + Uint16 time_to_live_ = 600; // Temporizador con el tiempo que el objeto está presente // Alinea el circulo de colisión con la posición del objeto void shiftColliders(); @@ -58,7 +58,7 @@ private: public: // Constructor - Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr texture, const std::vector &animation); + Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr texture, const std::vector &animation); // Destructor ~Item() = default; diff --git a/source/logo.cpp b/source/logo.cpp index 8919c41..a8237f9 100644 --- a/source/logo.cpp +++ b/source/logo.cpp @@ -165,7 +165,8 @@ void Logo::updateTextureColors() // Actualiza las variables void Logo::update() { - // Comprueba que la diferencia de ticks sea mayor a la velocidad del juego + constexpr int TICKS_SPEED = 15; + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks diff --git a/source/logo.h b/source/logo.h index 6efe103..2cc5611 100644 --- a/source/logo.h +++ b/source/logo.h @@ -21,7 +21,6 @@ class Logo { private: // Constantes - static constexpr Uint32 TICKS_SPEED = 15; // Velocidad a la que se repiten los bucles del programa static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998" static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo diff --git a/source/player.cpp b/source/player.cpp index 9da0ba9..b274eeb 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -11,26 +11,18 @@ #include "options.h" // Constructor -Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector> texture, const std::vector> &animations) +Player::Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector> texture, const std::vector> &animations) : player_sprite_(std::make_unique(texture[0], animations[0])), power_sprite_(std::make_unique(texture[1], animations[1])), enter_name_(std::make_unique()), - play_area_(play_area), id_(id), - pos_x_(x), - pos_y_(y), + play_area_(play_area), 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 + // Configura objetos power_sprite_->getTexture()->setAlpha(224); - - // Establece los offsets para el sprite de PowerUp power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2; power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight())); @@ -46,25 +38,21 @@ void Player::init() pos_x_ = default_pos_x_; pos_y_ = default_pos_y_; status_walking_ = PlayerStatus::WALKING_STOP; - status_firing_ = PlayerStatus::FIRING_NO; + status_firing_ = PlayerStatus::FIRING_NONE; + status_playing_ = PlayerStatus::WAITING; invulnerable_ = true; - invulnerable_counter_ = PLAYER_INVULNERABLE_COUNTER; + invulnerable_counter_ = INVULNERABLE_COUNTER_; power_up_ = false; - power_up_counter_ = PLAYER_POWERUP_COUNTER; + power_up_counter_ = POWERUP_COUNTER_; extra_hit_ = false; coffees_ = 0; - input_ = true; continue_ticks_ = 0; continue_counter_ = 10; enter_name_ticks_ = 0; enter_name_counter_ = param.game.enter_name_seconds; - width_ = 30; - height_ = 30; - collider_.r = 9; shiftColliders(); vel_x_ = 0; vel_y_ = 0; - base_speed_ = 1.5; score_ = 0; score_multiplier_ = 1.0f; cooldown_ = 10; @@ -107,14 +95,14 @@ void Player::setInputPlaying(InputType input) { case InputType::LEFT: { - vel_x_ = -base_speed_; + vel_x_ = -BASE_SPEED_; setWalkingStatus(PlayerStatus::WALKING_LEFT); break; } case InputType::RIGHT: { - vel_x_ = base_speed_; + vel_x_ = BASE_SPEED_; setWalkingStatus(PlayerStatus::WALKING_RIGHT); break; } @@ -186,7 +174,7 @@ void Player::move() pos_x_ += vel_x_; // Si el jugador abandona el area de juego por los laterales - if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + width_ > play_area_->w + 5)) + if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + WIDTH_ > play_area_.w + 5)) { // Restaura su posición pos_x_ -= vel_x_; @@ -203,7 +191,7 @@ void Player::move() player_sprite_->update(); // Si el cadaver abandona el area de juego por los laterales - if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + width_ > play_area_->w)) + if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w)) { // Restaura su posición const float vx = player_sprite_->getVelX(); @@ -226,7 +214,7 @@ void Player::render() { if (power_up_ && isPlaying()) { - if (power_up_counter_ > (PLAYER_POWERUP_COUNTER / 4) || power_up_counter_ % 20 > 4) + if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4) { power_sprite_->render(); } @@ -261,7 +249,7 @@ void Player::setAnimation() // Establece la animación a partir de las cadenas if (isPlaying()) { - if (status_firing_ == PlayerStatus::FIRING_NO) + if (status_firing_ == PlayerStatus::FIRING_NONE) { // No esta disparando player_sprite_->setCurrentAnimation(a_walking); player_sprite_->setFlip(flip_walk); @@ -301,13 +289,13 @@ int Player::getPosY() const // Obtiene el valor de la variable int Player::getWidth() const { - return width_; + return WIDTH_; } // Obtiene el valor de la variable int Player::getHeight() const { - return height_; + return HEIGHT_; } // Indica si el jugador puede disparar @@ -336,7 +324,7 @@ void Player::updateCooldown() } else { - setFiringStatus(PlayerStatus::FIRING_NO); + setFiringStatus(PlayerStatus::FIRING_NONE); } } @@ -459,8 +447,8 @@ void Player::setStatusPlaying(PlayerStatus value) { case PlayerStatus::PLAYING: { - status_playing_ = PlayerStatus::PLAYING; init(); + status_playing_ = PlayerStatus::PLAYING; setScoreboardMode(ScoreboardMode::SCORE); break; } @@ -556,7 +544,7 @@ bool Player::isInvulnerable() const void Player::setInvulnerable(bool value) { invulnerable_ = value; - invulnerable_counter_ = invulnerable_ ? PLAYER_INVULNERABLE_COUNTER : 0; + invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0; } // Obtiene el valor de la variable @@ -599,7 +587,7 @@ bool Player::isPowerUp() const void Player::setPowerUp() { power_up_ = true; - power_up_counter_ = PLAYER_POWERUP_COUNTER; + power_up_counter_ = POWERUP_COUNTER_; } // Obtiene el valor de la variable @@ -654,18 +642,6 @@ void Player::removeExtraHit() extra_hit_ = coffees_ == 0 ? false : true; } -// Habilita la entrada de ordenes -void Player::enableInput() -{ - input_ = true; -} - -// Deshabilita la entrada de ordenes -void Player::disableInput() -{ - input_ = false; -} - // Devuelve el número de cafes actuales int Player::getCoffees() const { @@ -681,8 +657,8 @@ Circle &Player::getCollider() // Actualiza el circulo de colisión a la posición del jugador void Player::shiftColliders() { - collider_.x = int(pos_x_ + (width_ / 2)); - collider_.y = int(pos_y_ + (height_ / 2)); + collider_.x = static_cast(pos_x_ + (WIDTH_ / 2)); + collider_.y = static_cast(pos_y_ + (HEIGHT_ / 2)); } // Pone las texturas del jugador @@ -703,9 +679,8 @@ void Player::updateContinueCounter() { if (status_playing_ == PlayerStatus::CONTINUE) { - constexpr Uint32 ticks_speed = 1000; - - if (SDL_GetTicks() - continue_ticks_ > ticks_speed) + constexpr int TICKS_SPEED = 1000; + if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED) { decContinueCounter(); } @@ -717,9 +692,8 @@ void Player::updateEnterNameCounter() { if (status_playing_ == PlayerStatus::ENTERING_NAME) { - constexpr Uint32 ticks_speed = 1000; - - if (SDL_GetTicks() - enter_name_ticks_ > ticks_speed) + constexpr int TICKS_SPEED = 1000; + if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED) { decEnterNameCounter(); } diff --git a/source/player.h b/source/player.h index 8e128bc..550aa1c 100644 --- a/source/player.h +++ b/source/player.h @@ -23,7 +23,7 @@ enum class PlayerStatus FIRING_UP, FIRING_LEFT, FIRING_RIGHT, - FIRING_NO, + FIRING_NONE, PLAYING, CONTINUE, @@ -35,54 +35,55 @@ enum class PlayerStatus }; // Variables del jugador -constexpr int PLAYER_INVULNERABLE_COUNTER = 200; -constexpr int PLAYER_POWERUP_COUNTER = 1500; // Clase Player class Player { private: + // Constantes + static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp + static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable + static constexpr int WIDTH_ = 30; // Anchura + static constexpr int HEIGHT_ = 30; // Altura + static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador + // Objetos y punteros std::unique_ptr player_sprite_; // Sprite para dibujar el jugador std::unique_ptr power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope std::unique_ptr enter_name_; // Clase utilizada para introducir el nombre - SDL_Rect *play_area_; // Rectangulo con la zona de juego // Variables - int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 - float pos_x_; // Posicion en el eje X - int pos_y_; // Posicion en el eje Y - float default_pos_x_; // Posición inicial para el jugador - int default_pos_y_; // Posición inicial para el jugador - int width_; // Anchura - int height_; // Altura - float vel_x_; // Cantidad de pixeles a desplazarse en el eje X - int vel_y_; // Cantidad de pixeles a desplazarse en el eje Y - float base_speed_; // Velocidad base del jugador - int cooldown_; // Contador durante el cual no puede disparar - int score_; // Puntos del jugador - float score_multiplier_; // Multiplicador de puntos - PlayerStatus status_walking_; // Estado del jugador al moverse - PlayerStatus status_firing_; // Estado del jugador al disparar - PlayerStatus status_playing_; // Estado del jugador en el juego - bool invulnerable_; // Indica si el jugador es invulnerable - int invulnerable_counter_; // Contador para la invulnerabilidad - bool extra_hit_; // Indica si el jugador tiene un toque extra - int coffees_; // Indica cuantos cafes lleva acumulados - bool power_up_; // Indica si el jugador tiene activo el modo PowerUp - int power_up_counter_; // Temporizador para el modo PowerUp - int power_up_desp_x_; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador - bool input_; // Indica si puede recibir ordenes de entrada - Circle collider_; // Circulo de colisión del jugador - int continue_counter_; // Contador para poder continuar - Uint32 continue_ticks_; // Variable para poder cambiar el contador de continue en función del tiempo - int scoreboard_panel_; // Panel del marcador asociado al jugador - std::string name_; // Nombre del jugador - std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones - int controller_index_; // Indice del array de mandos que utilizará para moverse - bool demo_; // Para que el jugador sepa si está en el modo demostración - int enter_name_counter_; // Contador para poner nombre - Uint32 enter_name_ticks_; // Variable para poder cambiar el contador de poner nombre en función del tiempo + int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2 + SDL_Rect play_area_; // Rectangulo con la zona de juego + float pos_x_ = 0.0f; // Posicion en el eje X + int pos_y_ = 0; // Posicion en el eje Y + float default_pos_x_; // Posición inicial para el jugador + int default_pos_y_; // Posición inicial para el jugador + float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X + int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y + int cooldown_ = 10; // Contador durante el cual no puede disparar + int score_ = 0; // Puntos del jugador + float score_multiplier_ = 1.0f; // Multiplicador de puntos + PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse + PlayerStatus status_firing_ = PlayerStatus::FIRING_NONE; // Estado del jugador al disparar + PlayerStatus status_playing_ = PlayerStatus::WAITING; // Estado del jugador en el juego + bool invulnerable_ = true; // Indica si el jugador es invulnerable + int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad + bool extra_hit_ = false; // Indica si el jugador tiene un toque extra + int coffees_ = 0; // Indica cuantos cafes lleva acumulados + bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp + int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp + int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador + Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador + int continue_counter_ = 10; // Contador para poder continuar + Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo + int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador + std::string name_; // Nombre del jugador + std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones + int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse + bool demo_; // Para que el jugador sepa si está en el modo demostración + int enter_name_counter_; // Contador para poner nombre + Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo // Actualiza el circulo de colisión a la posición del jugador void shiftColliders(); @@ -113,7 +114,7 @@ private: public: // Constructor - Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector> texture, const std::vector> &animations); + Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector> texture, const std::vector> &animations); // Destructor ~Player() = default; @@ -256,12 +257,6 @@ public: // Quita el toque extra al jugador void removeExtraHit(); - // Habilita la entrada de ordenes - void enableInput(); - - // Deshabilita la entrada de ordenes - void disableInput(); - // Devuelve el número de cafes actuales int getCoffees() const; diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 5b4cae5..45bfe79 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -98,7 +98,9 @@ std::string Scoreboard::updateScoreText(int num) // Actualiza el contador void Scoreboard::updateCounter() { - if (SDL_GetTicks() - ticks_ > SCOREBOARD_TICK_SPEED_) + constexpr int TICKS_SPEED = 100; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { ticks_ = SDL_GetTicks(); counter_++; diff --git a/source/scoreboard.h b/source/scoreboard.h index 8e8c7ba..58e1ec8 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -42,9 +42,6 @@ struct Panel class Scoreboard { private: - // Constantes - static constexpr int SCOREBOARD_TICK_SPEED_ = 100; - // [SINGLETON] Objeto scoreboard privado para Don Melitón static Scoreboard *scoreboard_; diff --git a/source/title.cpp b/source/title.cpp index 57d0e9e..0ff91fa 100644 --- a/source/title.cpp +++ b/source/title.cpp @@ -54,8 +54,9 @@ Title::~Title() // Actualiza las variables del objeto void Title::update() { - // Calcula la lógica de los objetos - if (SDL_GetTicks() - ticks_ > TICKS_SPEED_) + constexpr int TICKS_SPEED = 15; + + if (SDL_GetTicks() - ticks_ > TICKS_SPEED) { // Actualiza el contador de ticks_ ticks_ = SDL_GetTicks(); diff --git a/source/title.h b/source/title.h index 0a85380..ad80e85 100644 --- a/source/title.h +++ b/source/title.h @@ -43,9 +43,6 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = true; class Title { private: - // Constantes - static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa - // Objetos y punteros std::unique_ptr text1_; // Objeto de texto para poder escribir textos en pantalla std::unique_ptr text2_; // Objeto de texto para poder escribir textos en pantalla diff --git a/source/utils.cpp b/source/utils.cpp index 4de79b9..ccd8a0e 100644 --- a/source/utils.cpp +++ b/source/utils.cpp @@ -274,8 +274,15 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd) } #endif // RECORDING -// Obtiene el nombre de un fichero a partir de una ruta +// Obtiene el nombre de un fichero a partir de una ruta completa std::string getFileName(const std::string &path) { return std::filesystem::path(path).filename().string(); } + +// Obtiene la ruta eliminando el nombre del fichero +std::string getPath(const std::string &full_path) +{ + std::filesystem::path path(full_path); + return path.parent_path().string(); +} diff --git a/source/utils.h b/source/utils.h index 44448be..46cdef9 100644 --- a/source/utils.h +++ b/source/utils.h @@ -47,6 +47,13 @@ extern Overrides overrides; struct Circle { int x, y, r; + + // Constructor por defecto + Circle() : x(0), y(0), r(0) {} + + // Constructor + Circle(int xCoord, int yCoord, int radius) + : x(xCoord), y(yCoord), r(radius) {} }; // Estructura para definir un color @@ -319,6 +326,9 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd); // Obtiene el nombre de un fichero a partir de una ruta std::string getFileName(const std::string &path); +// Obtiene la ruta eliminando el nombre del fichero +std::string getPath(const std::string &full_path); + // Colores extern const Color bg_color; extern const Color no_color;