From f2fa216b0dbae1bc4f5b62501f9904571704938f Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Wed, 9 Oct 2024 21:48:01 +0200 Subject: [PATCH] Commit pa que Mon arregle el codi mentre em dutxe --- source/animated_sprite.cpp | 174 +++++----- source/animated_sprite.h | 27 +- source/background.cpp | 40 +-- source/background.h | 32 +- source/balloon.cpp | 2 +- source/balloon.h | 4 +- source/bullet.cpp | 2 +- source/bullet.h | 4 +- source/explosions.cpp | 13 +- source/explosions.h | 9 +- source/game.cpp | 653 ++++++++++++++----------------------- source/game.h | 93 +++--- source/game_logo.cpp | 4 +- source/intro.cpp | 36 +- source/intro.h | 5 +- source/item.cpp | 10 +- source/item.h | 11 +- source/moving_sprite.cpp | 248 +++++--------- source/moving_sprite.h | 103 ++---- source/notify.cpp | 8 +- source/notify.h | 6 +- source/player.cpp | 4 +- source/player.h | 6 +- source/scoreboard.cpp | 6 +- source/scoreboard.h | 8 +- source/smart_sprite.cpp | 111 +++---- source/smart_sprite.h | 35 +- source/sprite.cpp | 89 +++-- source/sprite.h | 56 ++-- source/texture.cpp | 120 +++---- source/texture.h | 16 +- source/tiled_bg.cpp | 12 +- source/writer.cpp | 93 +++--- source/writer.h | 40 ++- 34 files changed, 862 insertions(+), 1218 deletions(-) diff --git a/source/animated_sprite.cpp b/source/animated_sprite.cpp index 6658f03..a818d81 100644 --- a/source/animated_sprite.cpp +++ b/source/animated_sprite.cpp @@ -1,19 +1,19 @@ #include "animated_sprite.h" -#include // for basic_ostream, operator<<, basic_istream, basic... -#include // for cout -#include // for basic_stringstream -#include "texture.h" // for Texture +#include // for basic_ostream, operator<<, basic_istream, basic... +#include // for cout +#include // for basic_stringstream +#include "texture.h" // for Texture // Carga la animación desde un fichero -animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose) +animatedSprite_t loadAnimationFromFile(std::shared_ptr texture, std::string filePath) { // Inicializa variables animatedSprite_t as; as.texture = texture; - int framesPerRow = 0; - int frameWidth = 0; - int frameHeight = 0; - int maxTiles = 0; + auto framesPerRow = 0; + auto frameWidth = 0; + auto frameHeight = 0; + auto maxTiles = 0; const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1); std::ifstream file(filePath); @@ -23,16 +23,15 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b if (file.good()) { // Procesa el fichero linea a linea - if (verbose) - { - std::cout << "Animation loaded: " << filename << std::endl; - } +#ifdef VERBOSE + std::cout << "Animation loaded: " << filename << std::endl; +#endif while (std::getline(file, line)) { // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación if (line == "[animation]") { - animation_t buffer; + Animation buffer; buffer.counter = 0; buffer.currentFrame = 0; buffer.completed = false; @@ -71,7 +70,7 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b while (getline(ss, tmp, ',')) { // Comprueba que el tile no sea mayor que el maximo indice permitido - const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp); + const auto numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp); rect.x = (numTile % framesPerRow) * frameWidth; rect.y = (numTile / framesPerRow) * frameHeight; buffer.frames.push_back(rect); @@ -80,7 +79,9 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b else { +#ifdef VERBOSE std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; +#endif } } } while (line != "[/animation]"); @@ -115,7 +116,9 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b else { +#ifdef VERBOSE std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; +#endif } // Normaliza valores @@ -126,8 +129,8 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) { - const int w = texture->getWidth() / frameWidth; - const int h = texture->getHeight() / frameHeight; + const auto w = texture->getWidth() / frameWidth; + const auto h = texture->getHeight() / frameHeight; maxTiles = w * h; } } @@ -140,17 +143,16 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b // El fichero no se puede abrir else { - if (verbose) - { - std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; - } +#ifdef VERBOSE + std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; +#endif } return as; } // Constructor -AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vector *buffer) +AnimatedSprite::AnimatedSprite(std::shared_ptr texture, std::string file, std::vector *buffer) { // Copia los punteros setTexture(texture); @@ -163,7 +165,7 @@ AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vectoranimation.push_back(animation); + animations_.push_back(animation); } } @@ -173,7 +175,7 @@ AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vectortexture); // Inicializa variables - currentAnimation = 0; + currentAnimation_ = 0; // Copia los datos de las animaciones for (auto a : animation->animations) { - this->animation.push_back(a); + animations_.push_back(a); } } // Destructor AnimatedSprite::~AnimatedSprite() { - animation.clear(); + animations_.clear(); } // Obtiene el indice de la animación a partir del nombre int AnimatedSprite::getIndex(std::string name) { - int index = -1; + auto index = -1; - for (auto a : animation) + for (auto a : animations_) { index++; if (a.name == name) @@ -211,147 +213,147 @@ int AnimatedSprite::getIndex(std::string name) return index; } } - +#ifdef VERBOSE std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; - +#endif return -1; } // Calcula el frame correspondiente a la animación void AnimatedSprite::animate() { - if (!enabled || animation[currentAnimation].speed == 0) + if (!enabled_ || animations_[currentAnimation_].speed == 0) { return; } // Calcula el frame actual a partir del contador - animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed; + animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].counter / animations_[currentAnimation_].speed; // Si alcanza el final de la animación, reinicia el contador de la animación // en función de la variable loop y coloca el nuevo frame - if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size()) + if (animations_[currentAnimation_].currentFrame >= (int)animations_[currentAnimation_].frames.size()) { - if (animation[currentAnimation].loop == -1) + if (animations_[currentAnimation_].loop == -1) { // Si no hay loop, deja el último frame - animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size(); - animation[currentAnimation].completed = true; + animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].frames.size(); + animations_[currentAnimation_].completed = true; } else { // Si hay loop, vuelve al frame indicado - animation[currentAnimation].counter = 0; - animation[currentAnimation].currentFrame = animation[currentAnimation].loop; + animations_[currentAnimation_].counter = 0; + animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].loop; } } // En caso contrario else { // Escoge el frame correspondiente de la animación - setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); + setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]); // Incrementa el contador de la animacion - animation[currentAnimation].counter++; + animations_[currentAnimation_].counter++; } } // Obtiene el número de frames de la animación actual int AnimatedSprite::getNumFrames() { - return (int)animation[currentAnimation].frames.size(); + return (int)animations_[currentAnimation_].frames.size(); } // Establece el frame actual de la animación void AnimatedSprite::setCurrentFrame(int num) { // Descarta valores fuera de rango - if (num >= (int)animation[currentAnimation].frames.size()) + if (num >= (int)animations_[currentAnimation_].frames.size()) { num = 0; } // Cambia el valor de la variable - animation[currentAnimation].currentFrame = num; - animation[currentAnimation].counter = 0; + animations_[currentAnimation_].currentFrame = num; + animations_[currentAnimation_].counter = 0; // Escoge el frame correspondiente de la animación - setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]); + setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]); } // Establece el valor del contador void AnimatedSprite::setAnimationCounter(std::string name, int num) { - animation[getIndex(name)].counter = num; + animations_[getIndex(name)].counter = num; } // Establece la velocidad de una animación void AnimatedSprite::setAnimationSpeed(std::string name, int speed) { - animation[getIndex(name)].counter = speed; + animations_[getIndex(name)].counter = speed; } // Establece la velocidad de una animación void AnimatedSprite::setAnimationSpeed(int index, int speed) { - animation[index].counter = speed; + animations_[index].counter = speed; } // Establece si la animación se reproduce en bucle void AnimatedSprite::setAnimationLoop(std::string name, int loop) { - animation[getIndex(name)].loop = loop; + animations_[getIndex(name)].loop = loop; } // Establece si la animación se reproduce en bucle void AnimatedSprite::setAnimationLoop(int index, int loop) { - animation[index].loop = loop; + animations_[index].loop = loop; } // Establece el valor de la variable void AnimatedSprite::setAnimationCompleted(std::string name, bool value) { - animation[getIndex(name)].completed = value; + animations_[getIndex(name)].completed = value; } // OLD - Establece el valor de la variable void AnimatedSprite::setAnimationCompleted(int index, bool value) { - animation[index].completed = value; + animations_[index].completed = value; } // Comprueba si ha terminado la animación bool AnimatedSprite::animationIsCompleted() { - return animation[currentAnimation].completed; + return animations_[currentAnimation_].completed; } // Devuelve el rectangulo de una animación y frame concreto SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index) { - return animation[getIndex(name)].frames[index]; + return animations_[getIndex(name)].frames[index]; } // Devuelve el rectangulo de una animación y frame concreto SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF) { - return animation[indexA].frames[indexF]; + return animations_[indexA].frames[indexF]; } // Carga la animación desde un vector bool AnimatedSprite::loadFromVector(std::vector *source) { // Inicializa variables - int framesPerRow = 0; - int frameWidth = 0; - int frameHeight = 0; - int maxTiles = 0; + auto framesPerRow = 0; + auto frameWidth = 0; + auto frameHeight = 0; + auto maxTiles = 0; // Indicador de éxito en el proceso - bool success = true; + auto success = true; std::string line; // Recorre todo el vector - int index = 0; + auto index = 0; while (index < (int)source->size()) { // Lee desde el vector @@ -360,7 +362,7 @@ bool AnimatedSprite::loadFromVector(std::vector *source) // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación if (line == "[animation]") { - animation_t buffer; + Animation buffer; buffer.counter = 0; buffer.currentFrame = 0; buffer.completed = false; @@ -410,14 +412,16 @@ bool AnimatedSprite::loadFromVector(std::vector *source) else { +#ifdef VERBOSE std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl; +#endif success = false; } } } while (line != "[/animation]"); // Añade la animación al vector de animaciones - animation.push_back(buffer); + animations_.push_back(buffer); } // En caso contrario se parsea el fichero para buscar las variables y los valores @@ -446,20 +450,22 @@ bool AnimatedSprite::loadFromVector(std::vector *source) else { +#ifdef VERBOSE std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl; +#endif success = false; } // Normaliza valores if (framesPerRow == 0 && frameWidth > 0) { - framesPerRow = texture->getWidth() / frameWidth; + framesPerRow = texture_->getWidth() / frameWidth; } if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) { - const int w = texture->getWidth() / frameWidth; - const int h = texture->getHeight() / frameHeight; + const int w = texture_->getWidth() / frameWidth; + const int h = texture_->getHeight() / frameHeight; maxTiles = w * h; } } @@ -478,26 +484,26 @@ bool AnimatedSprite::loadFromVector(std::vector *source) // Establece la animacion actual void AnimatedSprite::setCurrentAnimation(std::string name) { - const int newAnimation = getIndex(name); - if (currentAnimation != newAnimation) + const auto newAnimation = getIndex(name); + if (currentAnimation_ != newAnimation) { - currentAnimation = newAnimation; - animation[currentAnimation].currentFrame = 0; - animation[currentAnimation].counter = 0; - animation[currentAnimation].completed = false; + currentAnimation_ = newAnimation; + animations_[currentAnimation_].currentFrame = 0; + animations_[currentAnimation_].counter = 0; + animations_[currentAnimation_].completed = false; } } // Establece la animacion actual void AnimatedSprite::setCurrentAnimation(int index) { - const int newAnimation = index; - if (currentAnimation != newAnimation) + const auto newAnimation = index; + if (currentAnimation_ != newAnimation) { - currentAnimation = newAnimation; - animation[currentAnimation].currentFrame = 0; - animation[currentAnimation].counter = 0; - animation[currentAnimation].completed = false; + currentAnimation_ = newAnimation; + animations_[currentAnimation_].currentFrame = 0; + animations_[currentAnimation_].counter = 0; + animations_[currentAnimation_].completed = false; } } @@ -511,13 +517,13 @@ void AnimatedSprite::update() // Establece el rectangulo para un frame de una animación void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h) { - animation[index_animation].frames.push_back({x, y, w, h}); + animations_[index_animation].frames.push_back({x, y, w, h}); } // OLD - Establece el contador para todas las animaciones void AnimatedSprite::setAnimationCounter(int value) { - for (auto &a : animation) + for (auto &a : animations_) { a.counter = value; } @@ -526,7 +532,7 @@ void AnimatedSprite::setAnimationCounter(int value) // Reinicia la animación void AnimatedSprite::resetAnimation() { - animation[currentAnimation].currentFrame = 0; - animation[currentAnimation].counter = 0; - animation[currentAnimation].completed = false; + animations_[currentAnimation_].currentFrame = 0; + animations_[currentAnimation_].counter = 0; + animations_[currentAnimation_].completed = false; } \ No newline at end of file diff --git a/source/animated_sprite.h b/source/animated_sprite.h index f98b7bd..aef5b50 100644 --- a/source/animated_sprite.h +++ b/source/animated_sprite.h @@ -1,13 +1,14 @@ #pragma once -#include // for SDL_Rect -#include // for Uint8 -#include // for string, basic_string -#include // for vector -#include "moving_sprite.h" // for MovingSprite -class Texture; +#include // for SDL_Rect +#include // for Uint8 +#include // for string, basic_string +#include // for vector +#include "moving_sprite.h" // for MovingSprite +#include "texture.h" +#include -struct animation_t +struct Animation { std::string name; // Nombre de la animacion std::vector frames; // Cada uno de los frames que componen la animación @@ -20,23 +21,23 @@ struct animation_t struct animatedSprite_t { - std::vector animations; // Vector con las diferentes animaciones - Texture *texture; // Textura con los graficos para el sprite + std::vector animations; // Vector con las diferentes animaciones + std::shared_ptr texture; // Textura con los graficos para el sprite }; // Carga la animación desde un fichero -animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose = false); +animatedSprite_t loadAnimationFromFile(std::shared_ptr texture, std::string filePath); class AnimatedSprite : public MovingSprite { private: // Variables - std::vector animation; // Vector con las diferentes animaciones - int currentAnimation; // Animacion activa + std::vector animations_; // Vector con las diferentes animaciones + int currentAnimation_; // Animacion activa public: // Constructor - AnimatedSprite(Texture *texture = nullptr, std::string file = "", std::vector *buffer = nullptr); + AnimatedSprite(std::shared_ptr texture = nullptr, std::string file = "", std::vector *buffer = nullptr); AnimatedSprite(animatedSprite_t *animation); // Destructor diff --git a/source/background.cpp b/source/background.cpp index 063453d..769a64f 100644 --- a/source/background.cpp +++ b/source/background.cpp @@ -4,21 +4,18 @@ #include // for max, min #include // for basic_string #include "asset.h" // for Asset -#include "moving_sprite.h" // for MovingSprite #include "param.h" // for param -#include "sprite.h" // for Sprite -#include "texture.h" // for Texture // Constructor Background::Background(SDL_Renderer *renderer) : renderer(renderer) { // Carga las texturas - buildingsTexture = new Texture(renderer, Asset::get()->get("game_buildings.png")); - topCloudsTexture = new Texture(renderer, Asset::get()->get("game_clouds1.png")); - bottomCloudsTexture = new Texture(renderer, Asset::get()->get("game_clouds2.png")); - grassTexture = new Texture(renderer, Asset::get()->get("game_grass.png")); - gradientsTexture = new Texture(renderer, Asset::get()->get("game_sky_colors.png")); + buildingsTexture = std::make_shared(renderer, Asset::get()->get("game_buildings.png")); + topCloudsTexture = std::make_shared(renderer, Asset::get()->get("game_clouds1.png")); + bottomCloudsTexture = std::make_shared(renderer, Asset::get()->get("game_clouds2.png")); + grassTexture = std::make_shared(renderer, Asset::get()->get("game_grass.png")); + gradientsTexture = std::make_shared(renderer, Asset::get()->get("game_sky_colors.png")); // Inicializa variables gradientNumber = 0; @@ -53,15 +50,15 @@ Background::Background(SDL_Renderer *renderer) const int bottomClouds_y = base - 101; const float topCloudsSpeed = 0.1f; const float bottomCloudsSpeed = 0.05f; - topCloudsSprite_A = new MovingSprite(0, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); - topCloudsSprite_B = new MovingSprite(rect.w, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); + topCloudsSprite_A = std::make_unique(0, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); + topCloudsSprite_B = std::make_unique(rect.w, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); - bottomCloudsSprite_A = new MovingSprite(0, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); - bottomCloudsSprite_B = new MovingSprite(rect.w, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); + bottomCloudsSprite_A = std::make_unique(0, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); + bottomCloudsSprite_B = std::make_unique(rect.w, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); - buildingsSprite = new Sprite(0, 0, buildingsTexture->getWidth(), buildingsTexture->getHeight(), buildingsTexture); - gradientSprite = new Sprite(0, 0, rect.w, rect.h, gradientsTexture); - grassSprite = new Sprite(0, 0, grassTexture->getWidth(), grassTexture->getHeight() / 2, grassTexture); + buildingsSprite = std::make_unique(0, 0, buildingsTexture->getWidth(), buildingsTexture->getHeight(), buildingsTexture); + gradientSprite = std::make_unique(0, 0, rect.w, rect.h, gradientsTexture); + grassSprite = std::make_unique(0, 0, grassTexture->getWidth(), grassTexture->getHeight() / 2, grassTexture); // Inicializa objetos topCloudsSprite_A->setSpriteClip(0, 0, topCloudsTexture->getWidth(), topCloudsTexture->getHeight()); @@ -85,19 +82,6 @@ Background::Background(SDL_Renderer *renderer) // Destructor Background::~Background() { - delete buildingsTexture; - delete topCloudsTexture; - delete bottomCloudsTexture; - delete grassTexture; - delete gradientsTexture; - - delete topCloudsSprite_A; - delete topCloudsSprite_B; - delete bottomCloudsSprite_A; - delete bottomCloudsSprite_B; - delete buildingsSprite; - delete gradientSprite; - delete grassSprite; SDL_DestroyTexture(canvas); SDL_DestroyTexture(colorTexture); } diff --git a/source/background.h b/source/background.h index ff6df73..4b09e65 100644 --- a/source/background.h +++ b/source/background.h @@ -3,10 +3,10 @@ #include // for SDL_Rect #include // for SDL_Renderer, SDL_Texture #include "utils.h" // for color_t -class Asset; -class MovingSprite; -class Sprite; -class Texture; +#include "moving_sprite.h" +#include "sprite.h" +#include "texture.h" +#include /* Esta clase es la encargada de dibujar el fondo que aparece durante la sección @@ -52,20 +52,20 @@ private: // Objetos y punteros SDL_Renderer *renderer; // El renderizador de la ventana - Texture *buildingsTexture; // Textura con los edificios de fondo - Texture *topCloudsTexture; // Textura con las nubes de fondo - Texture *bottomCloudsTexture; // Textura con las nubes de fondo - Texture *grassTexture; // Textura con la hierba del suelo - Texture *gradientsTexture; // Textura con los diferentes colores de fondo del juego + std::shared_ptr buildingsTexture; // Textura con los edificios de fondo + std::shared_ptr topCloudsTexture; // Textura con las nubes de fondo + std::shared_ptr bottomCloudsTexture; // Textura con las nubes de fondo + std::shared_ptr grassTexture; // Textura con la hierba del suelo + std::shared_ptr gradientsTexture; // Textura con los diferentes colores de fondo del juego - MovingSprite *topCloudsSprite_A; // Sprite para las nubes superiores - MovingSprite *topCloudsSprite_B; // Sprite para las nubes superiores - MovingSprite *bottomCloudsSprite_A; // Sprite para las nubes inferiores - MovingSprite *bottomCloudsSprite_B; // Sprite para las nubes inferiores + std::unique_ptr topCloudsSprite_A; // Sprite para las nubes superiores + std::unique_ptr topCloudsSprite_B; // Sprite para las nubes superiores + std::unique_ptr bottomCloudsSprite_A; // Sprite para las nubes inferiores + std::unique_ptr bottomCloudsSprite_B; // Sprite para las nubes inferiores - Sprite *buildingsSprite; // Sprite con los edificios de fondo - Sprite *gradientSprite; // Sprite con los graficos del degradado de color de fondo - Sprite *grassSprite; // Sprite para la hierba + std::unique_ptr buildingsSprite; // Sprite con los edificios de fondo + std::unique_ptr gradientSprite; // Sprite con los graficos del degradado de color de fondo + std::unique_ptr grassSprite; // Sprite para la hierba SDL_Texture *canvas; // Textura para componer el fondo SDL_Texture *colorTexture; // Textura para atenuar el fondo diff --git a/source/balloon.cpp b/source/balloon.cpp index 312f12e..0aebf3e 100644 --- a/source/balloon.cpp +++ b/source/balloon.cpp @@ -7,7 +7,7 @@ #include "texture.h" // for Texture // Constructor -Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector *animation) +Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, std::shared_ptr texture, std::vector *animation) : kind(kind), speed(speed) { sprite = std::make_unique(texture, "", animation); diff --git a/source/balloon.h b/source/balloon.h index 67d64c0..315e8ca 100644 --- a/source/balloon.h +++ b/source/balloon.h @@ -6,7 +6,7 @@ #include #include "utils.h" // for circle_t #include "animated_sprite.h" -class Texture; +#include "texture.h" // Cantidad de elementos del vector con los valores de la deformación del globo al rebotar constexpr int MAX_BOUNCE = 10; @@ -141,7 +141,7 @@ private: public: // Constructor - Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector *animation); + Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, std::shared_ptr texture, std::vector *animation); // Destructor ~Balloon() = default; diff --git a/source/bullet.cpp b/source/bullet.cpp index 0c3d5c4..5f745d4 100644 --- a/source/bullet.cpp +++ b/source/bullet.cpp @@ -11,7 +11,7 @@ constexpr int BULLET_VELX_LEFT = -2; constexpr int BULLET_VELX_RIGHT = 2; // Constructor -Bullet::Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, Texture *texture) +Bullet::Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr texture) : posX(x), posY(y), width(BULLET_WIDTH), height(BULLET_HEIGHT), velX(0), velY(BULLET_VELY), kind(kind), owner(owner), playArea(playArea) { diff --git a/source/bullet.h b/source/bullet.h index 7698524..2f5d555 100644 --- a/source/bullet.h +++ b/source/bullet.h @@ -5,7 +5,7 @@ #include // for unique_ptr #include "sprite.h" // for Sprite #include "utils.h" // for circle_t -class Texture; // lines 9-9 +#include "texture.h" // lines 9-9 // Enumeración para los diferentes tipos de balas enum class BulletType @@ -42,7 +42,7 @@ private: void shiftColliders(); // Alinea el círculo de colisión con el objeto public: - Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, Texture *texture); + Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr texture); ~Bullet() = default; void render(); // Pinta el objeto en pantalla diff --git a/source/explosions.cpp b/source/explosions.cpp index a66ad9d..de91d7e 100644 --- a/source/explosions.cpp +++ b/source/explosions.cpp @@ -18,7 +18,7 @@ Explosions::~Explosions() // Actualiza la lógica de la clase void Explosions::update() { - for (auto explosion : explosions) + for (auto &explosion : explosions) { explosion->update(); } @@ -30,18 +30,18 @@ void Explosions::update() // Dibuja el objeto en pantalla void Explosions::render() { - for (auto explosion : explosions) + for (auto &explosion : explosions) { explosion->render(); } } // Añade texturas al objeto -void Explosions::addTexture(int size, Texture *texture, std::vector *animation) +void Explosions::addTexture(int size, std::shared_ptr texture, std::vector *animation) { explosion_texture_t temp; temp.size = size; - temp.texture = texture; + temp.texture = texture.get(); temp.animation = animation; textures.push_back(temp); } @@ -50,9 +50,9 @@ void Explosions::addTexture(int size, Texture *texture, std::vector void Explosions::add(int x, int y, int size) { const int index = getIndexBySize(size); - AnimatedSprite *sprite = new AnimatedSprite(textures[index].texture, "", textures[index].animation); + auto sprite = std::make_unique(textures[index].texture, "", textures[index].animation); sprite->setPos(x, y); - explosions.push_back(sprite); + explosions.push_back(std::move(sprite)); } // Vacia el vector de elementos finalizados @@ -64,7 +64,6 @@ void Explosions::freeExplosions() { if (explosions[i]->animationIsCompleted()) { - delete explosions[i]; explosions.erase(explosions.begin() + i); } } diff --git a/source/explosions.h b/source/explosions.h index 46fc8cb..3df5121 100644 --- a/source/explosions.h +++ b/source/explosions.h @@ -2,8 +2,9 @@ #include // for string #include // for vector -class AnimatedSprite; -class Texture; +#include "animated_sprite.h" +#include +#include "texture.h" struct explosion_texture_t { @@ -18,7 +19,7 @@ class Explosions private: // Variables std::vector textures; // Vector con las texturas a utilizar - std::vector explosions; // Lista con todas las explosiones + std::vector> explosions; // Lista con todas las explosiones // Vacia el vector de elementos finalizados void freeExplosions(); @@ -40,7 +41,7 @@ public: void render(); // Añade texturas al objeto - void addTexture(int size, Texture *texture, std::vector *animation); + void addTexture(int size, std::shared_ptr texture, std::vector *animation); // Añade una explosión void add(int x, int y, int size); diff --git a/source/game.cpp b/source/game.cpp index 3f0a8a8..0a3c879 100644 --- a/source/game.cpp +++ b/source/game.cpp @@ -30,6 +30,7 @@ #include "smart_sprite.h" // for SmartSprite #include "text.h" // for Text, TXT_CENTER #include "texture.h" // for Texture +#include "dbgtxt.h" struct JA_Music_t; struct JA_Sound_t; @@ -37,9 +38,9 @@ struct JA_Sound_t; // Constructor Game::Game(int playerID, int currentStage, bool demo, JA_Music_t *music) + : music(music) { // Copia los punteros - this->music = music; asset = Asset::get(); input = Input::get(); screen = Screen::get(); @@ -75,9 +76,9 @@ Game::Game(int playerID, int currentStage, bool demo, JA_Music_t *music) background->setPos(param.game.playArea.rect); - n1000Sprite = std::make_unique(gameTextTexture.get()); - n2500Sprite = std::make_unique(gameTextTexture.get()); - n5000Sprite = std::make_unique(gameTextTexture.get()); + n1000Sprite = std::make_shared(gameTextTexture); + n2500Sprite = std::make_shared(gameTextTexture); + n5000Sprite = std::make_shared(gameTextTexture); explosions->addTexture(1, explosionsTextures[0], explosionsAnimations[0]); explosions->addTexture(2, explosionsTextures[1], explosionsAnimations[1]); @@ -118,32 +119,25 @@ void Game::init(int playerID) ticksSpeed = 15; // Elimina qualquier jugador que hubiese antes de crear los nuevos - for (auto player : players) - { - if (player) - { - delete player; - } - }; players.clear(); // Crea los dos jugadores - Player *player1 = new Player(1, (param.game.playArea.firstQuarterX * ((0 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, ¶m.game.playArea.rect, playerTextures[0], playerAnimations); + auto player1 = std::make_unique(1, (param.game.playArea.firstQuarterX * ((0 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, ¶m.game.playArea.rect, playerTextures[0], playerAnimations); player1->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL); player1->setName(lang::getText(53)); - const int controller1 = getController(player1->getId()); + const auto controller1 = getController(player1->getId()); player1->setController(controller1); - players.push_back(player1); + players.push_back(std::move(player1)); - Player *player2 = new Player(2, (param.game.playArea.firstQuarterX * ((1 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, ¶m.game.playArea.rect, playerTextures[1], playerAnimations); + auto player2 = std::make_unique(2, (param.game.playArea.firstQuarterX * ((1 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, ¶m.game.playArea.rect, playerTextures[1], playerAnimations); player2->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL); player2->setName(lang::getText(54)); - const int controller2 = getController(player2->getId()); + const auto controller2 = getController(player2->getId()); player2->setController(controller2); - players.push_back(player2); + players.push_back(std::move(player2)); - // Obtiene el "id" del jugador que va a jugar - Player *player = getPlayer(playerID); + // Obtiene mediante "playerID" el jugador que va a empezar jugar + auto player = getPlayer(playerID); // Cambia el estado del jugador seleccionado player->setStatusPlaying(PlayerStatus::PLAYING); @@ -187,7 +181,7 @@ void Game::init(int playerID) // Variables para el marcador scoreboard->setPos({param.scoreboard.x, param.scoreboard.y, param.scoreboard.w, param.scoreboard.h}); - for (auto player : players) + for (auto &player : players) { scoreboard->setName(player->getScoreBoardPanel(), player->getName()); if (player->isWaiting()) @@ -239,8 +233,8 @@ void Game::init(int playerID) if (demo.enabled) { // Selecciona una pantalla al azar - const int demos = 3; - const int demo = rand() % demos; + constexpr auto demos = 3; + const auto demo = rand() % demos; const int stages[demos] = {0, 3, 5}; currentStage = stages[demo]; @@ -253,12 +247,12 @@ void Game::init(int playerID) // Activa o no al otro jugador if (rand() % 2 == 0) { - const int otherPlayer = playerID == 1 ? 2 : 1; - Player *player = getPlayer(otherPlayer); + const auto otherPlayer = playerID == 1 ? 2 : 1; + auto player = getPlayer(otherPlayer); player->setStatusPlaying(PlayerStatus::PLAYING); } - for (auto player : players) + for (auto &player : players) { // Añade 0, 1 o 2 cafes al jugador for (int i = 0; i < rand() % 3; ++i) @@ -303,10 +297,10 @@ void Game::init(int playerID) evaluateAndSetMenace(); // Inicializa el bitmap de 1000 puntos - constexpr int height = 15; - constexpr int sprite1Width = 35; - constexpr int sprite2Width = 38; - constexpr int sprite3Width = 39; + constexpr auto height = 15; + constexpr auto sprite1Width = 35; + constexpr auto sprite2Width = 38; + constexpr auto sprite3Width = 39; n1000Sprite->setPosX(0); n1000Sprite->setPosY(0); n1000Sprite->setWidth(sprite1Width); @@ -317,7 +311,7 @@ void Game::init(int playerID) n1000Sprite->setAccelY(-0.1f); n1000Sprite->setSpriteClip(0, 0, sprite1Width, height); n1000Sprite->setEnabled(false); - n1000Sprite->setEnabledCounter(0); + n1000Sprite->setFinishedCounter(0); n1000Sprite->setDestX(0); n1000Sprite->setDestY(0); @@ -332,7 +326,7 @@ void Game::init(int playerID) n2500Sprite->setAccelY(-0.1f); n2500Sprite->setSpriteClip(sprite1Width, 0, sprite2Width, height); n2500Sprite->setEnabled(false); - n2500Sprite->setEnabledCounter(0); + n2500Sprite->setFinishedCounter(0); n2500Sprite->setDestX(0); n2500Sprite->setDestY(0); @@ -347,7 +341,7 @@ void Game::init(int playerID) n5000Sprite->setAccelY(-0.1f); n5000Sprite->setSpriteClip(sprite1Width + sprite2Width, 0, sprite3Width, height); n5000Sprite->setEnabled(false); - n5000Sprite->setEnabledCounter(0); + n5000Sprite->setFinishedCounter(0); n5000Sprite->setDestX(0); n5000Sprite->setDestY(0); } @@ -370,78 +364,78 @@ void Game::loadMedia() explosionsTextures.clear(); // Texturas - bulletTexture = std::make_unique(renderer, asset->get("bullet.png")); - gameTextTexture = std::make_unique(renderer, asset->get("game_text.png")); + bulletTexture = std::make_shared(renderer, asset->get("bullet.png")); + gameTextTexture = std::make_shared(renderer, asset->get("game_text.png")); // Texturas - Globos - Texture *balloon1Texture = new Texture(renderer, asset->get("balloon1.png")); + auto balloon1Texture = std::make_shared(renderer, asset->get("balloon1.png")); balloonTextures.push_back(balloon1Texture); - Texture *balloon2Texture = new Texture(renderer, asset->get("balloon2.png")); + auto balloon2Texture = std::make_shared(renderer, asset->get("balloon2.png")); balloonTextures.push_back(balloon2Texture); - Texture *balloon3Texture = new Texture(renderer, asset->get("balloon3.png")); + auto balloon3Texture = std::make_shared(renderer, asset->get("balloon3.png")); balloonTextures.push_back(balloon3Texture); - Texture *balloon4Texture = new Texture(renderer, asset->get("balloon4.png")); + auto balloon4Texture = std::make_shared(renderer, asset->get("balloon4.png")); balloonTextures.push_back(balloon4Texture); - Texture *balloon5Texture = new Texture(renderer, asset->get("powerball.png")); + auto balloon5Texture = std::make_shared(renderer, asset->get("powerball.png")); balloonTextures.push_back(balloon5Texture); // Texturas - Explosiones - Texture *explosion1Texture = new Texture(renderer, asset->get("explosion1.png")); + auto explosion1Texture = std::make_shared(renderer, asset->get("explosion1.png")); explosionsTextures.push_back(explosion1Texture); - Texture *explosion2Texture = new Texture(renderer, asset->get("explosion2.png")); + auto explosion2Texture = std::make_shared(renderer, asset->get("explosion2.png")); explosionsTextures.push_back(explosion2Texture); - Texture *explosion3Texture = new Texture(renderer, asset->get("explosion3.png")); + auto explosion3Texture = std::make_shared(renderer, asset->get("explosion3.png")); explosionsTextures.push_back(explosion3Texture); - Texture *explosion4Texture = new Texture(renderer, asset->get("explosion4.png")); + auto explosion4Texture = std::make_shared(renderer, asset->get("explosion4.png")); explosionsTextures.push_back(explosion4Texture); // Texturas - Items - Texture *item1 = new Texture(renderer, asset->get("item_points1_disk.png")); + auto item1 = std::make_shared(renderer, asset->get("item_points1_disk.png")); itemTextures.push_back(item1); - Texture *item2 = new Texture(renderer, asset->get("item_points2_gavina.png")); + auto item2 = std::make_shared(renderer, asset->get("item_points2_gavina.png")); itemTextures.push_back(item2); - Texture *item3 = new Texture(renderer, asset->get("item_points3_pacmar.png")); + auto item3 = std::make_shared(renderer, asset->get("item_points3_pacmar.png")); itemTextures.push_back(item3); - Texture *item4 = new Texture(renderer, asset->get("item_clock.png")); + auto item4 = std::make_shared(renderer, asset->get("item_clock.png")); itemTextures.push_back(item4); - Texture *item5 = new Texture(renderer, asset->get("item_coffee.png")); + auto item5 = std::make_shared(renderer, asset->get("item_coffee.png")); itemTextures.push_back(item5); - Texture *item6 = new Texture(renderer, asset->get("item_coffee_machine.png")); + auto item6 = std::make_shared(renderer, asset->get("item_coffee_machine.png")); itemTextures.push_back(item6); // Texturas - Player1 - Texture *player1 = new Texture(renderer, asset->get("player1.gif")); + auto player1 = std::make_shared(renderer, asset->get("player1.gif")); player1->addPalette(asset->get("player1_pal1.gif")); player1->addPalette(asset->get("player1_pal2.gif")); player1->addPalette(asset->get("player1_pal3.gif")); player1Textures.push_back(player1); - Texture *player1Power = new Texture(renderer, asset->get("player_power.gif")); + auto player1Power = std::make_shared(renderer, asset->get("player_power.gif")); player1Power->addPalette(asset->get("player_power_pal.gif")); player1Textures.push_back(player1Power); playerTextures.push_back(player1Textures); // Texturas - Player2 - Texture *player2 = new Texture(renderer, asset->get("player2.gif")); + auto player2 = std::make_shared(renderer, asset->get("player2.gif")); player2->addPalette(asset->get("player2_pal1.gif")); player2->addPalette(asset->get("player2_pal2.gif")); player2->addPalette(asset->get("player2_pal3.gif")); player2Textures.push_back(player2); - Texture *player2Power = new Texture(renderer, asset->get("player_power.gif")); + auto player2Power = std::make_shared(renderer, asset->get("player_power.gif")); player2Power->addPalette(asset->get("player_power_pal.gif")); player2Power->setPalette(1); player2Textures.push_back(player2Power); @@ -525,10 +519,10 @@ void Game::loadMedia() itemAnimations.push_back(item6Animation); // Texto - text = new Text(asset->get("smb2.gif"), asset->get("smb2.txt"), renderer); - textBig = new Text(asset->get("smb2_big.png"), asset->get("smb2_big.txt"), renderer); - textNokia2 = new Text(asset->get("nokia2.png"), asset->get("nokia2.txt"), renderer); - textNokiaBig2 = new Text(asset->get("nokia_big2.png"), asset->get("nokia_big2.txt"), renderer); + text = std::make_unique(asset->get("smb2.gif"), asset->get("smb2.txt"), renderer); + textBig = std::make_unique(asset->get("smb2_big.png"), asset->get("smb2_big.txt"), renderer); + textNokia2 = std::make_unique(asset->get("nokia2.png"), asset->get("nokia2.txt"), renderer); + textNokiaBig2 = std::make_unique(asset->get("nokia_big2.png"), asset->get("nokia_big2.txt"), renderer); // Sonidos balloonSound = JA_LoadSound(asset->get("balloon.wav").c_str()); @@ -557,94 +551,18 @@ void Game::loadMedia() void Game::unloadMedia() { // Texturas - for (auto texture : player1Textures) - { - if (texture) - { - delete texture; - } - } player1Textures.clear(); - - for (auto texture : player2Textures) - { - if (texture) - { - delete texture; - } - } player2Textures.clear(); - - for (auto texture : itemTextures) - { - if (texture) - { - delete texture; - } - } itemTextures.clear(); - - for (auto texture : balloonTextures) - { - if (texture) - { - delete texture; - } - } balloonTextures.clear(); - - for (auto texture : explosionsTextures) - { - if (texture) - { - delete texture; - } - } explosionsTextures.clear(); // Animaciones - for (auto animation : playerAnimations) - { - if (animation) - { - delete animation; - } - } playerAnimations.clear(); - - for (auto animation : balloonAnimations) - { - if (animation) - { - delete animation; - } - } balloonAnimations.clear(); - - for (auto animation : explosionsAnimations) - { - if (animation) - { - delete animation; - } - } explosionsAnimations.clear(); - - for (auto animation : itemAnimations) - { - if (animation) - { - delete animation; - } - } itemAnimations.clear(); - // Text - delete text; - delete textBig; - delete textNokia2; - delete textNokiaBig2; - // Sonidos JA_DeleteSound(balloonSound); JA_DeleteSound(bulletSound); @@ -667,11 +585,11 @@ void Game::unloadMedia() bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_DATA]) { // Indicador de éxito en la carga - bool success = true; + auto success = true; const std::string fileName = filePath.substr(filePath.find_last_of("\\/") + 1); - SDL_RWops *file = SDL_RWFromFile(filePath.c_str(), "r+b"); - if (file == nullptr) + auto file = SDL_RWFromFile(filePath.c_str(), "r+b"); + if (!file) { // El fichero no existe #ifdef VERBOSE std::cout << "Warning: Unable to open " << fileName.c_str() << " file" << std::endl; @@ -681,7 +599,7 @@ bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_ file = SDL_RWFromFile(filePath.c_str(), "w+b"); // Si ha creado el fichero - if (file != nullptr) + if (file) { #ifdef VERBOSE std::cout << "New file (" << fileName.c_str() << ") created!" << std::endl; @@ -739,11 +657,11 @@ bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_ // Guarda el fichero de datos para la demo bool Game::saveDemoFile(std::string filePath) { - bool success = true; + auto success = true; const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1); - SDL_RWops *file = SDL_RWFromFile(filePath.c_str(), "w+b"); - if (file != nullptr) + auto file = SDL_RWFromFile(filePath.c_str(), "w+b"); + if (file) { // Guardamos los datos for (int i = 0; i < TOTAL_DEMO_DATA; ++i) @@ -791,7 +709,7 @@ void Game::deployEnemyFormation() powerBallCounter > 0 ? powerBallCounter-- : powerBallCounter = 0; // Elige una formación enemiga la azar - int set = rand() % 10; + auto set = rand() % 10; // Evita repetir la ultima formación enemiga desplegada if (set == lastEnemyDeploy) @@ -802,7 +720,7 @@ void Game::deployEnemyFormation() lastEnemyDeploy = set; const stage_t stage = enemyFormations->getStage(currentStage); - const int numEnemies = stage.enemyPool->set[set]->numberOfEnemies; + const auto numEnemies = stage.enemyPool->set[set]->numberOfEnemies; for (int i = 0; i < numEnemies; ++i) { createBalloon(stage.enemyPool->set[set]->init[i].x, @@ -828,7 +746,7 @@ void Game::increaseStageCurrentPower(int power) void Game::updateHiScore() { // Si la puntuación actual es mayor que la máxima puntuación - for (auto player : players) + for (auto &player : players) { if (player->getScore() > hiScore.score) { @@ -848,7 +766,7 @@ void Game::updateHiScore() // Actualiza las variables del jugador void Game::updatePlayers() { - for (auto player : players) + for (auto &player : players) { player->update(); @@ -875,7 +793,7 @@ void Game::updatePlayers() // Dibuja a los jugadores void Game::renderPlayers() { - for (auto player : players) + for (auto &player : players) { if (!player->isWaiting()) { @@ -905,7 +823,7 @@ void Game::updateStage() destroyAllBalloons(); // Destruye a todos los enemigos currentPower = 0; // Vuelve a dejar el poder a cero, por lo que hubiera podido subir al destruir todos lo globos menaceCurrent = 255; // Sube el nivel de amenaza para que no cree mas globos - for (auto player : players) + for (auto &player : players) { // Añade un millon de puntos a los jugadores que queden vivos if (player->isPlaying()) { @@ -952,7 +870,7 @@ void Game::updateGameOver() if ((gameOverCounter == 250) || (gameOverCounter == 200) || (gameOverCounter == 180) || (gameOverCounter == 120) || (gameOverCounter == 60)) { // Hace sonar aleatoriamente uno de los 4 sonidos de burbujas - const int index = rand() % 4; + const auto index = rand() % 4; JA_Sound_t *sound[4] = {bubble1Sound, bubble2Sound, bubble3Sound, bubble4Sound}; JA_PlaySound(sound[index], 0); } @@ -982,40 +900,40 @@ void Game::updateBalloons() // Pinta en pantalla todos los globos activos void Game::renderBalloons() { - for (auto balloon : balloons) + for (auto &balloon : balloons) { balloon->render(); } } // Crea un globo nuevo en el vector de globos -int Game::createBalloon(float x, int y, int kind, float velx, float speed, int creationtimer) +std::shared_ptr Game::createBalloon(float x, int y, int kind, float velx, float speed, int creationtimer) { - const int index = (kind - 1) % 4; - Balloon *b = new Balloon(x, y, kind, velx, speed, creationtimer, balloonTextures[index], balloonAnimations[index]); + const auto index = (kind - 1) % 4; + auto b = std::make_shared(x, y, kind, velx, speed, creationtimer, balloonTextures[index], balloonAnimations[index]); balloons.push_back(b); - return (int)(balloons.size() - 1); + return b; } // Crea una PowerBall void Game::createPowerBall() { - const int values = 6; - const int posY = -BLOCK; + constexpr auto values = 6; + constexpr auto posY = -BLOCK; - const int left = param.game.playArea.rect.x; - const int center = param.game.playArea.centerX - (BALLOON_WIDTH_4 / 2); - const int right = param.game.playArea.rect.w - BALLOON_WIDTH_4; + const auto left = param.game.playArea.rect.x; + const auto center = param.game.playArea.centerX - (BALLOON_WIDTH_4 / 2); + const auto right = param.game.playArea.rect.w - BALLOON_WIDTH_4; - const float vpos = BALLOON_VELX_POSITIVE; - const float vneg = BALLOON_VELX_NEGATIVE; + const auto vpos = BALLOON_VELX_POSITIVE; + const auto vneg = BALLOON_VELX_NEGATIVE; - const int luck = rand() % values; + const auto luck = rand() % values; const int x[values] = {left, left, center, center, right, right}; const float vx[values] = {vpos, vpos, vpos, vneg, vneg, vneg}; - Balloon *b = new Balloon(x[luck], posY, POWER_BALL, vx[luck], enemySpeed, 300, balloonTextures[4], balloonAnimations[4]); - balloons.push_back(b); + auto b = std::make_unique(x[luck], posY, POWER_BALL, vx[luck], enemySpeed, 300, balloonTextures[4], balloonAnimations[4]); + balloons.push_back(std::move(b)); powerBallEnabled = true; powerBallCounter = POWERBALL_COUNTER; @@ -1024,7 +942,7 @@ void Game::createPowerBall() // Establece la velocidad de los globos void Game::setBalloonSpeed(float speed) { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled()) { @@ -1131,13 +1049,13 @@ void Game::updateBalloonSpeed() } // Explosiona un globo. Lo destruye y crea otros dos si es el caso -void Game::popBalloon(Balloon *balloon) +void Game::popBalloon(std::shared_ptr &balloon) { // Aumenta el poder de la fase increaseStageCurrentPower(1); balloonsPopped++; - const int kind = balloon->getKind(); + const auto kind = balloon->getKind(); if (kind == POWER_BALL) { destroyAllBalloons(); @@ -1146,7 +1064,7 @@ void Game::popBalloon(Balloon *balloon) } else { - const int size = balloon->getSize(); + const auto size = balloon->getSize(); if (size == BALLOON_SIZE_1) { // Si es del tipo más pequeño, simplemente elimina el globo explosions->add(balloon->getPosX(), balloon->getPosY(), size); @@ -1154,27 +1072,13 @@ void Game::popBalloon(Balloon *balloon) } else { // En cualquier otro caso, crea dos globos de un tipo inferior - const int index = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_NEGATIVE, enemySpeed, 0); - balloons[index]->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); - if (balloons[index]->getClass() == BALLOON_CLASS) - { - balloons[index]->setVelY(-2.50f); - } - else - { - balloons[index]->setVelY(BALLOON_VELX_NEGATIVE); - } + const auto bLeft = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_NEGATIVE, enemySpeed, 0); + bLeft->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); + bLeft->setVelY(bLeft->getClass() == BALLOON_CLASS ? -2.50f : BALLOON_VELX_NEGATIVE); - const int index2 = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_POSITIVE, enemySpeed, 0); - balloons[index2]->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); - if (balloons[index2]->getClass() == BALLOON_CLASS) - { - balloons[index2]->setVelY(-2.50f); - } - else - { - balloons[index2]->setVelY(BALLOON_VELX_NEGATIVE); - } + const auto bRight = createBalloon(0, balloon->getPosY(), balloon->getKind() - 1, BALLOON_VELX_POSITIVE, enemySpeed, 0); + bRight->allignTo(balloon->getPosX() + (balloon->getWidth() / 2)); + bRight->setVelY(bRight->getClass() == BALLOON_CLASS ? -2.50f : BALLOON_VELX_NEGATIVE); // Elimina el globo explosions->add(balloon->getPosX(), balloon->getPosY(), size); @@ -1187,44 +1091,54 @@ void Game::popBalloon(Balloon *balloon) } // Explosiona un globo. Lo destruye = no crea otros globos -void Game::destroyBalloon(Balloon *balloon) +void Game::destroyBalloon(std::shared_ptr &balloon) { - int score = 0; + auto score = 0; // Calcula la puntuación y el poder que generaria el globo en caso de romperlo a él y a sus hijos - const int size = balloon->getSize(); + const auto size = balloon->getSize(); switch (size) { case BALLOON_SIZE_4: + { score = BALLOON_SCORE_4 + (2 * BALLOON_SCORE_3) + (4 * BALLOON_SCORE_2) + (8 * BALLOON_SCORE_1); break; - - case BALLOON_SIZE_3: - score = BALLOON_SCORE_3 + (2 * BALLOON_SCORE_2) + (4 * BALLOON_SCORE_1); - break; - - case BALLOON_SIZE_2: - score = BALLOON_SCORE_2 + (2 * BALLOON_SCORE_1); - break; - - case BALLOON_SIZE_1: - score = BALLOON_SCORE_1; - break; - - default: - score = 0; - break; } - // Otorga los puntos correspondientes al globo - for (auto player : players) + case BALLOON_SIZE_3: { - player->addScore(Uint32(score * player->getScoreMultiplier() * difficultyScoreMultiplier)); + score = BALLOON_SCORE_3 + (2 * BALLOON_SCORE_2) + (4 * BALLOON_SCORE_1); + break; + } + + case BALLOON_SIZE_2: + { + score = BALLOON_SCORE_2 + (2 * BALLOON_SCORE_1); + break; + } + + case BALLOON_SIZE_1: + { + score = BALLOON_SCORE_1; + break; + } + + default: + { + score = 0; + break; + } + } + + // Otorga los puntos correspondientes al globo + for (auto &player : players) + { + player->addScore(score * player->getScoreMultiplier() * difficultyScoreMultiplier); } updateHiScore(); // Aumenta el poder de la fase - const int power = balloon->getPower(); + const auto power = balloon->getPower(); increaseStageCurrentPower(power); balloonsPopped += power; @@ -1239,7 +1153,7 @@ void Game::destroyBalloon(Balloon *balloon) // Explosiona todos los globos void Game::popAllBalloons() { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->canBePopped()) { @@ -1253,7 +1167,7 @@ void Game::popAllBalloons() // Destruye todos los globos void Game::destroyAllBalloons() { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->canBeDestroyed()) { @@ -1261,7 +1175,7 @@ void Game::destroyAllBalloons() } } - enemyDeployCounter = 255; + enemyDeployCounter = 300; JA_PlaySound(powerBallSound); screen->flash(flashColor, 5); screen->shake(); @@ -1270,7 +1184,7 @@ void Game::destroyAllBalloons() // Detiene todos los globos void Game::stopAllBalloons(int time) { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled()) { @@ -1283,7 +1197,7 @@ void Game::stopAllBalloons(int time) // Pone en marcha todos los globos void Game::startAllBalloons() { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if ((balloon->isEnabled()) && (!balloon->isBeingCreated())) { @@ -1296,9 +1210,9 @@ void Game::startAllBalloons() // Obtiene el número de globos activos int Game::countBalloons() { - int num = 0; + auto num = 0; - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled()) { @@ -1312,23 +1226,16 @@ int Game::countBalloons() // Vacia del vector de globos los globos que ya no sirven void Game::freeBalloons() { - if (balloons.empty() == false) - { - for (int i = balloons.size() - 1; i >= 0; --i) - { - if (balloons[i]->isEnabled() == false) - { - delete balloons[i]; - balloons.erase(balloons.begin() + i); - } - } - } + auto it = std::remove_if(balloons.begin(), balloons.end(), + [](const auto &balloon) + { return !balloon->isEnabled(); }); + balloons.erase(it, balloons.end()); } // Comprueba la colisión entre el jugador y los globos activos -bool Game::checkPlayerBalloonCollision(Player *player) +bool Game::checkPlayerBalloonCollision(std::shared_ptr &player) { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if ((balloon->isEnabled()) && !(balloon->isStopped()) && !(balloon->isInvulnerable())) { @@ -1343,14 +1250,14 @@ bool Game::checkPlayerBalloonCollision(Player *player) } // Comprueba la colisión entre el jugador y los items -void Game::checkPlayerItemCollision(Player *player) +void Game::checkPlayerItemCollision(std::shared_ptr &player) { if (!player->isPlaying()) { return; } - for (auto item : items) + for (auto &item : items) { if (item->isEnabled()) { @@ -1359,52 +1266,56 @@ void Game::checkPlayerItemCollision(Player *player) switch (item->getClass()) { case ITEM_POINTS_1_DISK: + { player->addScore(1000); - updateHiScore(); - createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n1000Sprite->getWidth() / 2), player->getPosY(), n1000Sprite.get()); - JA_PlaySound(itemPickUpSound); + createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n1000Sprite->getWidth() / 2), player->getPosY(), n1000Sprite); break; + } case ITEM_POINTS_2_GAVINA: + { player->addScore(2500); - updateHiScore(); - createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n2500Sprite->getWidth() / 2), player->getPosY(), n2500Sprite.get()); - JA_PlaySound(itemPickUpSound); + createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n2500Sprite->getWidth() / 2), player->getPosY(), n2500Sprite); break; + } case ITEM_POINTS_3_PACMAR: + { player->addScore(5000); - updateHiScore(); - createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite.get()); - JA_PlaySound(itemPickUpSound); + createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite); break; + } case ITEM_CLOCK: + { enableTimeStopItem(); - JA_PlaySound(itemPickUpSound); break; + } case ITEM_COFFEE: + { if (player->getCoffees() == 2) { player->addScore(5000); - updateHiScore(); - createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite.get()); + createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (n5000Sprite->getWidth() / 2), player->getPosY(), n5000Sprite); } player->giveExtraHit(); - JA_PlaySound(itemPickUpSound); break; + } case ITEM_COFFEE_MACHINE: + { player->setPowerUp(); - JA_PlaySound(itemPickUpSound); coffeeMachineEnabled = false; break; + } default: break; } + updateHiScore(); + JA_PlaySound(itemPickUpSound); item->disable(); } } @@ -1414,27 +1325,27 @@ void Game::checkPlayerItemCollision(Player *player) // Comprueba y procesa la colisión entre las balas y los globos void Game::checkBulletBalloonCollision() { - for (auto bullet : bullets) + for (auto &bullet : bullets) { - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled() && (!balloon->isInvulnerable()) && bullet->isEnabled()) { if (checkCollision(balloon->getCollider(), bullet->getCollider())) { // Otorga los puntos correspondientes al globo al jugador que disparó la bala - Player *player = getPlayer(bullet->getOwner()); + auto player = getPlayer(bullet->getOwner()); if (!player) { return; } player->incScoreMultiplier(); - player->addScore(Uint32(balloon->getScore() * player->getScoreMultiplier() * difficultyScoreMultiplier)); + player->addScore(balloon->getScore() * player->getScoreMultiplier() * difficultyScoreMultiplier); updateHiScore(); // Suelta el item si se da el caso - const int droppeditem = dropItem(); - if ((droppeditem != ITEM_NULL) && !(demo.recording)) + const auto droppeditem = dropItem(); + if (droppeditem != ITEM_NULL && !demo.recording) { if (droppeditem != ITEM_COFFEE_MACHINE) { @@ -1467,14 +1378,13 @@ void Game::checkBulletBalloonCollision() // Mueve las balas activas void Game::moveBullets() { - for (auto bullet : bullets) + for (auto &bullet : bullets) { if (bullet->isEnabled()) { if (bullet->move() == BulletMoveStatus::OUT) { - Player *player = getPlayer(bullet->getOwner()); - player->decScoreMultiplier(); + getPlayer(bullet->getOwner())->decScoreMultiplier(); } } } @@ -1483,7 +1393,7 @@ void Game::moveBullets() // Pinta las balas activas void Game::renderBullets() { - for (auto bullet : bullets) + for (auto &bullet : bullets) { if (bullet->isEnabled()) { @@ -1495,20 +1405,19 @@ void Game::renderBullets() // Crea un objeto bala void Game::createBullet(int x, int y, BulletType kind, bool poweredUp, int owner) { - Bullet *b = new Bullet(x, y, kind, poweredUp, owner, &(param.game.playArea.rect), bulletTexture.get()); - bullets.push_back(b); + auto b = std::make_unique(x, y, kind, poweredUp, owner, &(param.game.playArea.rect), bulletTexture); + bullets.push_back(std::move(b)); } // Vacia el vector de balas void Game::freeBullets() { - if (bullets.empty() == false) + if (!bullets.empty()) { for (int i = bullets.size() - 1; i >= 0; --i) { - if (bullets[i]->isEnabled() == false) + if (!bullets[i]->isEnabled()) { - delete bullets[i]; bullets.erase(bullets.begin() + i); } } @@ -1518,7 +1427,7 @@ void Game::freeBullets() // Actualiza los items void Game::updateItems() { - for (auto item : items) + for (auto &item : items) { if (item->isEnabled()) { @@ -1535,7 +1444,7 @@ void Game::updateItems() // Pinta los items activos void Game::renderItems() { - for (auto item : items) + for (auto &item : items) { item->render(); } @@ -1544,8 +1453,8 @@ void Game::renderItems() // Devuelve un item al azar y luego segun sus probabilidades int Game::dropItem() { - const int luckyNumber = rand() % 100; - const int item = rand() % 6; + const auto luckyNumber = rand() % 100; + const auto item = rand() % 6; switch (item) { @@ -1596,7 +1505,7 @@ int Game::dropItem() if (luckyNumber < helper.itemCoffeeMachineOdds) { helper.itemCoffeeMachineOdds = ITEM_COFFEE_MACHINE_ODDS; - if ((!coffeeMachineEnabled) && (helper.needCoffeeMachine)) + if (!coffeeMachineEnabled && helper.needCoffeeMachine) { return ITEM_COFFEE_MACHINE; } @@ -1620,20 +1529,19 @@ int Game::dropItem() // Crea un objeto item void Game::createItem(int kind, float x, float y) { - Item *item = new Item(kind, x, y, &(param.game.playArea.rect), itemTextures[kind - 1], itemAnimations[kind - 1]); - items.push_back(item); + auto item = std::make_unique(kind, x, y, &(param.game.playArea.rect), itemTextures[kind - 1], itemAnimations[kind - 1]); + items.push_back(std::move(item)); } // Vacia el vector de items void Game::freeItems() { - if (items.empty() == false) + if (!items.empty()) { for (int i = items.size() - 1; i >= 0; --i) { - if (items[i]->isEnabled() == false) + if (!items[i]->isEnabled()) { - delete items[i]; items.erase(items.begin() + i); } } @@ -1641,9 +1549,9 @@ void Game::freeItems() } // Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto -void Game::createItemScoreSprite(int x, int y, SmartSprite *sprite) +void Game::createItemScoreSprite(int x, int y, std::shared_ptr sprite) { - SmartSprite *ss = new SmartSprite(nullptr); + auto ss = new SmartSprite(nullptr); smartSprites.push_back(ss); // Crea una copia del objeto @@ -1653,19 +1561,18 @@ void Game::createItemScoreSprite(int x, int y, SmartSprite *sprite) ss->setDestX(x); ss->setDestY(y - 25); ss->setEnabled(true); - ss->setEnabledCounter(100); + ss->setFinishedCounter(100); } // Vacia el vector de smartsprites void Game::freeSmartSprites() { - if (smartSprites.empty() == false) + if (!smartSprites.empty()) { for (int i = smartSprites.size() - 1; i >= 0; --i) { if (smartSprites[i]->hasFinished()) { - delete smartSprites[i]; smartSprites.erase(smartSprites.begin() + i); } } @@ -1675,7 +1582,7 @@ void Game::freeSmartSprites() // Crea un SmartSprite para arrojar el item café al recibir un impacto void Game::throwCoffee(int x, int y) { - SmartSprite *ss = new SmartSprite(itemTextures[4]); + auto ss = new SmartSprite(itemTextures[4]); smartSprites.push_back(ss); ss->setPosX(x - 8); @@ -1689,7 +1596,7 @@ void Game::throwCoffee(int x, int y) ss->setDestX(x + (ss->getVelX() * 50)); ss->setDestY(param.game.height + 1); ss->setEnabled(true); - ss->setEnabledCounter(1); + ss->setFinishedCounter(1); ss->setSpriteClip(0, param.game.itemSize, param.game.itemSize, param.game.itemSize); ss->setRotate(true); ss->setRotateSpeed(10); @@ -1715,7 +1622,7 @@ void Game::renderSmartSprites() } // Acciones a realizar cuando el jugador muere -void Game::killPlayer(Player *player) +void Game::killPlayer(std::shared_ptr &player) { if (!player->isPlaying() || player->isInvulnerable()) { // Si no está jugando o tiene inmunidad, no hace nada @@ -1752,7 +1659,7 @@ void Game::killPlayer(Player *player) void Game::evaluateAndSetMenace() { menaceCurrent = 0; - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled()) { @@ -1762,7 +1669,7 @@ void Game::evaluateAndSetMenace() } // Obtiene el valor de la variable -int Game::getMenace() +int Game::getMenace() const { return menaceCurrent; } @@ -1774,7 +1681,7 @@ void Game::setTimeStopped(bool value) } // Obtiene el valor de la variable -bool Game::isTimeStopped() +bool Game::isTimeStopped() const { return timeStopped; } @@ -1933,7 +1840,7 @@ void Game::update() // Vacia los vectores freeBullets(); - //freeBalloons(); + freeBalloons(); freeItems(); freeSmartSprites(); } @@ -1955,19 +1862,12 @@ void Game::updateBackground() // Si el juego está completado, se reduce la velocidad de las nubes if (gameCompleted) { - if (balloonsPopped > 400) - { - balloonsPopped -= 25; - } - else - { - balloonsPopped = 200; - } + balloonsPopped = (balloonsPopped > 400) ? (balloonsPopped - 25) : 200; } // Calcula la velocidad en función de los globos explotados y el total de globos a explotar para acabar el juego - const float cloudsInitialSpeed = 0.05f; - const float cloudsFinalSpeed = 2.00f - cloudsInitialSpeed; + constexpr auto cloudsInitialSpeed = 0.05f; + constexpr auto cloudsFinalSpeed = 2.00f - cloudsInitialSpeed; const float cloudsSpeed = (-cloudsInitialSpeed) + (-cloudsFinalSpeed * ((float)balloonsPopped / (float)totalPowerToCompleteGame)); background->setCloudsSpeed(cloudsSpeed); @@ -1985,7 +1885,7 @@ void Game::updateBackground() void Game::fillCanvas() { // Dibujamos el contenido de la zona de juego en su textura - SDL_Texture *temp = SDL_GetRenderTarget(renderer); + auto temp = SDL_GetRenderTarget(renderer); SDL_SetRenderTarget(renderer, canvas); // Dibuja los objetos @@ -2029,7 +1929,7 @@ void Game::updateMenace() return; } - const stage_t stage = enemyFormations->getStage(currentStage); + const auto stage = enemyFormations->getStage(currentStage); const float percent = currentPower / stage.powerToComplete; const int difference = stage.maxMenace - stage.minMenace; @@ -2064,8 +1964,8 @@ void Game::checkInput() // Modo Demo activo if (demo.enabled) { - int i = 0; - for (auto player : players) + auto i = 0; + for (auto &player : players) { if (player->isPlaying()) { @@ -2139,10 +2039,10 @@ void Game::checkInput() demo.keys.fireLeft = 0; demo.keys.fireRight = 0; #endif - for (auto player : players) + for (auto &player : players) { - const int controllerIndex = player->getController(); - const bool autofire = player->isPowerUp() || options.game.autofire; + const auto controllerIndex = player->getController(); + const auto autofire = player->isPowerUp() || options.game.autofire; if (player->isPlaying()) { // Input a la izquierda @@ -2241,9 +2141,9 @@ void Game::checkInput() } // Si está continuando, los botones de fuego hacen decrementar el contador - const bool fire1 = input->checkInput(input_fire_left, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); - const bool fire2 = input->checkInput(input_fire_center, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); - const bool fire3 = input->checkInput(input_fire_right, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire1 = input->checkInput(input_fire_left, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire2 = input->checkInput(input_fire_center, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire3 = input->checkInput(input_fire_right, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); if (fire1 || fire2 || fire3) { player->decContinueCounter(); @@ -2251,9 +2151,9 @@ void Game::checkInput() } else if (player->isEnteringName()) { - const bool fire1 = input->checkInput(input_fire_left, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); - const bool fire2 = input->checkInput(input_fire_center, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); - const bool fire3 = input->checkInput(input_fire_right, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire1 = input->checkInput(input_fire_left, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire2 = input->checkInput(input_fire_center, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); + const auto fire3 = input->checkInput(input_fire_right, INPUT_DO_NOT_ALLOW_REPEAT, options.controller[controllerIndex].deviceType, options.controller[controllerIndex].index); if (fire1 || fire2 || fire3) { if (player->getRecordNamePos() == 7) @@ -2304,7 +2204,7 @@ void Game::checkInput() void Game::renderMessages() { // GetReady - if ((counter < STAGE_COUNTER) && (!demo.enabled)) + if (counter < STAGE_COUNTER && !demo.enabled) { textNokiaBig2->write((int)getReadyBitmapPath[counter], param.game.playArea.centerY - 8, lang::getText(75), -2); } @@ -2312,7 +2212,7 @@ void Game::renderMessages() // Time Stopped if (timeStopped) { - if ((timeStoppedCounter > 100) || (timeStoppedCounter % 10 > 4)) + if (timeStoppedCounter > 100 || timeStoppedCounter % 10 > 4) { textNokia2->writeDX(TXT_CENTER, param.game.playArea.centerX, param.game.playArea.firstQuarterY, lang::getText(36) + std::to_string(timeStoppedCounter / 10), -1, noColor, 1, shdwTxtColor); } @@ -2321,7 +2221,6 @@ void Game::renderMessages() { if (timeStoppedCounter % 30 == 0) { - // JA_PlaySound(clockSound, false); JA_PlaySound(clockSound); } } @@ -2329,7 +2228,6 @@ void Game::renderMessages() { if (timeStoppedCounter % 15 == 0) { - // JA_PlaySound(clockSound, false); JA_PlaySound(clockSound); } } @@ -2338,8 +2236,8 @@ void Game::renderMessages() // STAGE NUMBER if (stageBitmapCounter < STAGE_COUNTER) { - const int stageNum = enemyFormations->getStage(currentStage).number; - std::string text; + const auto stageNum = enemyFormations->getStage(currentStage).number; + std::string text = ""; if (stageNum == 10) { // Ultima fase @@ -2391,7 +2289,7 @@ void Game::disableTimeStopItem() void Game::checkMusicStatus() { // Si la música no está sonando - if ((JA_GetMusicState() == JA_MUSIC_INVALID) || (JA_GetMusicState() == JA_MUSIC_STOPPED)) + if (JA_GetMusicState() == JA_MUSIC_INVALID || JA_GetMusicState() == JA_MUSIC_STOPPED) { // Si se ha completado el juego o los jugadores han terminado, detiene la música gameCompleted || allPlayersAreGameOver() ? JA_StopMusic() : JA_PlayMusic(music); @@ -2412,14 +2310,7 @@ void Game::run() } // Vuelve a dejar el sonido como estaba - if (demo.enabled) - { - JA_EnableSound(options.audio.sound.enabled); - } - else - { - JA_StopMusic(); - } + (demo.enabled) ? JA_EnableSound(options.audio.sound.enabled) : JA_StopMusic(); } // Indica si se puede crear una powerball @@ -2436,9 +2327,9 @@ bool Game::canPowerBallBeCreated() // Calcula el poder actual de los globos en pantalla int Game::calculateScreenPower() { - int power = 0; + auto power = 0; - for (auto balloon : balloons) + for (auto &balloon : balloons) { if (balloon->isEnabled()) { @@ -2460,10 +2351,10 @@ void Game::initPaths() } // Letrero de STAGE # - const int firstPart = STAGE_COUNTER / 4; // 50 - const int secondPart = firstPart * 3; // 150 - const int centerPoint = param.game.playArea.centerY - (BLOCK * 2); - const int distance = (param.game.playArea.rect.h) - (param.game.playArea.centerY - 16); + constexpr auto firstPart = STAGE_COUNTER / 4; // 50 + constexpr auto secondPart = firstPart * 3; // 150 + const auto centerPoint = param.game.playArea.centerY - (BLOCK * 2); + const auto distance = (param.game.playArea.rect.h) - (param.game.playArea.centerY - 16); for (int i = 0; i < STAGE_COUNTER; ++i) { @@ -2484,7 +2375,7 @@ void Game::initPaths() } // Letrero de GetReady - const int size = textNokiaBig2->lenght(lang::getText(75), -2); + const auto size = textNokiaBig2->lenght(lang::getText(75), -2); const float start1 = param.game.playArea.rect.x - size; const float finish1 = param.game.playArea.centerX - (size / 2); @@ -2528,7 +2419,6 @@ void Game::updateGameCompleted() if (gameCompletedCounter == GAME_COMPLETED_END) { - // section::options = SUBSECTION_GAME_GAMEOVER; section::name = section::NAME_TITLE; section::options = section::OPTIONS_TITLE_1; } @@ -2540,39 +2430,23 @@ void Game::updateHelper() // Solo ofrece ayuda cuando la amenaza es elevada if (menaceCurrent > 15) { - for (auto player : players) + for (auto &player : players) { - if (player->getCoffees() == 0) - { - helper.needCoffee = true; - } - else - { - helper.needCoffee = false; - } - - if (!player->isPowerUp()) - { - helper.needCoffeeMachine = true; - } - else - { - helper.needCoffeeMachine = false; - } + helper.needCoffee = (player->getCoffees() == 0); + helper.needCoffeeMachine = (!player->isPowerUp()); } } else { - helper.needCoffee = false; - helper.needCoffeeMachine = false; + helper.needCoffee = helper.needCoffeeMachine = false; } } // Comprueba si todos los jugadores han terminado de jugar bool Game::allPlayersAreWaitingOrGameOver() { - bool success = true; - for (auto player : players) + auto success = true; + for (auto &player : players) { success &= player->isWaiting() || player->isGameOver(); } @@ -2583,8 +2457,8 @@ bool Game::allPlayersAreWaitingOrGameOver() // Comprueba si todos los jugadores han terminado de jugar bool Game::allPlayersAreGameOver() { - bool success = true; - for (auto player : players) + auto success = true; + for (auto &player : players) { success &= player->isGameOver(); } @@ -2595,8 +2469,8 @@ bool Game::allPlayersAreGameOver() // Comprueba si todos los jugadores han terminado de jugar bool Game::allPlayersAreNotPlaying() { - bool success = true; - for (auto player : players) + auto success = true; + for (auto &player : players) { success &= !player->isPlaying(); } @@ -2607,33 +2481,40 @@ bool Game::allPlayersAreNotPlaying() // Comprueba los eventos que hay en cola void Game::checkEvents() { - while (SDL_PollEvent(eventHandler.get()) != 0) + SDL_Event event; + while (SDL_PollEvent(&event)) { // Evento de salida de la aplicación - if (eventHandler->type == SDL_QUIT) + if (event.type == SDL_QUIT) { section::name = section::NAME_QUIT; break; } - else if (eventHandler->type == SDL_WINDOWEVENT) + else if (event.type == SDL_WINDOWEVENT) { - switch (eventHandler->window.event) + switch (event.window.event) { case SDL_WINDOWEVENT_FOCUS_LOST: + { if (!demo.enabled) { pause(true); } break; + } case SDL_WINDOWEVENT_FOCUS_GAINED: + { pause(false); break; + } case SDL_WINDOWEVENT_SIZE_CHANGED: + { reloadTextures(); break; + } default: break; @@ -2641,9 +2522,9 @@ void Game::checkEvents() } #ifdef DEBUG - else if (eventHandler->type == SDL_KEYDOWN) + else if (event.type == SDL_KEYDOWN) { - switch (eventHandler->key.keysym.sym) + switch (event.key.keysym.sym) { // Crea una powerball case SDLK_1: @@ -2655,9 +2536,9 @@ void Game::checkEvents() // Crea dos BALLON4 case SDLK_2: { - const int set = 0; - const stage_t stage = enemyFormations->getStage(0); - const int numEnemies = stage.enemyPool->set[set]->numberOfEnemies; + const auto set = 0; + const auto stage = enemyFormations->getStage(0); + const auto numEnemies = stage.enemyPool->set[set]->numberOfEnemies; for (int i = 0; i < numEnemies; ++i) { createBalloon(stage.enemyPool->set[set]->init[i].x, @@ -2723,34 +2604,10 @@ void Game::loadAnimations(std::string filePath, std::vector *buffer // Elimina todos los objetos contenidos en vectores void Game::deleteAllVectorObjects() { - for (auto player : players) - { - delete player; - }; players.clear(); - - for (auto ballon : balloons) - { - delete ballon; - }; balloons.clear(); - - for (auto bullet : bullets) - { - delete bullet; - }; bullets.clear(); - - for (auto item : items) - { - delete item; - }; items.clear(); - - for (auto smartSprite : smartSprites) - { - delete smartSprite; - }; smartSprites.clear(); } @@ -2785,7 +2642,7 @@ void Game::reloadTextures() // Actualiza el marcador void Game::updateScoreboard() { - for (auto player : players) + for (auto &player : players) { scoreboard->setScore(player->getScoreBoardPanel(), player->getScore()); scoreboard->setMult(player->getScoreBoardPanel(), player->getScoreMultiplier()); @@ -2840,7 +2697,7 @@ void Game::checkPlayersStatusPlaying() if (allPlayersAreWaitingOrGameOver()) { // Entonces los pone en estado de Game Over - for (auto player : players) + for (auto &player : players) { player->setStatusPlaying(PlayerStatus::GAME_OVER); } @@ -2852,9 +2709,9 @@ void Game::checkPlayersStatusPlaying() } // Obtiene un jugador a partir de su "id" -Player *Game::getPlayer(int id) +std::shared_ptr Game::getPlayer(int id) { - for (auto player : players) + for (auto &player : players) { if (player->getId() == id) { @@ -2877,18 +2734,4 @@ int Game::getController(int playerId) } return -1; -} - -// Termina -void Game::quit(section::options_e code) -{ - if (screen->notificationsAreActive()) - { - section::name = section::NAME_QUIT; - section::options = code; - } - else - { - screen->showNotification(lang::getText(94)); - } } \ No newline at end of file diff --git a/source/game.h b/source/game.h index ca2afc6..4a6989b 100644 --- a/source/game.h +++ b/source/game.h @@ -8,21 +8,21 @@ #include "section.h" // for options_e #include "utils.h" // for demoKeys_t, color_t, hiScoreEntry_t #include -class Asset; // lines 11-11 -class Background; // lines 12-12 -class Balloon; // lines 13-13 -class Bullet; // lines 14-14 -class EnemyFormations; // lines 15-15 -class Explosions; // lines 16-16 -class Fade; // lines 17-17 -class Input; // lines 18-18 -class Item; // lines 19-19 -class Player; // lines 20-20 -class Scoreboard; // lines 21-21 -class Screen; // lines 22-22 -class SmartSprite; // lines 23-23 -class Text; // lines 24-24 -class Texture; // lines 25-25 +#include "asset.h" // lines 11-11 +#include "background.h" // lines 12-12 +#include "balloon.h" // lines 13-13 +#include "bullet.h" // lines 14-14 +#include "enemy_formations.h" // lines 15-15 +#include "explosions.h" // lines 16-16 +#include "fade.h" // lines 17-17 +#include "input.h" // lines 18-18 +#include "item.h" // lines 19-19 +#include "player.h" // lines 20-20 +#include "scoreboard.h" // lines 21-21 +#include "screen.h" // lines 22-22 +#include "smart_sprite.h" // lines 23-23 +#include "text.h" // lines 24-24 +#include "texture.h" // lines 24-24 enum class BulletType; struct JA_Music_t; // lines 26-26 struct JA_Sound_t; // lines 27-27 @@ -118,38 +118,38 @@ private: SDL_Texture *canvas; // Textura para dibujar la zona de juego - std::vector players; // Vector con los jugadores - std::vector balloons; // Vector con los globos - std::vector bullets; // Vector con las balas - std::vector items; // Vector con los items - std::vector smartSprites; // Vector con los smartsprites + std::vector> players; // Vector con los jugadores + std::vector> balloons; // Vector con los globos + std::vector> bullets; // Vector con las balas + std::vector> items; // Vector con los items + std::vector smartSprites; // Vector con los smartsprites - std::unique_ptr bulletTexture; // Textura para las balas - std::vector itemTextures; // Vector con las texturas de los items - std::vector balloonTextures; // Vector con las texturas de los globos - std::vector explosionsTextures; // Vector con las texturas de las explosiones - std::vector player1Textures; // Vector con las texturas del jugador - std::vector player2Textures; // Vector con las texturas del jugador - std::vector> playerTextures; // Vector con todas las texturas de los jugadores; + std::shared_ptr bulletTexture; // Textura para las balas + std::vector> itemTextures; // Vector con las texturas de los items + std::vector> balloonTextures; // Vector con las texturas de los globos + std::vector> explosionsTextures; // Vector con las texturas de las explosiones + std::vector> player1Textures; // Vector con las texturas del jugador + std::vector> player2Textures; // Vector con las texturas del jugador + std::vector>> playerTextures; // Vector con todas las texturas de los jugadores; - std::unique_ptr gameTextTexture; // Textura para los sprites con textos + std::shared_ptr gameTextTexture; // Textura para los sprites con textos std::vector *> itemAnimations; // Vector con las animaciones de los items std::vector *> playerAnimations; // Vector con las animaciones del jugador std::vector *> balloonAnimations; // Vector con las animaciones de los globos std::vector *> explosionsAnimations; // Vector con las animaciones de las explosiones - Text *text; // Fuente para los textos del juego - Text *textBig; // Fuente de texto grande - Text *textNokia2; // Otra fuente de texto para mensajes - Text *textNokiaBig2; // Y la versión en grande + std::unique_ptr text; // Fuente para los textos del juego + std::unique_ptr textBig; // Fuente de texto grande + std::unique_ptr textNokia2; // Otra fuente de texto para mensajes + std::unique_ptr textNokiaBig2; // Y la versión en grande std::unique_ptr fade; // Objeto para renderizar fades std::unique_ptr eventHandler; // Manejador de eventos - std::unique_ptr n1000Sprite; // Sprite con el texto 1.000 - std::unique_ptr n2500Sprite; // Sprite con el texto 2.500 - std::unique_ptr n5000Sprite; // Sprite con el texto 5.000 + std::shared_ptr n1000Sprite; // Sprite con el texto 1.000 + std::shared_ptr n2500Sprite; // Sprite con el texto 2.500 + std::shared_ptr n5000Sprite; // Sprite con el texto 5.000 JA_Sound_t *balloonSound; // Sonido para la explosión del globo JA_Sound_t *bulletSound; // Sonido para los disparos @@ -259,7 +259,7 @@ private: void renderBalloons(); // Crea un globo nuevo en el vector de globos - int createBalloon(float x, int y, int kind, float velx, float speed, int stoppedcounter); + std::shared_ptr createBalloon(float x, int y, int kind, float velx, float speed, int stoppedcounter); // Crea una PowerBall void createPowerBall(); @@ -277,10 +277,10 @@ private: void updateBalloonSpeed(); // Explosiona un globo. Lo destruye y crea otros dos si es el caso - void popBalloon(Balloon *balloon); + void popBalloon(std::shared_ptr &balloon); // Explosiona un globo. Lo destruye - void destroyBalloon(Balloon *balloon); + void destroyBalloon(std::shared_ptr &balloon); // Explosiona todos los globos void popAllBalloons(); @@ -301,10 +301,10 @@ private: void freeBalloons(); // Comprueba la colisión entre el jugador y los globos activos - bool checkPlayerBalloonCollision(Player *player); + bool checkPlayerBalloonCollision(std::shared_ptr &player); // Comprueba la colisión entre el jugador y los items - void checkPlayerItemCollision(Player *player); + void checkPlayerItemCollision(std::shared_ptr &player); // Comprueba la colisión entre las balas y los globos void checkBulletBalloonCollision(); @@ -337,7 +337,7 @@ private: void freeItems(); // Crea un objeto SmartSprite - void createItemScoreSprite(int x, int y, SmartSprite *sprite); + void createItemScoreSprite(int x, int y, std::shared_ptr sprite); // Vacia el vector de smartsprites void freeSmartSprites(); @@ -352,19 +352,19 @@ private: void renderSmartSprites(); // Acciones a realizar cuando el jugador muere - void killPlayer(Player *player); + void killPlayer(std::shared_ptr &player); // Calcula y establece el valor de amenaza en funcion de los globos activos void evaluateAndSetMenace(); // Obtiene el valor de la variable - int getMenace(); + int getMenace() const; // Establece el valor de la variable void setTimeStopped(bool value); // Obtiene el valor de la variable - bool isTimeStopped(); + bool isTimeStopped() const; // Establece el valor de la variable void setTimeStoppedCounter(int value); @@ -451,14 +451,11 @@ private: void checkPlayersStatusPlaying(); // Obtiene un jugador a partir de su "id" - Player *getPlayer(int id); + std::shared_ptr getPlayer(int id); // Obtiene un controlador a partir del "id" del jugador int getController(int playerId); - // Termina - void quit(section::options_e code); - public: // Constructor Game(int playerID, int currentStage, bool demo, JA_Music_t *music); diff --git a/source/game_logo.cpp b/source/game_logo.cpp index 8b9ab6f..061fb71 100644 --- a/source/game_logo.cpp +++ b/source/game_logo.cpp @@ -69,7 +69,7 @@ void GameLogo::init() coffeeSprite->setAccelY(0.1f); coffeeSprite->setSpriteClip(0, 0, coffeeTexture->getWidth(), coffeeTexture->getHeight()); coffeeSprite->setEnabled(true); - coffeeSprite->setEnabledCounter(0); + coffeeSprite->setFinishedCounter(0); coffeeSprite->setDestX(xp); coffeeSprite->setDestY(y - coffeeTexture->getHeight()); @@ -85,7 +85,7 @@ void GameLogo::init() crisisSprite->setAccelY(-0.1f); crisisSprite->setSpriteClip(0, 0, crisisTexture->getWidth(), crisisTexture->getHeight()); crisisSprite->setEnabled(true); - crisisSprite->setEnabledCounter(0); + crisisSprite->setFinishedCounter(0); crisisSprite->setDestX(xp + 15); crisisSprite->setDestY(y); diff --git a/source/intro.cpp b/source/intro.cpp index 967ed99..8c90708 100644 --- a/source/intro.cpp +++ b/source/intro.cpp @@ -23,12 +23,11 @@ Intro::Intro(JA_Music_t *music) : music(music) { // Copia los punteros - SDL_Renderer *renderer = Screen::get()->getRenderer(); + auto renderer = Screen::get()->getRenderer(); // Reserva memoria para los objetos - eventHandler = std::make_unique(); - texture = std::make_unique(renderer, Asset::get()->get("intro.png")); - text = std::make_unique(Asset::get()->get("nokia.png"), Asset::get()->get("nokia.txt"), renderer); + texture = std::make_shared(renderer, Asset::get()->get("intro.png")); + text = std::make_shared(Asset::get()->get("nokia.png"), Asset::get()->get("nokia.txt"), renderer); // Inicializa variables section::name = section::NAME_INTRO; @@ -41,10 +40,10 @@ Intro::Intro(JA_Music_t *music) constexpr int totalBitmaps = 6; for (int i = 0; i < totalBitmaps; ++i) { - auto ss = std::make_unique(texture.get()); + auto ss = std::make_unique(texture); ss->setWidth(128); ss->setHeight(96); - ss->setEnabledCounter(20); + ss->setFinishedCounter(20); ss->setDestX(param.game.gameArea.centerX - 64); ss->setDestY(param.game.gameArea.firstQuarterY - 24); bitmaps.push_back(std::move(ss)); @@ -73,7 +72,7 @@ Intro::Intro(JA_Music_t *music) bitmaps[2]->setAccelX(0.1f); bitmaps[2]->setAccelY(0.3f); bitmaps[2]->setSpriteClip(0, 96, 128, 96); - bitmaps[2]->setEnabledCounter(250); + bitmaps[2]->setFinishedCounter(250); bitmaps[3]->setPosX(param.game.gameArea.centerX - 64); bitmaps[3]->setPosY(param.game.height); @@ -103,12 +102,12 @@ Intro::Intro(JA_Music_t *music) constexpr int totalTexts = 9; for (int i = 0; i < totalTexts; ++i) { - auto w = std::make_unique(text.get()); + auto w = std::make_unique(text); w->setPosX(BLOCK * 0); w->setPosY(param.game.height - (BLOCK * 6)); w->setKerning(-1); w->setEnabled(false); - w->setEnabledCounter(180); + w->setFinishedCounter(180); texts.push_back(std::move(w)); } @@ -164,23 +163,30 @@ void Intro::reloadTextures() // Comprueba los eventos void Intro::checkEvents() { + SDL_Event event; + // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler.get()) != 0) + while (SDL_PollEvent(&event)) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_QUIT) + switch (event.type) + { + case SDL_QUIT: { section::name = section::NAME_QUIT; break; } - // Comprueba si se ha cambiado el tamaño de la ventana - else if (eventHandler->type == SDL_WINDOWEVENT) + case SDL_WINDOWEVENT: { - if (eventHandler->window.event == SDL_WINDOWEVENT_SIZE_CHANGED) + if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { reloadTextures(); } + break; + } + + default: + break; } } } diff --git a/source/intro.h b/source/intro.h index 760de64..dc21b25 100644 --- a/source/intro.h +++ b/source/intro.h @@ -20,9 +20,8 @@ class Intro { private: // Objetos - std::unique_ptr texture; // Textura con los graficos - std::unique_ptr eventHandler; // Manejador de eventos - std::unique_ptr text; // Textos de la intro + std::shared_ptr texture; // Textura con los graficos + std::shared_ptr text; // Textos de la intro std::vector> bitmaps; // Vector con los sprites inteligentes para los dibujos de la intro std::vector> texts; // Textos de la intro diff --git a/source/item.cpp b/source/item.cpp index ea5be7a..6b70e95 100644 --- a/source/item.cpp +++ b/source/item.cpp @@ -5,10 +5,10 @@ class Texture; // Constructor -Item::Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std::vector *animation) +Item::Item(int kind, float x, float y, SDL_Rect *playArea, std::shared_ptr texture, std::vector *animation) : kind(kind), playArea(playArea) { - sprite = new AnimatedSprite(texture, "", animation); + sprite = std::make_unique(texture, "", animation); enabled = true; timeToLive = 600; @@ -43,12 +43,6 @@ Item::Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std shiftColliders(); } -// Destructor -Item::~Item() -{ - delete sprite; -} - // Centra el objeto en la posición X void Item::allignTo(int x) { diff --git a/source/item.h b/source/item.h index 007f701..706812c 100644 --- a/source/item.h +++ b/source/item.h @@ -4,9 +4,10 @@ #include // for Uint16 #include // for string #include // for vector +#include #include "utils.h" // for circle_t -class AnimatedSprite; -class Texture; +#include "animated_sprite.h" +#include "texture.h" // Tipos de objetos #define ITEM_POINTS_1_DISK 1 @@ -22,7 +23,7 @@ class Item { private: // Objetos y punteros - AnimatedSprite *sprite; // Sprite con los graficos del objeto + std::unique_ptr sprite; // Sprite con los graficos del objeto // Variables float posX; // Posición X del objeto @@ -49,10 +50,10 @@ public: Uint16 timeToLive; // Temporizador con el tiempo que el objeto está presente // Constructor - Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std::vector *animation); + Item(int kind, float x, float y, SDL_Rect *playArea, std::shared_ptr texture, std::vector *animation); // Destructor - ~Item(); + ~Item() = default; // Centra el objeto en la posición X void allignTo(int x); diff --git a/source/moving_sprite.cpp b/source/moving_sprite.cpp index 43438e5..2eeb42e 100644 --- a/source/moving_sprite.cpp +++ b/source/moving_sprite.cpp @@ -2,294 +2,258 @@ #include "texture.h" // for Texture // Constructor -MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture) - : x(x), y(y) +MovingSprite::MovingSprite(float x, float y, int w, int h, float vx, float vy, float ax, float ay, std::shared_ptr texture) + : Sprite((int)x, (int)y, w, h, texture), x_(x), y_(y), vx_(vx), vy_(vy), ax_(ax), ay_(ay) { - // Copia los punteros - this->texture = texture; - - // Establece el alto y el ancho del sprite - this->w = w; - this->h = h; - - // Establece la posición X,Y del sprite - xPrev = x; - yPrev = y; - - // Establece la velocidad X,Y del sprite - vx = velx; - vy = vely; - - // Establece la aceleración X,Y del sprite - ax = accelx; - ay = accely; - // Establece el zoom W,H del sprite - zoomW = 1; - zoomH = 1; + zoomW_ = 1; + zoomH_ = 1; // Establece el angulo con el que se dibujará - angle = (double)0; + angle_ = (double)0; // Establece los valores de rotacion - rotateEnabled = false; - rotateSpeed = 0; - rotateAmount = (double)0; + rotateEnabled_ = false; + rotateSpeed_ = 0; + rotateAmount_ = (double)0; // Contador interno - counter = 0; + counter_ = 0; // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; + spriteClip_ = {0, 0, w_, h_}; // Establece el centro de rotación - center = nullptr; + center_ = nullptr; // Establece el tipo de volteado - currentFlip = SDL_FLIP_NONE; + currentFlip_ = SDL_FLIP_NONE; }; // Reinicia todas las variables void MovingSprite::clear() { - x = 0.0f; // Posición en el eje X - y = 0.0f; // Posición en el eje Y + x_ = 0.0f; // Posición en el eje X + y_ = 0.0f; // Posición en el eje Y - vx = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - vy = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - ax = 0.0f; // Aceleración en el eje X. Variación de la velocidad - ay = 0.0f; // Aceleración en el eje Y. Variación de la velocidad + ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad + ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad - zoomW = 1.0f; // Zoom aplicado a la anchura - zoomH = 1.0f; // Zoom aplicado a la altura + zoomW_ = 1.0f; // Zoom aplicado a la anchura + zoomH_ = 1.0f; // Zoom aplicado a la altura - angle = 0.0; // Angulo para dibujarlo - rotateEnabled = false; // Indica si ha de rotar - center = nullptr; // Centro de rotación - rotateSpeed = 0; // Velocidad de giro - rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración - counter = 0; // Contador interno + angle_ = 0.0; // Angulo para dibujarlo + rotateEnabled_ = false; // Indica si ha de rotar + center_ = nullptr; // Centro de rotación + rotateSpeed_ = 0; // Velocidad de giro + rotateAmount_ = 0.0; // Cantidad de grados a girar en cada iteración + counter_ = 0; // Contador interno - currentFlip = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite + currentFlip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite } // Mueve el sprite void MovingSprite::move() { - if (enabled) - { - xPrev = x; - yPrev = y; + x_ += vx_; + y_ += vy_; - x += vx; - y += vy; - - vx += ax; - vy += ay; - } + vx_ += ax_; + vy_ += ay_; } // Muestra el sprite por pantalla void MovingSprite::render() { - if (enabled) - { - texture->render((int)x, (int)y, &spriteClip, zoomW, zoomH, angle, center, currentFlip); - } + texture_->render((int)x_, (int)y_, &spriteClip_, zoomW_, zoomH_, angle_, center_, currentFlip_); } // Obtiene el valor de la variable -float MovingSprite::getPosX() +float MovingSprite::getPosX() const { - return x; + return x_; } // Obtiene el valor de la variable -float MovingSprite::getPosY() +float MovingSprite::getPosY() const { - return y; + return y_; } // Obtiene el valor de la variable -float MovingSprite::getVelX() +float MovingSprite::getVelX() const { - return vx; + return vx_; } // Obtiene el valor de la variable -float MovingSprite::getVelY() +float MovingSprite::getVelY() const { - return vy; + return vy_; } // Obtiene el valor de la variable -float MovingSprite::getAccelX() +float MovingSprite::getAccelX() const { - return ax; + return ax_; } // Obtiene el valor de la variable -float MovingSprite::getAccelY() +float MovingSprite::getAccelY() const { - return ay; + return ay_; } // Obtiene el valor de la variable -float MovingSprite::getZoomW() +float MovingSprite::getZoomW() const { - return zoomW; + return zoomW_; } // Obtiene el valor de la variable -float MovingSprite::getZoomH() +float MovingSprite::getZoomH() const { - return zoomH; + return zoomH_; } // Obtiene el valor de la variable -double MovingSprite::getAngle() +double MovingSprite::getAngle() const { - return angle; + return angle_; } -// Establece la posición y el tamaño del objeto +// Establece la posición y_ el tamaño del objeto void MovingSprite::setRect(SDL_Rect rect) { - x = (float)rect.x; - y = (float)rect.y; - w = rect.w; - h = rect.h; + x_ = (float)rect.x; + y_ = (float)rect.y; + w_ = rect.w; + h_ = rect.h; } // Establece el valor de las variables void MovingSprite::setPos(float x, float y) { - this->x = x; - this->y = y; + x_ = x; + y_ = y; } // Establece el valor de la variable void MovingSprite::setPosX(float value) { - x = value; + x_ = value; } // Establece el valor de la variable void MovingSprite::setPosY(float value) { - y = value; + y_ = value; } // Establece el valor de la variable void MovingSprite::setVelX(float value) { - vx = value; + vx_ = value; } // Establece el valor de la variable void MovingSprite::setVelY(float value) { - vy = value; + vy_ = value; } // Establece el valor de la variable void MovingSprite::setAccelX(float value) { - ax = value; + ax_ = value; } // Establece el valor de la variable void MovingSprite::setAccelY(float value) { - ay = value; + ay_ = value; } // Establece el valor de la variable void MovingSprite::setZoomW(float value) { - zoomW = value; + zoomW_ = value; } // Establece el valor de la variable void MovingSprite::setZoomH(float value) { - zoomH = value; + zoomH_ = value; } // Establece el valor de la variable void MovingSprite::setAngle(double value) { - angle = value; + angle_ = value; } // Incrementa el valor de la variable void MovingSprite::incAngle(double value) { - angle += value; + angle_ += value; } // Decrementa el valor de la variable void MovingSprite::decAngle(double value) { - angle -= value; + angle_ -= value; } // Obtiene el valor de la variable -bool MovingSprite::getRotate() +bool MovingSprite::getRotate() const { - return rotateEnabled; + return rotateEnabled_; } // Obtiene el valor de la variable -Uint16 MovingSprite::getRotateSpeed() +Uint16 MovingSprite::getRotateSpeed() const { - return rotateSpeed; + return rotateSpeed_; } // Establece la rotacion void MovingSprite::rotate() { - if (enabled) - if (rotateEnabled) + if (rotateEnabled_) + { + if (counter_ % rotateSpeed_ == 0) { - if (counter % rotateSpeed == 0) - { - incAngle(rotateAmount); - } + incAngle(rotateAmount_); } + } } // Establece el valor de la variable void MovingSprite::setRotate(bool value) { - rotateEnabled = value; + rotateEnabled_ = value; } // Establece el valor de la variable void MovingSprite::setRotateSpeed(int value) { - if (value < 1) - { - rotateSpeed = 1; - } - else - { - rotateSpeed = value; - } + rotateSpeed_ = (value < 1) ? 1 : value; } // Establece el valor de la variable void MovingSprite::setRotateAmount(double value) { - rotateAmount = value; + rotateAmount_ = value; } // Establece el valor de la variable void MovingSprite::disableRotate() { - rotateEnabled = false; - angle = (double)0; + rotateEnabled_ = false; + angle_ = (double)0; } // Actualiza las variables internas del objeto @@ -297,71 +261,35 @@ void MovingSprite::update() { move(); rotate(); - - if (enabled) - { - ++counter %= 60000; - } + ++counter_ %= 60000; } // Cambia el sentido de la rotación void MovingSprite::switchRotate() { - rotateAmount *= -1; + rotateAmount_ *= -1; } // Establece el valor de la variable void MovingSprite::setFlip(SDL_RendererFlip flip) { - currentFlip = flip; + currentFlip_ = flip; } // Gira el sprite horizontalmente void MovingSprite::flip() { - currentFlip = (currentFlip == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; + currentFlip_ = (currentFlip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL; } // Obtiene el valor de la variable SDL_RendererFlip MovingSprite::getFlip() { - return currentFlip; + return currentFlip_; } // Devuelve el rectangulo donde está el sprite SDL_Rect MovingSprite::getRect() { - const SDL_Rect rect = {(int)x, (int)y, w, h}; - return rect; -} - -// Deshace el último movimiento -void MovingSprite::undoMove() -{ - x = xPrev; - y = yPrev; -} - -// Deshace el último movimiento en el eje X -void MovingSprite::undoMoveX() -{ - x = xPrev; -} - -// Deshace el último movimiento en el eje Y -void MovingSprite::undoMoveY() -{ - y = yPrev; -} - -// Pone a cero las velocidades de desplacamiento -void MovingSprite::clearVel() -{ - vx = vy = 0.0f; -} - -// Devuelve el incremento en el eje X en pixels -int MovingSprite::getIncX() -{ - return (int)x - (int)xPrev; + return (SDL_Rect){(int)x_, (int)y_, w_, h_}; } \ No newline at end of file diff --git a/source/moving_sprite.h b/source/moving_sprite.h index 6b4560d..e4e5cfd 100644 --- a/source/moving_sprite.h +++ b/source/moving_sprite.h @@ -3,39 +3,37 @@ #include // for SDL_Rect, SDL_Point #include // for SDL_RendererFlip #include // for Uint16 +#include #include "sprite.h" // for Sprite -class Texture; +#include "texture.h" // Clase MovingSprite. Añade posicion y velocidad en punto flotante class MovingSprite : public Sprite { protected: - float x; // Posición en el eje X - float y; // Posición en el eje Y + float x_; // Posición en el eje X + float y_; // Posición en el eje Y - float xPrev; // Posición anterior en el eje X - float yPrev; // Posición anterior en el eje Y + float vx_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse + float vy_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse - float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse - float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse + float ax_; // Aceleración en el eje X. Variación de la velocidad + float ay_; // Aceleración en el eje Y. Variación de la velocidad - float ax; // Aceleración en el eje X. Variación de la velocidad - float ay; // Aceleración en el eje Y. Variación de la velocidad + float zoomW_; // Zoom aplicado a la anchura + float zoomH_; // Zoom aplicado a la altura - float zoomW; // Zoom aplicado a la anchura - float zoomH; // Zoom aplicado a la altura - - double angle; // Angulo para dibujarlo - bool rotateEnabled; // Indica si ha de rotar - int rotateSpeed; // Velocidad de giro - double rotateAmount; // Cantidad de grados a girar en cada iteración - int counter; // Contador interno - SDL_Point *center; // Centro de rotación - SDL_RendererFlip currentFlip; // Indica como se voltea el sprite + double angle_; // Angulo para dibujarlo + bool rotateEnabled_; // Indica si ha de rotar + int rotateSpeed_; // Velocidad de giro + double rotateAmount_; // Cantidad de grados a girar en cada iteración + int counter_; // Contador interno + SDL_Point *center_; // Centro de rotación + SDL_RendererFlip currentFlip_; // Indica como se voltea el sprite public: // Constructor - MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, Texture *texture = nullptr); + MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr texture = nullptr); // Mueve el sprite void move(); @@ -53,37 +51,25 @@ public: void render(); // Obten el valor de la variable - float getPosX(); + float getPosX() const; + float getPosY() const; // Obten el valor de la variable - float getPosY(); + float getVelX() const; + float getVelY() const; // Obten el valor de la variable - float getVelX(); + float getAccelX() const; + float getAccelY() const; // Obten el valor de la variable - float getVelY(); + float getZoomW() const; + float getZoomH() const; // Obten el valor de la variable - float getAccelX(); - - // Obten el valor de la variable - float getAccelY(); - - // Obten el valor de la variable - float getZoomW(); - - // Obten el valor de la variable - float getZoomH(); - - // Obten el valor de la variable - double getAngle(); - - // Obtiene el valor de la variable - bool getRotate(); - - // Obtiene el valor de la variable - Uint16 getRotateSpeed(); + double getAngle() const; + bool getRotate() const; + Uint16 getRotateSpeed() const; // Establece la posición y el tamaño del objeto void setRect(SDL_Rect rect); @@ -93,44 +79,28 @@ public: // Establece el valor de la variable void setPosX(float value); - - // Establece el valor de la variable void setPosY(float value); // Establece el valor de la variable void setVelX(float value); - - // Establece el valor de la variable void setVelY(float value); // Establece el valor de la variable void setAccelX(float value); - - // Establece el valor de la variable void setAccelY(float value); // Establece el valor de la variable void setZoomW(float value); - - // Establece el valor de la variable void setZoomH(float value); // Establece el valor de la variable void setAngle(double vaue); - - // Incrementa el valor de la variable void incAngle(double value); - - // Decrementa el valor de la variable void decAngle(double value); // Establece el valor de la variable void setRotate(bool value); - - // Establece el valor de la variable void setRotateSpeed(int value); - - // Establece el valor de la variable void setRotateAmount(double value); // Quita el efecto de rotación y deja el sprite en su angulo inicial. @@ -150,19 +120,4 @@ public: // Devuelve el rectangulo donde está el sprite SDL_Rect getRect(); - - // Deshace el último movimiento - void undoMove(); - - // Deshace el último movimiento en el eje X - void undoMoveX(); - - // Deshace el último movimiento en el eje Y - void undoMoveY(); - - // Pone a cero las velocidades de desplacamiento - void clearVel(); - - // Devuelve el incremento en el eje X en pixels - int getIncX(); }; \ No newline at end of file diff --git a/source/notify.cpp b/source/notify.cpp index 49e8acf..977d220 100644 --- a/source/notify.cpp +++ b/source/notify.cpp @@ -128,7 +128,7 @@ void Notify::update() } } - notifications[i].sprite->setRect(notifications[i].rect); + notifications[i].sprite->setPos(notifications[i].rect); } clearFinishedNotifications(); @@ -225,7 +225,7 @@ void Notify::showText(std::string text1, std::string text2, int icon) n.rect = {despH, yPos, width, height}; // Crea la textura - n.texture = new Texture(renderer); + n.texture = std::make_shared(renderer); n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET); n.texture->setBlendMode(SDL_BLENDMODE_BLEND); @@ -258,7 +258,7 @@ void Notify::showText(std::string text1, std::string text2, int icon) // Dibuja el icono de la notificación if (hasIcons && icon >= 0 && numTexts == 2) { - auto sp = std::make_unique((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture.get()); + auto sp = std::make_unique((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture); sp->setPos({paddingIn, paddingIn, iconSize, iconSize}); sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize}); sp->render(); @@ -280,7 +280,7 @@ void Notify::showText(std::string text1, std::string text2, int icon) SDL_SetRenderTarget(renderer, nullptr); // Crea el sprite de la notificación - n.sprite = new Sprite(n.rect, n.texture); + n.sprite = std::make_shared(n.rect, n.texture); // Deja la notificación invisible n.texture->setAlpha(0); diff --git a/source/notify.h b/source/notify.h index 6629ba5..cb0c5d2 100644 --- a/source/notify.h +++ b/source/notify.h @@ -42,8 +42,8 @@ private: struct Notification { - Texture *texture; - Sprite *sprite; + std::shared_ptr texture; + std::shared_ptr sprite; std::string text1; std::string text2; int counter; @@ -58,7 +58,7 @@ private: // Objetos y punteros SDL_Renderer *renderer; // El renderizador de la ventana - std::unique_ptr iconTexture; // Textura para los iconos de las notificaciones + std::shared_ptr iconTexture; // Textura para los iconos de las notificaciones std::unique_ptr text; // Objeto para dibujar texto // Variables diff --git a/source/player.cpp b/source/player.cpp index 193fab0..b8ad76f 100644 --- a/source/player.cpp +++ b/source/player.cpp @@ -11,7 +11,7 @@ #include "options.h" // Constructor -Player::Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector texture, std::vector *> animations) +Player::Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector> texture, std::vector *> animations) { // Reserva memoria para los objetos playerSprite = std::make_unique(texture[0], "", animations[0]); @@ -679,7 +679,7 @@ void Player::shiftColliders() } // Pone las texturas del jugador -void Player::setPlayerTextures(std::vector texture) +void Player::setPlayerTextures(std::vector> texture) { playerSprite->setTexture(texture[0]); powerSprite->setTexture(texture[1]); diff --git a/source/player.h b/source/player.h index 4878098..396b4d8 100644 --- a/source/player.h +++ b/source/player.h @@ -8,7 +8,7 @@ #include "animated_sprite.h" // for AnimatedSprite #include "enter_name.h" // for EnterName #include "utils.h" // for circle_t -class Texture; // lines 12-12 +#include "texture.h" // lines 12-12 enum class ScoreboardMode; // Estados del jugador @@ -103,7 +103,7 @@ private: public: // Constructor - Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector texture, std::vector *> animations); + Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector> texture, std::vector *> animations); // Destructor ~Player() = default; @@ -118,7 +118,7 @@ public: void render(); // Pone las texturas del jugador - void setPlayerTextures(std::vector texture); + void setPlayerTextures(std::vector> texture); // Actua en consecuencia de la entrada recibida void setInput(int input); diff --git a/source/scoreboard.cpp b/source/scoreboard.cpp index 2f52637..52db3d1 100644 --- a/source/scoreboard.cpp +++ b/source/scoreboard.cpp @@ -67,9 +67,9 @@ Scoreboard::Scoreboard(SDL_Renderer *renderer) recalculateAnchors(); // Crea objetos - gamePowerMeterTexture = std::unique_ptr(new Texture(renderer, Asset::get()->get("game_power_meter.png"))); - powerMeterSprite = std::unique_ptr(new Sprite(slot4_2.x - 20, slot4_2.y, 40, 7, gamePowerMeterTexture.get())); - textScoreBoard = std::unique_ptr(new Text(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer)); + gamePowerMeterTexture = std::make_shared(renderer, Asset::get()->get("game_power_meter.png")); + powerMeterSprite = std::make_unique(slot4_2.x - 20, slot4_2.y, 40, 7, gamePowerMeterTexture); + textScoreBoard = std::make_unique(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer); // Crea la textura de fondo background = nullptr; diff --git a/source/scoreboard.h b/source/scoreboard.h index ae9fe59..bae650f 100644 --- a/source/scoreboard.h +++ b/source/scoreboard.h @@ -7,9 +7,9 @@ #include // for string, basic_string #include // for vector #include "utils.h" // for color_t -class Sprite; // lines 11-11 -class Text; // lines 12-12 -class Texture; // lines 13-13 +#include "sprite.h" // lines 11-11 +#include "text.h" // lines 12-12 +#include "texture.h" // lines 13-13 // Defines constexpr int SCOREBOARD_LEFT_PANEL = 0; @@ -48,7 +48,7 @@ private: // Objetos y punteros SDL_Renderer *renderer; // El renderizador de la ventana - std::unique_ptr gamePowerMeterTexture; // Textura con el marcador de poder de la fase + std::shared_ptr gamePowerMeterTexture; // Textura con el marcador de poder de la fase std::unique_ptr powerMeterSprite; // Sprite para el medidor de poder de la fase std::unique_ptr textScoreBoard; // Fuente para el marcador del juego diff --git a/source/smart_sprite.cpp b/source/smart_sprite.cpp index 7858e38..168ae22 100644 --- a/source/smart_sprite.cpp +++ b/source/smart_sprite.cpp @@ -1,101 +1,68 @@ #include "smart_sprite.h" -#include "moving_sprite.h" // for MovingSprite +#include "moving_sprite.h" // for MovingSprite class Texture; // Constructor -SmartSprite::SmartSprite(Texture *texture) +SmartSprite::SmartSprite(std::shared_ptr texture) { // Copia punteros setTexture(texture); - // Inicializa el objeto init(); } // Inicializa el objeto void SmartSprite::init() { - enabled = false; - enabledCounter = 0; - onDestination = false; - destX = 0; - destY = 0; - counter = 0; - finished = false; + finishedCounter_ = 0; + onDestination_ = false; + destX_ = 0; + destY_ = 0; + finished_ = false; } // Actualiza la posición y comprueba si ha llegado a su destino void SmartSprite::update() { - if (enabled) - { - // Actualiza las variables internas del objeto - MovingSprite::update(); - - // Comprueba el movimiento - checkMove(); - - // Comprueba si ha terminado - checkFinished(); - } + MovingSprite::update(); + checkMove(); + checkFinished(); } // Pinta el objeto en pantalla void SmartSprite::render() { - if (enabled) - { - // Muestra el sprite por pantalla - MovingSprite::render(); - } -} - -// Obtiene el valor de la variable -bool SmartSprite::isEnabled() -{ - return enabled; + MovingSprite::render(); } // Establece el valor de la variable -void SmartSprite::setEnabled(bool enabled) +void SmartSprite::setFinishedCounter(int value) { - this->enabled = enabled; -} - -// Obtiene el valor de la variable -int SmartSprite::getEnabledCounter() -{ - return enabledCounter; -} - -// Establece el valor de la variable -void SmartSprite::setEnabledCounter(int value) -{ - enabledCounter = value; + finishedCounter_ = value; } // Establece el valor de la variable void SmartSprite::setDestX(int x) { - destX = x; + destX_ = x; } // Establece el valor de la variable void SmartSprite::setDestY(int y) { - destY = y; + destY_ = y; } // Obtiene el valor de la variable -int SmartSprite::getDestX() +int SmartSprite::getDestX() const { - return destX; + return destX_; } // Obtiene el valor de la variable -int SmartSprite::getDestY() +int SmartSprite::getDestY() const { - return destY; + return destY_; } // Comprueba el movimiento @@ -105,10 +72,10 @@ void SmartSprite::checkMove() if (getAccelX() > 0 || getVelX() > 0) { // Comprueba si ha llegado al destino - if (getPosX() > destX) + if (getPosX() > destX_) { // Lo coloca en posición - setPosX(destX); + setPosX(destX_); // Lo detiene setVelX(0.0f); @@ -119,10 +86,10 @@ void SmartSprite::checkMove() else if (getAccelX() < 0 || getVelX() < 0) { // Comprueba si ha llegado al destino - if (getPosX() < destX) + if (getPosX() < destX_) { // Lo coloca en posición - setPosX(destX); + setPosX(destX_); // Lo detiene setVelX(0.0f); @@ -134,10 +101,10 @@ void SmartSprite::checkMove() if (getAccelY() > 0 || getVelY() > 0) { // Comprueba si ha llegado al destino - if (getPosY() > destY) + if (getPosY() > destY_) { // Lo coloca en posición - setPosY(destY); + setPosY(destY_); // Lo detiene setVelY(0.0f); @@ -148,10 +115,10 @@ void SmartSprite::checkMove() else if (getAccelY() < 0 || getVelY() < 0) { // Comprueba si ha llegado al destino - if (getPosY() < destY) + if (getPosY() < destY_) { // Lo coloca en posición - setPosY(destY); + setPosY(destY_); // Lo detiene setVelY(0.0f); @@ -164,29 +131,29 @@ void SmartSprite::checkMove() void SmartSprite::checkFinished() { // Comprueba si ha llegado a su destino - onDestination = (getPosX() == destX && getPosY() == destY) ? true : false; + onDestination_ = (getPosX() == destX_ && getPosY() == destY_) ? true : false; - if (onDestination) - { // Si esta en el destino comprueba su contador - if (enabledCounter == 0) - { // Si ha llegado a cero, deshabilita el objeto y lo marca como finalizado - finished = true; + if (onDestination_) + { + if (finishedCounter_ == 0) + { + finished_ = true; } else - { // Si no ha llegado a cero, decrementa el contador - enabledCounter--; + { + --finishedCounter_; } } } // Obtiene el valor de la variable -bool SmartSprite::isOnDestination() +bool SmartSprite::isOnDestination() const { - return onDestination; + return onDestination_; } // Obtiene el valor de la variable -bool SmartSprite::hasFinished() +bool SmartSprite::hasFinished() const { - return finished; + return finished_; } \ No newline at end of file diff --git a/source/smart_sprite.h b/source/smart_sprite.h index 66f8b3c..a64ff52 100644 --- a/source/smart_sprite.h +++ b/source/smart_sprite.h @@ -1,19 +1,19 @@ #pragma once #include "animated_sprite.h" // for AnimatedSprite -class Texture; +#include "texture.h" +#include // Clase SmartSprite class SmartSprite : public AnimatedSprite { private: // Variables - bool enabled; // Indica si esta habilitado - bool onDestination; // Indica si está en el destino - int destX; // Posicion de destino en el eje X - int destY; // Posicion de destino en el eje Y - int enabledCounter; // Contador para deshabilitarlo - bool finished; // Indica si ya ha terminado + bool onDestination_; // Indica si está en el destino + int destX_; // Posicion de destino en el eje X + int destY_; // Posicion de destino en el eje Y + int finishedCounter_; // Contador para deshabilitarlo + bool finished_; // Indica si ya ha terminado // Comprueba el movimiento void checkMove(); @@ -23,7 +23,7 @@ private: public: // Constructor - SmartSprite(Texture *texture); + SmartSprite(std::shared_ptr texture); // Destructor ~SmartSprite() = default; @@ -37,17 +37,8 @@ public: // Pinta el objeto en pantalla void render(); - // Obtiene el valor de la variable - bool isEnabled(); - // Establece el valor de la variable - void setEnabled(bool enabled); - - // Obtiene el valor de la variable - int getEnabledCounter(); - - // Establece el valor de la variable - void setEnabledCounter(int value); + void setFinishedCounter(int value); // Establece el valor de la variable void setDestX(int x); @@ -56,14 +47,14 @@ public: void setDestY(int y); // Obtiene el valor de la variable - int getDestX(); + int getDestX() const; // Obtiene el valor de la variable - int getDestY(); + int getDestY() const; // Obtiene el valor de la variable - bool isOnDestination(); + bool isOnDestination() const; // Obtiene el valor de la variable - bool hasFinished(); + bool hasFinished() const; }; \ No newline at end of file diff --git a/source/sprite.cpp b/source/sprite.cpp index b17d700..3e7c6b8 100644 --- a/source/sprite.cpp +++ b/source/sprite.cpp @@ -1,165 +1,162 @@ #include "sprite.h" -#include "texture.h" // for Texture // Constructor -Sprite::Sprite(int x, int y, int w, int h, Texture *texture) - : x(x), y(y), w(w), h(h), texture(texture) +Sprite::Sprite(int x, int y, int w, int h, std::shared_ptr texture) + : x_(x), y_(y), w_(w), h_(h), texture_(texture) { // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; + spriteClip_ = {0, 0, w, h}; // Inicializa variables - enabled = true; + enabled_ = true; } -Sprite::Sprite(SDL_Rect rect, Texture *texture) - : x(rect.x), y(rect.y), w(rect.w), h(rect.h), texture(texture) +Sprite::Sprite(SDL_Rect rect, std::shared_ptr texture) + : x_(rect.x), y_(rect.y), w_(rect.w), h_(rect.h), texture_(texture) { // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; + spriteClip_ = {0, 0, w_, h_}; // Inicializa variables - enabled = true; + enabled_ = true; } // Muestra el sprite por pantalla void Sprite::render() { - if (enabled) + if (enabled_) { - texture->render(x, y, &spriteClip); + texture_->render(x_, y_, &spriteClip_); } } // Obten el valor de la variable int Sprite::getPosX() const { - return x; + return x_; } // Obten el valor de la variable int Sprite::getPosY() const { - return y; + return y_; } // Obten el valor de la variable int Sprite::getWidth() const { - return w; + return w_; } // Obten el valor de la variable int Sprite::getHeight() const { - return h; + return h_; +} + +// Establece la posición del objeto +void Sprite::setPos(int x, int y) +{ + x_ = x; + y_ = y; } // Establece la posición del objeto void Sprite::setPos(SDL_Point p) { - this->x = p.x; - this->y = p.y; + x_ = p.x; + y_ = p.y; } // Establece la posición del objeto void Sprite::setPos(SDL_Rect r) { - this->x = r.x; - this->y = r.y; - this->w = r.w; - this->h = r.h; + x_ = r.x; + y_ = r.y; + w_ = r.w; + h_ = r.h; } // Establece el valor de la variable void Sprite::setPosX(int x) { - this->x = x; + x_ = x; } // Establece el valor de la variable void Sprite::setPosY(int y) { - this->y = y; + y_ = y; } // Establece el valor de la variable void Sprite::setWidth(int w) { - this->w = w; + w_ = w; } // Establece el valor de la variable void Sprite::setHeight(int h) { - this->h = h; + h_ = h; } // Obten el valor de la variable SDL_Rect Sprite::getSpriteClip() const { - return spriteClip; + return spriteClip_; } // Establece el valor de la variable void Sprite::setSpriteClip(SDL_Rect rect) { - spriteClip = rect; + spriteClip_ = rect; } // Establece el valor de la variable void Sprite::setSpriteClip(int x, int y, int w, int h) { - spriteClip = {x, y, w, h}; + spriteClip_ = (SDL_Rect){x, y, w, h}; } // Obten el valor de la variable -Texture *Sprite::getTexture() +std::shared_ptr Sprite::getTexture() const { - return texture; + return texture_; } // Establece el valor de la variable -void Sprite::setTexture(Texture *texture) +void Sprite::setTexture(std::shared_ptr texture) { - this->texture = texture; + texture_ = texture; } // Establece el valor de la variable void Sprite::setEnabled(bool value) { - enabled = value; + enabled_ = value; } // Comprueba si el objeto está habilitado bool Sprite::isEnabled() const { - return enabled; + return enabled_; } // Devuelve el rectangulo donde está el sprite SDL_Rect Sprite::getRect() const { - return (SDL_Rect){x, y, w, h}; -} - -// Establece los valores de posición y tamaño del sprite -void Sprite::setRect(SDL_Rect rect) -{ - x = rect.x; - y = rect.y; - w = rect.w; - h = rect.h; + return (SDL_Rect){x_, y_, w_, h_}; } // Incrementa el valor de la variable void Sprite::incPosX(int value) { - x += value; + x_ += value; } // Incrementa el valor de la variable void Sprite::incPosY(int value) { - y += value; + y_ += value; } \ No newline at end of file diff --git a/source/sprite.h b/source/sprite.h index a36db38..336bd72 100644 --- a/source/sprite.h +++ b/source/sprite.h @@ -1,26 +1,27 @@ #pragma once -#include // for SDL_Rect, SDL_Point -class Texture; +#include // for SDL_Rect, SDL_Point +#include "texture.h" +#include // Clase sprite class Sprite { protected: - int x; // Posición en el eje X donde dibujar el sprite - int y; // Posición en el eje Y donde dibujar el sprite - int w; // Ancho del sprite - int h; // Alto del sprite + int x_; // Posición en el eje X donde dibujar el sprite + int y_; // Posición en el eje Y donde dibujar el sprite + int w_; // Ancho del sprite + int h_; // Alto del sprite - Texture *texture; // Textura donde estan todos los dibujos del sprite - SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla + std::shared_ptr texture_; // Textura donde estan todos los dibujos del sprite + SDL_Rect spriteClip_; // Rectangulo de origen de la textura que se dibujará en pantalla - bool enabled; // Indica si el sprite esta habilitado + bool enabled_; // Indica si el sprite esta habilitado public: // Constructor - Sprite(int x = 0, int y = 0, int w = 0, int h = 0, Texture *texture = nullptr); - Sprite(SDL_Rect rect, Texture *texture = nullptr); + Sprite(int x = 0, int y = 0, int w = 0, int h = 0, std::shared_ptr texture = nullptr); + Sprite(SDL_Rect rect, std::shared_ptr texture = nullptr); // Destructor ~Sprite() = default; @@ -30,52 +31,40 @@ public: // Obten el valor de la variable int getPosX() const; - - // Obten el valor de la variable int getPosY() const; - - // Obten el valor de la variable int getWidth() const; - - // Obten el valor de la variable int getHeight() const; // Establece la posición del objeto + void setPos(int x, int y); void setPos(SDL_Point p); void setPos(SDL_Rect r); - // Establece el valor de la variable - void setPosX(int x); + // Devuelve el rectangulo donde está el sprite + SDL_Rect getRect() const; // Establece el valor de la variable + void setPosX(int x); void setPosY(int y); + void setWidth(int w); + void setHeight(int h); // Incrementa el valor de la variable void incPosX(int value); - - // Incrementa el valor de la variable void incPosY(int value); - // Establece el valor de la variable - void setWidth(int w); - - // Establece el valor de la variable - void setHeight(int h); - // Obten el valor de la variable SDL_Rect getSpriteClip() const; // Establece el valor de la variable void setSpriteClip(SDL_Rect rect); - - // Establece el valor de la variable void setSpriteClip(int x, int y, int w, int h); // Obten el valor de la variable - Texture *getTexture(); + std::shared_ptr getTexture() const; // Establece el valor de la variable - void setTexture(Texture *texture); + void setTexture(std::shared_ptr texture); // Establece el valor de la variable void setEnabled(bool value); @@ -83,9 +72,4 @@ public: // Comprueba si el objeto está habilitado bool isEnabled() const; - // Devuelve el rectangulo donde está el sprite - SDL_Rect getRect() const; - - // Establece los valores de posición y tamaño del sprite - void setRect(SDL_Rect rect); }; \ No newline at end of file diff --git a/source/texture.cpp b/source/texture.cpp index f836268..bbb8a0a 100644 --- a/source/texture.cpp +++ b/source/texture.cpp @@ -12,36 +12,36 @@ // Constructor Texture::Texture(SDL_Renderer *renderer, std::string path) - : renderer(renderer), path(path) + : renderer_(renderer), path_(path) { // Inicializa - surface = nullptr; - texture = nullptr; - width = 0; - height = 0; - paletteIndex = 0; - palettes.clear(); + surface_ = nullptr; + texture_ = nullptr; + width_ = 0; + height_ = 0; + paletteIndex_ = 0; + palettes_.clear(); // Carga el fichero en la textura - if (path != "") + if (path_ != "") { // Obtiene la extensión - const std::string extension = path.substr(path.find_last_of(".") + 1); + const std::string extension = path_.substr(path_.find_last_of(".") + 1); // .png if (extension == "png") { - loadFromFile(path); + loadFromFile(path_); } // .gif else if (extension == "gif") { - surface = loadSurface(path.c_str()); - addPalette(path.c_str()); + surface_ = loadSurface(path_.c_str()); + addPalette(path_.c_str()); setPaletteColor(0, 0, 0x00000000); - createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); - SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND); + createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING); + SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND); flipSurface(); } } @@ -106,7 +106,7 @@ bool Texture::loadFromFile(std::string path) else { // Crea la textura desde los pixels de la surface - newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface); + newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface); if (newTexture == nullptr) { #ifdef VERBOSE @@ -116,8 +116,8 @@ bool Texture::loadFromFile(std::string path) else { // Obtiene las dimensiones de la imagen - this->width = loadedSurface->w; - this->height = loadedSurface->h; + width_ = loadedSurface->w; + height_ = loadedSurface->h; } // Elimina la textura cargada @@ -126,71 +126,73 @@ bool Texture::loadFromFile(std::string path) // Return success stbi_image_free(data); - texture = newTexture; - return texture != nullptr; + texture_ = newTexture; + return texture_ != nullptr; } // Crea una textura en blanco bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL_TextureAccess access) { // Crea una textura sin inicializar - texture = SDL_CreateTexture(renderer, format, access, width, height); - if (texture == nullptr) + texture_ = SDL_CreateTexture(renderer_, format, access, width, height); + if (!texture_) { + #ifdef VERBOSE std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; + #endif } else { - this->width = width; - this->height = height; + width_ = width; + height_ = height; } - return texture != nullptr; + return texture_ != nullptr; } // Libera la memoria de la textura void Texture::unload() { // Libera la textura - if (texture != nullptr) + if (texture_) { - SDL_DestroyTexture(texture); - texture = nullptr; - width = 0; - height = 0; + SDL_DestroyTexture(texture_); + texture_ = nullptr; + width_ = 0; + height_ = 0; } // Libera la surface - if (surface != nullptr) + if (surface_) { - deleteSurface(surface); - surface = nullptr; + deleteSurface(surface_); + surface_ = nullptr; } } // Establece el color para la modulacion void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue) { - SDL_SetTextureColorMod(texture, red, green, blue); + SDL_SetTextureColorMod(texture_, red, green, blue); } // Establece el blending void Texture::setBlendMode(SDL_BlendMode blending) { - SDL_SetTextureBlendMode(texture, blending); + SDL_SetTextureBlendMode(texture_, blending); } // Establece el alpha para la modulación void Texture::setAlpha(Uint8 alpha) { - SDL_SetTextureAlphaMod(texture, alpha); + SDL_SetTextureAlphaMod(texture_, alpha); } // Renderiza la textura en un punto específico void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip) { // Establece el destino de renderizado en la pantalla - SDL_Rect renderQuad = {x, y, width, height}; + SDL_Rect renderQuad = {x, y, width_, height_}; // Obtiene las dimesiones del clip de renderizado if (clip != nullptr) @@ -203,37 +205,37 @@ void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, dou renderQuad.h = renderQuad.h * zoomH; // Renderiza a pantalla - SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip); + SDL_RenderCopyEx(renderer_, texture_, clip, &renderQuad, angle, center, flip); } // Establece la textura como objetivo de renderizado void Texture::setAsRenderTarget(SDL_Renderer *renderer) { - SDL_SetRenderTarget(renderer, texture); + SDL_SetRenderTarget(renderer, texture_); } // Obtiene el ancho de la imagen int Texture::getWidth() { - return width; + return width_; } // Obtiene el alto de la imagen int Texture::getHeight() { - return height; + return height_; } // Recarga la textura bool Texture::reLoad() { - return loadFromFile(path); + return loadFromFile(path_); } // Obtiene la textura SDL_Texture *Texture::getSDLTexture() { - return texture; + return texture_; } // Crea una nueva surface @@ -291,8 +293,8 @@ Surface Texture::loadSurface(const char *filename) surface->data = pixels; free(buffer); - this->width = w; - this->height = h; + width_ = w; + height_ = h; return surface; } @@ -301,27 +303,27 @@ Surface Texture::loadSurface(const char *filename) void Texture::flipSurface() { // Limpia la textura - SDL_Texture *temp = SDL_GetRenderTarget(renderer); - SDL_SetRenderTarget(renderer, texture); - SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); - SDL_RenderClear(renderer); - SDL_SetRenderTarget(renderer, temp); + auto *temp = SDL_GetRenderTarget(renderer_); + SDL_SetRenderTarget(renderer_, texture_); + SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0); + SDL_RenderClear(renderer_); + SDL_SetRenderTarget(renderer_, temp); // Vuelca los datos Uint32 *pixels; int pitch; - SDL_LockTexture(texture, nullptr, (void **)&pixels, &pitch); - for (int i = 0; i < width * height; ++i) + SDL_LockTexture(texture_, nullptr, (void **)&pixels, &pitch); + for (int i = 0; i < width_ * height_; ++i) { - pixels[i] = palettes[paletteIndex][surface->data[i]]; + pixels[i] = palettes_[paletteIndex_][surface_->data[i]]; } - SDL_UnlockTexture(texture); + SDL_UnlockTexture(texture_); } // Establece un color de la paleta void Texture::setPaletteColor(int palette, int index, Uint32 color) { - palettes.at(palette)[index] = color; + palettes_.at(palette)[index] = color; } // Carga una paleta desde un fichero @@ -361,16 +363,16 @@ std::vector Texture::loadPal(const char *filename) // Añade una paleta a la lista void Texture::addPalette(std::string path) { - palettes.push_back(loadPal(path.c_str())); - setPaletteColor((int)palettes.size() - 1, 0, 0x00000000); + palettes_.push_back(loadPal(path.c_str())); + setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000); } // Cambia la paleta de la textura void Texture::setPalette(int palette) { - if (palette < (int)palettes.size()) + if (palette < (int)palettes_.size()) { - paletteIndex = palette; + paletteIndex_ = palette; flipSurface(); } } @@ -378,5 +380,5 @@ void Texture::setPalette(int palette) // Obtiene el renderizador SDL_Renderer *Texture::getRenderer() { - return renderer; + return renderer_; } \ No newline at end of file diff --git a/source/texture.h b/source/texture.h index a733207..48eff62 100644 --- a/source/texture.h +++ b/source/texture.h @@ -21,16 +21,16 @@ class Texture { private: // Objetos y punteros - SDL_Texture *texture; // La textura - SDL_Renderer *renderer; // Renderizador donde dibujar la textura - Surface surface; // Surface para usar imagenes en formato gif con paleta + SDL_Texture *texture_; // La textura + SDL_Renderer *renderer_; // Renderizador donde dibujar la textura + Surface surface_; // Surface para usar imagenes en formato gif con paleta // Variables - int width; // Ancho de la imagen - int height; // Alto de la imagen - std::string path; // Ruta de la imagen de la textura - std::vector> palettes; // Vector con las diferentes paletas - int paletteIndex; // Indice de la paleta en uso + int width_; // Ancho de la imagen + int height_; // Alto de la imagen + std::string path_; // Ruta de la imagen de la textura + std::vector> palettes_; // Vector con las diferentes paletas + int paletteIndex_; // Indice de la paleta en uso // Crea una nueva surface Surface newSurface(int w, int h); diff --git a/source/tiled_bg.cpp b/source/tiled_bg.cpp index 1c8a3de..b3991ef 100644 --- a/source/tiled_bg.cpp +++ b/source/tiled_bg.cpp @@ -58,16 +58,16 @@ void Tiledbg::init() void Tiledbg::fillTexture() { // Crea los objetos para pintar en la textura de fondo - Texture *bgTileTexture = new Texture(renderer, texturePath); - Sprite *tile = new Sprite({0, 0, tileWidth, tileHeight}, bgTileTexture); + auto bgTileTexture = std::make_shared(renderer, texturePath); + auto tile = std::make_unique((SDL_Rect){0, 0, tileWidth, tileHeight}, bgTileTexture); // Prepara para dibujar sobre la textura - SDL_Texture *temp = SDL_GetRenderTarget(renderer); + auto temp = SDL_GetRenderTarget(renderer); SDL_SetRenderTarget(renderer, canvas); // Rellena la textura con el tile - const int iMax = pos.w * 2 / tileWidth; - const int jMax = pos.h * 2 / tileHeight; + const auto iMax = pos.w * 2 / tileWidth; + const auto jMax = pos.h * 2 / tileHeight; tile->setSpriteClip(0, 0, tileWidth, tileHeight); for (int i = 0; i < iMax; ++i) { @@ -84,8 +84,6 @@ void Tiledbg::fillTexture() // Libera la memoria utilizada por los objetos bgTileTexture->unload(); - delete bgTileTexture; - delete tile; } // Pinta la clase en pantalla diff --git a/source/writer.cpp b/source/writer.cpp index eda8491..39b11f1 100644 --- a/source/writer.cpp +++ b/source/writer.cpp @@ -1,138 +1,131 @@ #include "writer.h" -#include "text.h" // for Text // Constructor -Writer::Writer(Text *text) - : text(text) +Writer::Writer(std::shared_ptr text) + : text_(text) { // Inicializa variables - posX = 0; - posY = 0; - kerning = 0; - caption = ""; - speed = 0; - writingCounter = 0; - index = 0; - lenght = 0; - completed = false; - enabled = false; - enabledCounter = 0; - finished = false; + posX_ = 0; + posY_ = 0; + kerning_ = 0; + caption_ = ""; + speed_ = 0; + writingCounter_ = 0; + index_ = 0; + lenght_ = 0; + completed_ = false; + enabled_ = false; + enabledCounter_ = 0; + finished_ = false; } // Actualiza el objeto void Writer::update() { - if (enabled) + if (enabled_) { - if (!completed) + if (!completed_) { // No completado - if (writingCounter > 0) + if (writingCounter_ > 0) { - writingCounter--; + writingCounter_--; } - else if (writingCounter == 0) + else if (writingCounter_ == 0) { - index++; - writingCounter = speed; + index_++; + writingCounter_ = speed_; } - if (index == lenght) + if (index_ == lenght_) { - completed = true; + completed_ = true; } } else { // Completado - if (enabledCounter > 0) + if (enabledCounter_ > 0) { - enabledCounter--; + enabledCounter_--; } - else if (enabledCounter == 0) + else if (enabledCounter_ == 0) { - finished = true; + finished_ = true; } } } } // Dibuja el objeto en pantalla -void Writer::render() +void Writer::render() const { - if (enabled) + if (enabled_) { - text->write(posX, posY, caption, kerning, index); + text_->write(posX_, posY_, caption_, kerning_, index_); } } // Establece el valor de la variable void Writer::setPosX(int value) { - posX = value; + posX_ = value; } // Establece el valor de la variable void Writer::setPosY(int value) { - posY = value; + posY_ = value; } // Establece el valor de la variable void Writer::setKerning(int value) { - kerning = value; + kerning_ = value; } // Establece el valor de la variable void Writer::setCaption(std::string text) { - caption = text; - lenght = text.length(); + caption_ = text; + lenght_ = text.length(); } // Establece el valor de la variable void Writer::setSpeed(int value) { - speed = value; - writingCounter = value; + speed_ = value; + writingCounter_ = value; } // Establece el valor de la variable void Writer::setEnabled(bool value) { - enabled = value; + enabled_ = value; } // Obtiene el valor de la variable bool Writer::IsEnabled() const { - return enabled; + return enabled_; } // Establece el valor de la variable -void Writer::setEnabledCounter(int time) +void Writer::setFinishedCounter(int time) { - enabledCounter = time; -} - -// Obtiene el valor de la variable -int Writer::getEnabledCounter() const -{ - return enabledCounter; + enabledCounter_ = time; } // Centra la cadena de texto a un punto X void Writer::center(int x) { - setPosX(x - (text->lenght(caption, kerning) / 2)); + setPosX(x - (text_->lenght(caption_, kerning_) / 2)); } // Obtiene el valor de la variable bool Writer::hasFinished() const { - return finished; + return finished_; } \ No newline at end of file diff --git a/source/writer.h b/source/writer.h index c8bee28..7b08dfb 100644 --- a/source/writer.h +++ b/source/writer.h @@ -1,32 +1,33 @@ #pragma once -#include // for string, basic_string -class Text; +#include // for string, basic_string +#include +#include "text.h" // Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un bitmap class Writer { private: // Objetos y punteros - Text *text; // Objeto encargado de escribir el texto + std::shared_ptr text_; // Objeto encargado de escribir el texto // Variables - int posX; // Posicion en el eje X donde empezar a escribir el texto - int posY; // Posicion en el eje Y donde empezar a escribir el texto - int kerning; // Kerning del texto, es decir, espaciado entre caracteres - std::string caption; // El texto para escribir - int speed; // Velocidad de escritura - int writingCounter; // Temporizador de escritura para cada caracter - int index; // Posición del texto que se está escribiendo - int lenght; // Longitud de la cadena a escribir - bool completed; // Indica si se ha escrito todo el texto - bool enabled; // Indica si el objeto está habilitado - int enabledCounter; // Temporizador para deshabilitar el objeto - bool finished; // Indica si ya ha terminado + int posX_; // Posicion en el eje X donde empezar a escribir el texto + int posY_; // Posicion en el eje Y donde empezar a escribir el texto + int kerning_; // Kerning del texto, es decir, espaciado entre caracteres + std::string caption_; // El texto para escribir + int speed_; // Velocidad de escritura + int writingCounter_; // Temporizador de escritura para cada caracter + int index_; // Posición del texto que se está escribiendo + int lenght_; // Longitud de la cadena a escribir + bool completed_; // Indica si se ha escrito todo el texto + bool enabled_; // Indica si el objeto está habilitado + int enabledCounter_; // Temporizador para deshabilitar el objeto + bool finished_; // Indica si ya ha terminado public: // Constructor - Writer(Text *text); + Writer(std::shared_ptr text); // Destructor ~Writer() = default; @@ -35,7 +36,7 @@ public: void update(); // Dibuja el objeto en pantalla - void render(); + void render() const; // Establece el valor de la variable void setPosX(int value); @@ -59,10 +60,7 @@ public: bool IsEnabled() const; // Establece el valor de la variable - void setEnabledCounter(int time); - - // Obtiene el valor de la variable - int getEnabledCounter() const; + void setFinishedCounter(int time); // Centra la cadena de texto a un punto X void center(int x);