From 20b9a95619fcc6838bc3f68aa1ac5af978ba1bd4 Mon Sep 17 00:00:00 2001 From: Sergio Valor Date: Fri, 17 Apr 2026 22:20:37 +0200 Subject: [PATCH] cppcheck --- source/core/audio/jail_audio.hpp | 6 +- source/core/input/input.cpp | 23 ++-- source/core/input/input.h | 2 +- source/core/rendering/animatedsprite.cpp | 44 +++--- source/core/rendering/animatedsprite.h | 18 +-- source/core/rendering/fade.cpp | 6 +- source/core/rendering/fade.h | 28 ++-- source/core/rendering/movingsprite.cpp | 67 +++------ source/core/rendering/movingsprite.h | 2 +- source/core/rendering/screen.cpp | 6 +- source/core/rendering/sprite.cpp | 58 +++----- source/core/rendering/sprite.h | 2 +- source/core/rendering/text.cpp | 22 +-- source/core/rendering/text.h | 22 +-- source/core/rendering/texture.cpp | 35 +++-- source/core/rendering/texture.h | 4 +- source/core/rendering/writer.cpp | 33 +++-- source/core/rendering/writer.h | 4 +- source/core/resources/asset.cpp | 20 +-- source/core/resources/asset.h | 8 +- source/core/resources/resource.h | 2 +- source/core/resources/resource_pack.cpp | 8 +- source/game/entities/balloon.cpp | 8 +- source/game/entities/item.cpp | 3 - source/game/entities/player.cpp | 15 +-- source/game/entities/player.h | 4 +- source/game/game.cpp | 164 +++-------------------- source/game/game.h | 22 +-- source/game/scenes/intro.cpp | 33 +---- source/game/scenes/intro.h | 8 +- source/game/scenes/logo.cpp | 16 +-- source/game/scenes/logo.h | 5 +- source/game/scenes/title.cpp | 46 ++----- source/game/scenes/title.h | 5 +- source/game/ui/menu.cpp | 88 +++++------- source/game/ui/menu.h | 22 +-- source/utils/utils.cpp | 47 +++---- source/utils/utils.h | 26 ++-- 38 files changed, 310 insertions(+), 622 deletions(-) diff --git a/source/core/audio/jail_audio.hpp b/source/core/audio/jail_audio.hpp index 6fe39b1..5b78a38 100644 --- a/source/core/audio/jail_audio.hpp +++ b/source/core/audio/jail_audio.hpp @@ -96,15 +96,15 @@ inline int JA_FeedMusicChunk(JA_Music_t* music) { if (!music || !music->vorbis || !music->stream) return 0; short chunk[JA_MUSIC_CHUNK_SHORTS]; - const int channels = music->spec.channels; + const int numChannels = music->spec.channels; const int samples_per_channel = stb_vorbis_get_samples_short_interleaved( music->vorbis, - channels, + numChannels, chunk, JA_MUSIC_CHUNK_SHORTS); if (samples_per_channel <= 0) return 0; - const int bytes = samples_per_channel * channels * JA_MUSIC_BYTES_PER_SAMPLE; + const int bytes = samples_per_channel * numChannels * JA_MUSIC_BYTES_PER_SAMPLE; SDL_PutAudioStreamData(music->stream, chunk, bytes); return samples_per_channel; } diff --git a/source/core/input/input.cpp b/source/core/input/input.cpp index 62ae4a8..f03eac3 100644 --- a/source/core/input/input.cpp +++ b/source/core/input/input.cpp @@ -2,7 +2,8 @@ #include -#include // for basic_ostream, operator<<, cout, basi... +#include // for any_of +#include // for basic_ostream, operator<<, cout, basi... // Emscripten-only: SDL 3.4+ ja no casa el GUID dels mandos de Chrome Android // amb gamecontrollerdb (el gamepad.id d'Android no porta Vendor/Product, el @@ -57,10 +58,12 @@ auto Input::get() -> Input * { } // Constructor -Input::Input(std::string file) { - // Fichero gamecontrollerdb.txt - dbPath = file; - +Input::Input(const std::string &file) + : numGamepads(0), + dbPath(file), + verbose(true), + disabledUntil(d_notDisabled), + enabled(true) { // Inicializa las variables keyBindings_t kb; kb.scancode = 0; @@ -71,10 +74,6 @@ Input::Input(std::string file) { gcb.button = SDL_GAMEPAD_BUTTON_INVALID; gcb.active = false; gameControllerBindings.resize(input_number_of_inputs, gcb); - - numGamepads = 0; - verbose = true; - enabled = true; } // Destructor @@ -311,10 +310,8 @@ bool Input::handleGamepadAdded(SDL_JoystickID jid, std::string &outName) { } // Si el mando ya está registrado no hace nada (ej. evento retroactivo tras el scan inicial) - for (SDL_JoystickID existing : connectedControllerIds) { - if (existing == jid) { - return false; - } + if (std::any_of(connectedControllerIds.begin(), connectedControllerIds.end(), [jid](SDL_JoystickID existing) { return existing == jid; })) { + return false; } installWebStandardMapping(jid); diff --git a/source/core/input/input.h b/source/core/input/input.h index 290890c..a5600bd 100644 --- a/source/core/input/input.h +++ b/source/core/input/input.h @@ -80,7 +80,7 @@ class Input { std::string buildControllerName(SDL_Gamepad *pad, int padIndex); // Constructor privado (usar Input::init) - Input(std::string file); + explicit Input(const std::string &file); // Instancia única static Input *instance; diff --git a/source/core/rendering/animatedsprite.cpp b/source/core/rendering/animatedsprite.cpp index 74e7f7e..86b7d61 100644 --- a/source/core/rendering/animatedsprite.cpp +++ b/source/core/rendering/animatedsprite.cpp @@ -22,6 +22,8 @@ static animatedSprite_t parseAnimationStream(std::istream &file, Texture *textur while (std::getline(file, line)) { if (line == "[animation]") { animation_t buffer; + buffer.speed = 0; + buffer.loop = -1; buffer.counter = 0; buffer.currentFrame = 0; buffer.completed = false; @@ -82,7 +84,7 @@ static animatedSprite_t parseAnimationStream(std::istream &file, Texture *textur } // Carga la animación desde un fichero -animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose) { +animatedSprite_t loadAnimationFromFile(Texture *texture, const std::string &filePath, bool verbose) { const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1); std::ifstream file(filePath); if (!file.good()) { @@ -109,42 +111,34 @@ animatedSprite_t loadAnimationFromMemory(Texture *texture, const std::vector *buffer) { +AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, const std::string &file, std::vector *buffer) + : currentAnimation(0) { // Copia los punteros setTexture(texture); setRenderer(renderer); // Carga las animaciones - if (file != "") { + if (!file.empty()) { animatedSprite_t as = loadAnimationFromFile(texture, file); // Copia los datos de las animaciones - for (auto animation : as.animations) { - this->animation.push_back(animation); - } + animation.insert(animation.end(), as.animations.begin(), as.animations.end()); } else if (buffer) { loadFromVector(buffer); } - - // Inicializa variables - currentAnimation = 0; } // Constructor -AnimatedSprite::AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation) { +AnimatedSprite::AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation) + : currentAnimation(0) { // Copia los punteros setTexture(animation->texture); setRenderer(renderer); - // Inicializa variables - currentAnimation = 0; - // Copia los datos de las animaciones - for (auto a : animation->animations) { - this->animation.push_back(a); - } + this->animation.insert(this->animation.end(), animation->animations.begin(), animation->animations.end()); } // Destructor @@ -156,10 +150,10 @@ AnimatedSprite::~AnimatedSprite() { } // Obtiene el indice de la animación a partir del nombre -int AnimatedSprite::getIndex(std::string name) { +int AnimatedSprite::getIndex(const std::string &name) { int index = -1; - for (auto a : animation) { + for (const auto &a : animation) { index++; if (a.name == name) { return index; @@ -222,12 +216,12 @@ void AnimatedSprite::setCurrentFrame(int num) { } // Establece el valor del contador -void AnimatedSprite::setAnimationCounter(std::string name, int num) { +void AnimatedSprite::setAnimationCounter(const std::string &name, int num) { animation[getIndex(name)].counter = num; } // Establece la velocidad de una animación -void AnimatedSprite::setAnimationSpeed(std::string name, int speed) { +void AnimatedSprite::setAnimationSpeed(const std::string &name, int speed) { animation[getIndex(name)].counter = speed; } @@ -237,7 +231,7 @@ void AnimatedSprite::setAnimationSpeed(int index, int speed) { } // Establece si la animación se reproduce en bucle -void AnimatedSprite::setAnimationLoop(std::string name, int loop) { +void AnimatedSprite::setAnimationLoop(const std::string &name, int loop) { animation[getIndex(name)].loop = loop; } @@ -247,7 +241,7 @@ void AnimatedSprite::setAnimationLoop(int index, int loop) { } // Establece el valor de la variable -void AnimatedSprite::setAnimationCompleted(std::string name, bool value) { +void AnimatedSprite::setAnimationCompleted(const std::string &name, bool value) { animation[getIndex(name)].completed = value; } @@ -262,7 +256,7 @@ bool AnimatedSprite::animationIsCompleted() { } // Devuelve el rectangulo de una animación y frame concreto -SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index) { +SDL_Rect AnimatedSprite::getAnimationClip(const std::string &name, Uint8 index) { return animation[getIndex(name)].frames[index]; } @@ -292,6 +286,8 @@ 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; + buffer.speed = 0; + buffer.loop = -1; buffer.counter = 0; buffer.currentFrame = 0; buffer.completed = false; @@ -391,7 +387,7 @@ bool AnimatedSprite::loadFromVector(std::vector *source) { } // Establece la animacion actual -void AnimatedSprite::setCurrentAnimation(std::string name) { +void AnimatedSprite::setCurrentAnimation(const std::string &name) { const int newAnimation = getIndex(name); if (currentAnimation != newAnimation) { currentAnimation = newAnimation; diff --git a/source/core/rendering/animatedsprite.h b/source/core/rendering/animatedsprite.h index ba04393..62e12ad 100644 --- a/source/core/rendering/animatedsprite.h +++ b/source/core/rendering/animatedsprite.h @@ -25,7 +25,7 @@ struct animatedSprite_t { }; // Carga la animación desde un fichero -animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose = false); +animatedSprite_t loadAnimationFromFile(Texture *texture, const std::string &filePath, bool verbose = false); // Carga la animación desde bytes en memoria animatedSprite_t loadAnimationFromMemory(Texture *texture, const std::vector &bytes, const std::string &nameForLogs = "", bool verbose = false); @@ -38,7 +38,7 @@ class AnimatedSprite : public MovingSprite { public: // Constructor - AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector *buffer = nullptr); + explicit AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, const std::string &file = "", std::vector *buffer = nullptr); AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation); // Destructor @@ -54,35 +54,35 @@ class AnimatedSprite : public MovingSprite { void setCurrentFrame(int num); // Establece el valor del contador - void setAnimationCounter(std::string name, int num); + void setAnimationCounter(const std::string &name, int num); // Establece la velocidad de una animación - void setAnimationSpeed(std::string name, int speed); + void setAnimationSpeed(const std::string &name, int speed); void setAnimationSpeed(int index, int speed); // Establece el frame al que vuelve la animación al finalizar - void setAnimationLoop(std::string name, int loop); + void setAnimationLoop(const std::string &name, int loop); void setAnimationLoop(int index, int loop); // Establece el valor de la variable - void setAnimationCompleted(std::string name, bool value); + void setAnimationCompleted(const std::string &name, bool value); void setAnimationCompleted(int index, bool value); // Comprueba si ha terminado la animación bool animationIsCompleted(); // Devuelve el rectangulo de una animación y frame concreto - SDL_Rect getAnimationClip(std::string name = "default", Uint8 index = 0); + SDL_Rect getAnimationClip(const std::string &name = "default", Uint8 index = 0); SDL_Rect getAnimationClip(int indexA = 0, Uint8 indexF = 0); // Obtiene el indice de la animación a partir del nombre - int getIndex(std::string name); + int getIndex(const std::string &name); // Carga la animación desde un vector bool loadFromVector(std::vector *source); // Establece la animacion actual - void setCurrentAnimation(std::string name = "default"); + void setCurrentAnimation(const std::string &name = "default"); void setCurrentAnimation(int index = 0); // Actualiza las variables del objeto diff --git a/source/core/rendering/fade.cpp b/source/core/rendering/fade.cpp index 1d6a582..175aa1a 100644 --- a/source/core/rendering/fade.cpp +++ b/source/core/rendering/fade.cpp @@ -8,9 +8,8 @@ #include "game/defaults.hpp" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH // Constructor -Fade::Fade(SDL_Renderer *renderer) { - mRenderer = renderer; - +Fade::Fade(SDL_Renderer *renderer) + : mRenderer(renderer) { mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); if (mBackbuffer != nullptr) { SDL_SetTextureScaleMode(mBackbuffer, SDL_SCALEMODE_NEAREST); @@ -53,7 +52,6 @@ void Fade::render() { int alpha = mCounter * 4; if (alpha >= 255) { - alpha = 255; mFullscreenDone = true; // Deja todos los buffers del mismo color diff --git a/source/core/rendering/fade.h b/source/core/rendering/fade.h index a3bccbb..47781ef 100644 --- a/source/core/rendering/fade.h +++ b/source/core/rendering/fade.h @@ -10,23 +10,23 @@ constexpr int FADE_RANDOM_SQUARE = 2; // Clase Fade class Fade { private: - SDL_Renderer *mRenderer; // El renderizador de la ventana - SDL_Texture *mBackbuffer; // Textura para usar como backbuffer - Uint8 mFadeType; // Tipo de fade a realizar - Uint16 mCounter; // Contador interno - bool mEnabled; // Indica si el fade está activo - bool mFinished; // Indica si ha terminado la transición - Uint8 mR, mG, mB; // Colores para el fade - Uint8 mROriginal, mGOriginal, mBOriginal; // Colores originales para FADE_RANDOM_SQUARE - Uint32 mLastSquareTicks; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE) - Uint16 mSquaresDrawn; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE) - bool mFullscreenDone; // Indica si el fade fullscreen ha terminado la fase de fundido - SDL_Rect mRect1; // Rectangulo usado para crear los efectos de transición - SDL_Rect mRect2; // Rectangulo usado para crear los efectos de transición + SDL_Renderer *mRenderer = nullptr; // El renderizador de la ventana + SDL_Texture *mBackbuffer = nullptr; // Textura para usar como backbuffer + Uint8 mFadeType = FADE_FULLSCREEN; // Tipo de fade a realizar + Uint16 mCounter = 0; // Contador interno + bool mEnabled = false; // Indica si el fade está activo + bool mFinished = false; // Indica si ha terminado la transición + Uint8 mR = 0, mG = 0, mB = 0; // Colores para el fade + Uint8 mROriginal = 0, mGOriginal = 0, mBOriginal = 0; // Colores originales para FADE_RANDOM_SQUARE + Uint32 mLastSquareTicks = 0; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE) + Uint16 mSquaresDrawn = 0; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE) + bool mFullscreenDone = false; // Indica si el fade fullscreen ha terminado la fase de fundido + SDL_Rect mRect1{}; // Rectangulo usado para crear los efectos de transición + SDL_Rect mRect2{}; // Rectangulo usado para crear los efectos de transición public: // Constructor - Fade(SDL_Renderer *renderer); + explicit Fade(SDL_Renderer *renderer); // Destructor ~Fade(); diff --git a/source/core/rendering/movingsprite.cpp b/source/core/rendering/movingsprite.cpp index c19e1bb..2a9476b 100644 --- a/source/core/rendering/movingsprite.cpp +++ b/source/core/rendering/movingsprite.cpp @@ -3,53 +3,26 @@ #include "core/rendering/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, SDL_Renderer *renderer) { - // Copia los punteros - this->texture = texture; - this->renderer = renderer; - - // Establece el alto y el ancho del sprite - this->w = w; - this->h = h; - - // Establece la posición X,Y del sprite - this->x = x; - this->y = y; - 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; - - // Establece el angulo con el que se dibujará - angle = (double)0; - - // Establece los valores de rotacion - rotateEnabled = false; - rotateSpeed = 0; - rotateAmount = (double)0; - - // Contador interno - counter = 0; - - // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; - - // Establece el centro de rotación - center = nullptr; - - // Establece el tipo de volteado - currentFlip = SDL_FLIP_NONE; -}; +MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture, SDL_Renderer *renderer) + : Sprite(0, 0, w, h, texture, renderer), + x(x), + y(y), + xPrev(x), + yPrev(y), + vx(velx), + vy(vely), + ax(accelx), + ay(accely), + zoomW(1), + zoomH(1), + angle(0.0), + rotateEnabled(false), + rotateSpeed(0), + rotateAmount(0.0), + counter(0), + center(nullptr), + currentFlip(SDL_FLIP_NONE) { +} // Reinicia todas las variables void MovingSprite::clear() { diff --git a/source/core/rendering/movingsprite.h b/source/core/rendering/movingsprite.h index b212312..19c1e0e 100644 --- a/source/core/rendering/movingsprite.h +++ b/source/core/rendering/movingsprite.h @@ -33,7 +33,7 @@ class MovingSprite : public 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, SDL_Renderer *renderer = nullptr); + explicit 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, SDL_Renderer *renderer = nullptr); // Mueve el sprite void move(); diff --git a/source/core/rendering/screen.cpp b/source/core/rendering/screen.cpp index d483d3a..6d8a4f0 100644 --- a/source/core/rendering/screen.cpp +++ b/source/core/rendering/screen.cpp @@ -77,7 +77,8 @@ auto Screen::get() -> Screen * { } // Constructor -Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) { +Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) + : borderColor{0x00, 0x00, 0x00} { // Inicializa variables this->window = window; this->renderer = renderer; @@ -85,9 +86,6 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) { gameCanvasWidth = GAMECANVAS_WIDTH; gameCanvasHeight = GAMECANVAS_HEIGHT; - // Define el color del borde para el modo de pantalla completa - borderColor = {0x00, 0x00, 0x00}; - // Establece el modo de video (fullscreen/ventana + logical presentation) // ANTES de crear la textura — SDL3 GPU necesita la logical presentation // del renderer ya aplicada al swapchain quan es reclama la ventana per a GPU. diff --git a/source/core/rendering/sprite.cpp b/source/core/rendering/sprite.cpp index 5c40845..a9a85e2 100644 --- a/source/core/rendering/sprite.cpp +++ b/source/core/rendering/sprite.cpp @@ -3,48 +3,26 @@ #include "core/rendering/texture.h" // for Texture // Constructor -Sprite::Sprite(int x, int y, int w, int h, Texture *texture, SDL_Renderer *renderer) { - // Establece la posición X,Y del sprite - this->x = x; - this->y = y; - - // Establece el alto y el ancho del sprite - this->w = w; - this->h = h; - - // Establece el puntero al renderizador de la ventana - this->renderer = renderer; - - // Establece la textura donde están los gráficos para el sprite - this->texture = texture; - - // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; - - // Inicializa variables - enabled = true; +Sprite::Sprite(int x, int y, int w, int h, Texture *texture, SDL_Renderer *renderer) + : x(x), + y(y), + w(w), + h(h), + renderer(renderer), + texture(texture), + spriteClip{0, 0, w, h}, + enabled(true) { } -Sprite::Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer) { - // Establece la posición X,Y del sprite - x = rect.x; - y = rect.y; - - // Establece el alto y el ancho del sprite - w = rect.w; - h = rect.h; - - // Establece el puntero al renderizador de la ventana - this->renderer = renderer; - - // Establece la textura donde están los gráficos para el sprite - this->texture = texture; - - // Establece el rectangulo de donde coger la imagen - spriteClip = {0, 0, w, h}; - - // Inicializa variables - enabled = true; +Sprite::Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer) + : x(rect.x), + y(rect.y), + w(rect.w), + h(rect.h), + renderer(renderer), + texture(texture), + spriteClip{0, 0, rect.w, rect.h}, + enabled(true) { } // Destructor diff --git a/source/core/rendering/sprite.h b/source/core/rendering/sprite.h index 60ae114..d86f711 100644 --- a/source/core/rendering/sprite.h +++ b/source/core/rendering/sprite.h @@ -19,7 +19,7 @@ class Sprite { public: // Constructor - Sprite(int x = 0, int y = 0, int w = 0, int h = 0, Texture *texture = nullptr, SDL_Renderer *renderer = nullptr); + explicit Sprite(int x = 0, int y = 0, int w = 0, int h = 0, Texture *texture = nullptr, SDL_Renderer *renderer = nullptr); Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer); // Destructor diff --git a/source/core/rendering/text.cpp b/source/core/rendering/text.cpp index cb9cfc8..eb50c65 100644 --- a/source/core/rendering/text.cpp +++ b/source/core/rendering/text.cpp @@ -39,8 +39,10 @@ static void computeTextFileOffsets(textFile_t &tf) { } // Llena una estructuta textFile_t desde un fichero -textFile_t LoadTextFile(std::string file, bool verbose) { +textFile_t LoadTextFile(const std::string &file, bool verbose) { textFile_t tf; + tf.boxWidth = 0; + tf.boxHeight = 0; for (int i = 0; i < 128; ++i) { tf.offset[i].x = 0; tf.offset[i].y = 0; @@ -65,6 +67,8 @@ textFile_t LoadTextFile(std::string file, bool verbose) { // Llena una estructura textFile_t desde bytes en memoria textFile_t LoadTextFileFromMemory(const std::vector &bytes, bool verbose) { textFile_t tf; + tf.boxWidth = 0; + tf.boxHeight = 0; for (int i = 0; i < 128; ++i) { tf.offset[i].x = 0; tf.offset[i].y = 0; @@ -83,7 +87,7 @@ textFile_t LoadTextFileFromMemory(const std::vector &bytes, bool verbos } // Constructor -Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer) { +Text::Text(const std::string &bitmapFile, const std::string &textFile, SDL_Renderer *renderer) { // Carga los offsets desde el fichero textFile_t tf = LoadTextFile(textFile); @@ -105,7 +109,7 @@ Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer) } // Constructor -Text::Text(std::string textFile, Texture *texture, SDL_Renderer *renderer) { +Text::Text(const std::string &textFile, Texture *texture, SDL_Renderer *renderer) { // Carga los offsets desde el fichero textFile_t tf = LoadTextFile(textFile); @@ -172,7 +176,7 @@ Text::~Text() { } // Escribe texto en pantalla -void Text::write(int x, int y, std::string text, int kerning, int lenght) { +void Text::write(int x, int y, const std::string &text, int kerning, int lenght) { int shift = 0; if (lenght == -1) { @@ -192,14 +196,14 @@ void Text::write(int x, int y, std::string text, int kerning, int lenght) { } // Escribe el texto con colores -void Text::writeColored(int x, int y, std::string text, color_t color, int kerning, int lenght) { +void Text::writeColored(int x, int y, const std::string &text, color_t color, int kerning, int lenght) { sprite->getTexture()->setColor(color.r, color.g, color.b); write(x, y, text, kerning, lenght); sprite->getTexture()->setColor(255, 255, 255); } // Escribe el texto con sombra -void Text::writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance, int kerning, int lenght) { +void Text::writeShadowed(int x, int y, const std::string &text, color_t color, Uint8 shadowDistance, int kerning, int lenght) { sprite->getTexture()->setColor(color.r, color.g, color.b); write(x + shadowDistance, y + shadowDistance, text, kerning, lenght); sprite->getTexture()->setColor(255, 255, 255); @@ -207,13 +211,13 @@ void Text::writeShadowed(int x, int y, std::string text, color_t color, Uint8 sh } // Escribe el texto centrado en un punto x -void Text::writeCentered(int x, int y, std::string text, int kerning, int lenght) { +void Text::writeCentered(int x, int y, const std::string &text, int kerning, int lenght) { x -= (Text::lenght(text, kerning) / 2); write(x, y, text, kerning, lenght); } // Escribe texto con extras -void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, color_t textColor, Uint8 shadowDistance, color_t shadowColor, int lenght) { +void Text::writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning, color_t textColor, Uint8 shadowDistance, color_t shadowColor, int lenght) { const bool centered = ((flags & TXT_CENTER) == TXT_CENTER); const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW); const bool colored = ((flags & TXT_COLOR) == TXT_COLOR); @@ -245,7 +249,7 @@ void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, col } // Obtiene la longitud en pixels de una cadena -int Text::lenght(std::string text, int kerning) { +int Text::lenght(const std::string &text, int kerning) { int shift = 0; for (int i = 0; i < (int)text.length(); ++i) diff --git a/source/core/rendering/text.h b/source/core/rendering/text.h index 2558898..fdb25c0 100644 --- a/source/core/rendering/text.h +++ b/source/core/rendering/text.h @@ -28,7 +28,7 @@ struct textFile_t { }; // Llena una estructuta textFile_t desde un fichero -textFile_t LoadTextFile(std::string file, bool verbose = false); +textFile_t LoadTextFile(const std::string &file, bool verbose = false); // Llena una estructura textFile_t desde bytes en memoria textFile_t LoadTextFileFromMemory(const std::vector &bytes, bool verbose = false); @@ -48,8 +48,8 @@ class Text { public: // Constructor - Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer); - Text(std::string textFile, Texture *texture, SDL_Renderer *renderer); + Text(const std::string &bitmapFile, const std::string &textFile, SDL_Renderer *renderer); + Text(const std::string &textFile, Texture *texture, SDL_Renderer *renderer); Text(textFile_t *textFile, Texture *texture, SDL_Renderer *renderer); // Constructor desde bytes en memoria: comparte ownership del texture (no lo libera) @@ -58,23 +58,27 @@ class Text { // Destructor ~Text(); + // No copiable (gestiona memoria dinámica) + Text(const Text &) = delete; + Text &operator=(const Text &) = delete; + // Escribe el texto en pantalla - void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); + void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe el texto con colores - void writeColored(int x, int y, std::string text, color_t color, int kerning = 1, int lenght = -1); + void writeColored(int x, int y, const std::string &text, color_t color, int kerning = 1, int lenght = -1); // Escribe el texto con sombra - void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); + void writeShadowed(int x, int y, const std::string &text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); // Escribe el texto centrado en un punto x - void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); + void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1); // Escribe texto con extras - void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, color_t textColor = color_t(255, 255, 255), Uint8 shadowDistance = 1, color_t shadowColor = color_t(0, 0, 0), int lenght = -1); + void writeDX(Uint8 flags, int x, int y, const std::string &text, int kerning = 1, color_t textColor = color_t(255, 255, 255), Uint8 shadowDistance = 1, color_t shadowColor = color_t(0, 0, 0), int lenght = -1); // Obtiene la longitud en pixels de una cadena - int lenght(std::string text, int kerning = 1); + int lenght(const std::string &text, int kerning = 1); // Devuelve el valor de la variable int getCharacterSize(); diff --git a/source/core/rendering/texture.cpp b/source/core/rendering/texture.cpp index 6037c43..a2b9d27 100644 --- a/source/core/rendering/texture.cpp +++ b/source/core/rendering/texture.cpp @@ -15,30 +15,25 @@ void Texture::setGlobalScaleMode(SDL_ScaleMode mode) { } // Constructor -Texture::Texture(SDL_Renderer *renderer, std::string path, bool verbose) { - // Copia punteros - this->renderer = renderer; - this->path = path; - - // Inicializa - texture = nullptr; - width = 0; - height = 0; - +Texture::Texture(SDL_Renderer *renderer, const std::string &path, bool verbose) + : texture(nullptr), + renderer(renderer), + width(0), + height(0), + path(path) { // Carga el fichero en la textura - if (path != "") { + if (!path.empty()) { loadFromFile(path, renderer, verbose); } } // Constructor desde bytes -Texture::Texture(SDL_Renderer *renderer, const std::vector &bytes, bool verbose) { - this->renderer = renderer; - this->path = ""; - texture = nullptr; - width = 0; - height = 0; - +Texture::Texture(SDL_Renderer *renderer, const std::vector &bytes, bool verbose) + : texture(nullptr), + renderer(renderer), + width(0), + height(0), + path("") { if (!bytes.empty()) { loadFromMemory(bytes.data(), bytes.size(), renderer, verbose); } @@ -53,7 +48,7 @@ Texture::~Texture() { // Helper: convierte píxeles RGBA decodificados por stbi en SDL_Texture static SDL_Texture *createTextureFromPixels(SDL_Renderer *renderer, unsigned char *data, int w, int h, int *out_w, int *out_h) { const int pitch = 4 * w; - SDL_Surface *loadedSurface = SDL_CreateSurfaceFrom(w, h, SDL_PIXELFORMAT_RGBA32, (void *)data, pitch); + SDL_Surface *loadedSurface = SDL_CreateSurfaceFrom(w, h, SDL_PIXELFORMAT_RGBA32, static_cast(data), pitch); if (loadedSurface == nullptr) { return nullptr; } @@ -68,7 +63,7 @@ static SDL_Texture *createTextureFromPixels(SDL_Renderer *renderer, unsigned cha } // Carga una imagen desde un fichero -bool Texture::loadFromFile(std::string path, SDL_Renderer *renderer, bool verbose) { +bool Texture::loadFromFile(const std::string &path, SDL_Renderer *renderer, bool verbose) { const std::string filename = path.substr(path.find_last_of("\\/") + 1); int req_format = STBI_rgb_alpha; int w, h, orig_format; diff --git a/source/core/rendering/texture.h b/source/core/rendering/texture.h index cb28984..ce3176a 100644 --- a/source/core/rendering/texture.h +++ b/source/core/rendering/texture.h @@ -24,7 +24,7 @@ class Texture { static void setGlobalScaleMode(SDL_ScaleMode mode); // Constructor - Texture(SDL_Renderer *renderer, std::string path = "", bool verbose = false); + explicit Texture(SDL_Renderer *renderer, const std::string &path = "", bool verbose = false); // Constructor desde bytes (PNG en memoria) Texture(SDL_Renderer *renderer, const std::vector &bytes, bool verbose = false); @@ -33,7 +33,7 @@ class Texture { ~Texture(); // Carga una imagen desde un fichero - bool loadFromFile(std::string path, SDL_Renderer *renderer, bool verbose = false); + bool loadFromFile(const std::string &path, SDL_Renderer *renderer, bool verbose = false); // Carga una imagen desde bytes en memoria bool loadFromMemory(const uint8_t *data, size_t size, SDL_Renderer *renderer, bool verbose = false); diff --git a/source/core/rendering/writer.cpp b/source/core/rendering/writer.cpp index c02d1bd..74543ca 100644 --- a/source/core/rendering/writer.cpp +++ b/source/core/rendering/writer.cpp @@ -3,23 +3,20 @@ #include "core/rendering/text.h" // for Text // Constructor -Writer::Writer(Text *text) { - // Copia los punteros - this->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; +Writer::Writer(Text *text) + : text(text), + 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 @@ -73,7 +70,7 @@ void Writer::setKerning(int value) { } // Establece el valor de la variable -void Writer::setCaption(std::string text) { +void Writer::setCaption(const std::string &text) { caption = text; lenght = text.length(); } diff --git a/source/core/rendering/writer.h b/source/core/rendering/writer.h index dbab728..79827b2 100644 --- a/source/core/rendering/writer.h +++ b/source/core/rendering/writer.h @@ -25,7 +25,7 @@ class Writer { public: // Constructor - Writer(Text *text); + explicit Writer(Text *text); // Actualiza el objeto void update(); @@ -43,7 +43,7 @@ class Writer { void setKerning(int value); // Establece el valor de la variable - void setCaption(std::string text); + void setCaption(const std::string &text); // Establece el valor de la variable void setSpeed(int value); diff --git a/source/core/resources/asset.cpp b/source/core/resources/asset.cpp index e8f972f..d7eae84 100644 --- a/source/core/resources/asset.cpp +++ b/source/core/resources/asset.cpp @@ -25,14 +25,14 @@ auto Asset::get() -> Asset * { } // Constructor -Asset::Asset(std::string executablePath) { - this->executablePath = executablePath.substr(0, executablePath.find_last_of("\\/")); - longestName = 0; - verbose = true; +Asset::Asset(const std::string &executablePath) + : longestName(0), + executablePath(executablePath.substr(0, executablePath.find_last_of("\\/"))), + verbose(true) { } // Añade un elemento a la lista -void Asset::add(std::string file, enum assetType type, bool required, bool absolute) { +void Asset::add(const std::string &file, enum assetType type, bool required, bool absolute) { item_t temp; temp.file = absolute ? file : executablePath + file; temp.type = type; @@ -44,8 +44,8 @@ void Asset::add(std::string file, enum assetType type, bool required, bool absol } // Devuelve el fichero de un elemento de la lista a partir de una cadena -std::string Asset::get(std::string text) { - for (auto f : fileList) { +std::string Asset::get(const std::string &text) { + for (const auto &f : fileList) { const size_t lastIndex = f.file.find_last_of("/") + 1; const std::string file = f.file.substr(lastIndex, std::string::npos); @@ -76,7 +76,7 @@ bool Asset::check() { // Comprueba si hay ficheros de ese tipo bool any = false; - for (auto f : fileList) { + for (const auto &f : fileList) { if ((f.required) && (f.type == type)) { any = true; } @@ -88,7 +88,7 @@ bool Asset::check() { std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl; } - for (auto f : fileList) { + for (const auto &f : fileList) { if ((f.required) && (f.type == type)) { success &= checkFile(f.file); } @@ -111,7 +111,7 @@ bool Asset::check() { } // Comprueba que existe un fichero -bool Asset::checkFile(std::string path) { +bool Asset::checkFile(const std::string &path) { bool success = false; std::string result = "ERROR"; diff --git a/source/core/resources/asset.h b/source/core/resources/asset.h index dae5d3a..575c931 100644 --- a/source/core/resources/asset.h +++ b/source/core/resources/asset.h @@ -34,13 +34,13 @@ class Asset { bool verbose; // Indica si ha de mostrar información por pantalla // Comprueba que existe un fichero - bool checkFile(std::string executablePath); + bool checkFile(const std::string &executablePath); // Devuelve el nombre del tipo de recurso std::string getTypeName(int type); // Constructor privado (usar Asset::init) - Asset(std::string path); + explicit Asset(const std::string &path); // Instancia única static Asset *instance; @@ -52,10 +52,10 @@ class Asset { static auto get() -> Asset *; // Obtiene el puntero a la instancia // Añade un elemento a la lista - void add(std::string file, enum assetType type, bool required = true, bool absolute = false); + void add(const std::string &file, enum assetType type, bool required = true, bool absolute = false); // Devuelve un elemento de la lista a partir de una cadena - std::string get(std::string text); + std::string get(const std::string &text); // Devuelve toda la lista de items registrados const std::vector &getAll() const { return fileList; } diff --git a/source/core/resources/resource.h b/source/core/resources/resource.h index 9968155..f601dd4 100644 --- a/source/core/resources/resource.h +++ b/source/core/resources/resource.h @@ -30,7 +30,7 @@ class Resource { const std::vector &getDemoBytes() const { return demoBytes_; } private: - Resource(SDL_Renderer *renderer); + explicit Resource(SDL_Renderer *renderer); ~Resource(); void preloadAll(); diff --git a/source/core/resources/resource_pack.cpp b/source/core/resources/resource_pack.cpp index 7dbe062..34635cf 100644 --- a/source/core/resources/resource_pack.cpp +++ b/source/core/resources/resource_pack.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCRS_RESOURCES__2026"; @@ -17,11 +18,8 @@ ResourcePack::~ResourcePack() { } uint32_t ResourcePack::calculateChecksum(const std::vector& data) { - uint32_t checksum = 0x12345678; - for (unsigned char i : data) { - checksum = ((checksum << 5) + checksum) + i; - } - return checksum; + return std::accumulate(data.begin(), data.end(), uint32_t(0x12345678), + [](uint32_t acc, uint8_t b) { return ((acc << 5) + acc) + b; }); } void ResourcePack::encryptData(std::vector& data, const std::string& key) { diff --git a/source/game/entities/balloon.cpp b/source/game/entities/balloon.cpp index 2310be9..9dd1d83 100644 --- a/source/game/entities/balloon.cpp +++ b/source/game/entities/balloon.cpp @@ -261,15 +261,13 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c stoppedCounter = 0; blinking = false; visible = true; - invulnerable = true; - beingCreated = true; creationCounter = creationtimer; creationCounterIni = creationtimer; popping = false; - // Actualiza valores - beingCreated = creationCounter == 0 ? false : true; - invulnerable = beingCreated == false ? false : true; + // Valores iniciales dependentes del timer + beingCreated = creationCounter != 0; + invulnerable = beingCreated; counter = 0; travelY = 1.0f; diff --git a/source/game/entities/item.cpp b/source/game/entities/item.cpp index f7af964..c9817bf 100644 --- a/source/game/entities/item.cpp +++ b/source/game/entities/item.cpp @@ -107,9 +107,6 @@ void Item::move() { // Si el objeto se sale por la parte inferior if (posY + height > PLAY_AREA_BOTTOM) { - // Corrige - posY -= velY; - // Detiene el objeto velY = 0; velX = 0; diff --git a/source/game/entities/player.cpp b/source/game/entities/player.cpp index f505df3..ae1d20a 100644 --- a/source/game/entities/player.cpp +++ b/source/game/entities/player.cpp @@ -8,7 +8,7 @@ #include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT // Constructor -Player::Player(float x, int y, SDL_Renderer *renderer, std::vector texture, std::vector *> animations) { +Player::Player(float x, int y, SDL_Renderer *renderer, const std::vector &texture, const std::vector *> &animations) { // Copia los punteros this->renderer = renderer; @@ -189,19 +189,12 @@ void Player::render() { // Establece el estado del jugador cuando camina void Player::setWalkingStatus(Uint8 status) { - // Si cambiamos de estado, reiniciamos la animación - if (statusWalking != status) { - statusWalking = status; - // legsSprite->setCurrentFrame(0); - } + statusWalking = status; } // Establece el estado del jugador cuando dispara void Player::setFiringStatus(Uint8 status) { - // Si cambiamos de estado, reiniciamos la animación - if (statusFiring != status) { - statusFiring = status; - } + statusFiring = status; } // Establece la animación correspondiente al estado @@ -521,7 +514,7 @@ void Player::updatePowerUpHeadOffset() { } // Pone las texturas del jugador -void Player::setPlayerTextures(std::vector texture) { +void Player::setPlayerTextures(const std::vector &texture) { headSprite->setTexture(texture[0]); bodySprite->setTexture(texture[1]); legsSprite->setTexture(texture[2]); diff --git a/source/game/entities/player.h b/source/game/entities/player.h index 80a9902..6d4a014 100644 --- a/source/game/entities/player.h +++ b/source/game/entities/player.h @@ -81,7 +81,7 @@ class Player { public: // Constructor - Player(float x, int y, SDL_Renderer *renderer, std::vector texture, std::vector *> animations); + Player(float x, int y, SDL_Renderer *renderer, const std::vector &texture, const std::vector *> &animations); // Destructor ~Player(); @@ -96,7 +96,7 @@ class Player { void render(); // Pone las texturas del jugador - void setPlayerTextures(std::vector texture); + void setPlayerTextures(const std::vector &texture); // Actua en consecuencia de la entrada recibida void setInput(Uint8 input); diff --git a/source/game/game.cpp b/source/game/game.cpp index 9972b2e..43ade2a 100644 --- a/source/game/game.cpp +++ b/source/game/game.cpp @@ -4,6 +4,7 @@ #include // for rand #include // for max, min +#include // for accumulate #include // for basic_ifstream #include // for basic_ostream, char_traits, operator<< @@ -30,7 +31,8 @@ struct JA_Sound_t; // Constructor -Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, section_t *section) { +Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, section_t *section) + : lastStageReached(currentStage) { // Copia los punteros this->renderer = renderer; this->section = section; @@ -43,7 +45,6 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo, #else this->currentStage = currentStage; #endif - lastStageReached = currentStage; if (numPlayers == 1) { // Si solo juega un jugador, permite jugar tanto con teclado como con mando onePlayerControl = Options::inputs[0].deviceType; Options::inputs[0].deviceType = INPUT_USE_ANY; @@ -961,7 +962,6 @@ void Game::initEnemyFormations() { // #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simetricos j = 24; enemyFormation[j].numberOfEnemies = 30; - incX = 0; incTime = 5; for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) { Uint8 half = enemyFormation[j].numberOfEnemies / 2; @@ -981,7 +981,6 @@ void Game::initEnemyFormations() { // #25 - Treinta enemigos BALLOON1. Del centro hacia adentro. Juntos. Simetricos j = 25; enemyFormation[j].numberOfEnemies = 30; - incX = BALLOON_WIDTH_1 + 1; incTime = 5; for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) { Uint8 half = enemyFormation[j].numberOfEnemies / 2; @@ -1486,12 +1485,12 @@ void Game::updateStage() { // Actualiza el estado de muerte void Game::updateDeath() { // Comprueba si todos los jugadores estan muertos - bool allPlayersAreDead = true; + bool allDead = true; for (auto player : players) { - allPlayersAreDead &= (!player->isAlive()); + allDead &= (!player->isAlive()); } - if (allPlayersAreDead) { + if (allDead) { if (deathCounter > 0) { deathCounter--; @@ -1608,30 +1607,6 @@ void Game::incBalloonSpeed() { } } -// Decrementa la velocidad de los globos -void Game::decBalloonSpeed() { - // La velocidad solo se decrementa en el modo normal - if (difficulty == DIFFICULTY_NORMAL) { - if (enemySpeed == BALLOON_SPEED_5) { - enemySpeed = BALLOON_SPEED_4; - } - - else if (enemySpeed == BALLOON_SPEED_4) { - enemySpeed = BALLOON_SPEED_3; - } - - else if (enemySpeed == BALLOON_SPEED_3) { - enemySpeed = BALLOON_SPEED_2; - } - - else if (enemySpeed == BALLOON_SPEED_2) { - enemySpeed = BALLOON_SPEED_1; - } - - setBalloonSpeed(enemySpeed); - } -} - // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase void Game::updateBalloonSpeed() { const float percent = (float)stage[currentStage].currentPower / (float)stage[currentStage].powerToComplete; @@ -1761,17 +1736,6 @@ void Game::destroyBalloon(Balloon *balloon) { evaluateAndSetMenace(); } -// Explosiona todos los globos -void Game::popAllBalloons() { - for (auto balloon : balloons) { - if ((balloon->isEnabled()) && (!balloon->isPopping()) && (!balloon->isBeingCreated())) { - popBalloon(balloon); - } - } - - JA_PlaySound(balloonSound); -} - // Destruye todos los globos void Game::destroyAllBalloons() { for (auto balloon : balloons) { @@ -1808,21 +1772,6 @@ void Game::startAllBalloons() { } } -// Obtiene el numero de globos activos -Uint8 Game::countBalloons() { - Uint8 num = 0; - - for (auto balloon : balloons) { - if (balloon->isEnabled()) { - if (!balloon->isPopping()) { - num++; - } - } - } - - return num; -} - // Vacia el vector de globos void Game::freeBalloons() { if (balloons.empty() == false) { @@ -2090,7 +2039,7 @@ 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, const SmartSprite *sprite) { SmartSprite *ss = new SmartSprite(nullptr, renderer); smartSprites.push_back(ss); @@ -2235,12 +2184,8 @@ void Game::updateDeathSequence() { // Calcula y establece el valor de amenaza en funcion de los globos activos void Game::evaluateAndSetMenace() { - menaceCurrent = 0; - for (auto balloon : balloons) { - if (balloon->isEnabled()) { - menaceCurrent += balloon->getMenace(); - } - } + menaceCurrent = std::accumulate(balloons.begin(), balloons.end(), Uint8(0), + [](Uint8 acc, Balloon *b) { return b->isEnabled() ? acc + b->getMenace() : acc; }); } // Obtiene el valor de la variable @@ -2685,19 +2630,19 @@ void Game::renderMessages() { // STAGE NUMBER if (stageBitmapCounter < STAGE_COUNTER) { const int stageNum = stage[currentStage].number; - std::string text; + std::string stageText; if (stageNum == 10) { // Ultima fase - text = Lang::get()->getText(79); + stageText = Lang::get()->getText(79); } else { // X fases restantes - text = std::to_string(11 - stage[currentStage].number) + Lang::get()->getText(38); + stageText = std::to_string(11 - stage[currentStage].number) + Lang::get()->getText(38); } if (!gameCompleted) { // Escribe el numero de fases restantes - textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 2, shdwTxtColor); + textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], stageText, -2, noColor, 2, shdwTxtColor); } else { // Escribe el texto de juego completado - text = Lang::get()->getText(50); - textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 1, shdwTxtColor); + stageText = Lang::get()->getText(50); + textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], stageText, -2, noColor, 1, shdwTxtColor); textNokia2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter] + textNokiaBig2->getCharacterSize() + 2, Lang::get()->getText(76), -1, noColor, 1, shdwTxtColor); } } @@ -2813,7 +2758,7 @@ bool Game::hasFinished() const { } // Procesa un evento individual -void Game::handleEvent(SDL_Event *event) { +void Game::handleEvent(const SDL_Event *event) { // SDL_EVENT_QUIT ya lo maneja Director if (event->type == SDL_EVENT_WINDOW_FOCUS_LOST) { @@ -3025,23 +2970,6 @@ void Game::updateGameOverScreen() { } } -// Comprueba los eventos de la pantalla de game over -void Game::checkGameOverEvents() { - while (SDL_PollEvent(eventHandler) != 0) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_EVENT_QUIT) { - section->name = SECTION_PROG_QUIT; - break; - } else if (eventHandler->type == SDL_EVENT_KEY_DOWN && eventHandler->key.repeat == 0) { - if (gameCompleted) { - gameOverPostFade = 1; - fade->activateFade(); - JA_PlaySound(itemPickUpSound); - } - } - } -} - // Dibuja los elementos de la pantalla de game over void Game::renderGameOverScreen() { // Prepara para empezar a dibujar en la textura de juego @@ -3120,15 +3048,8 @@ bool Game::canPowerBallBeCreated() { // Calcula el poder actual de los globos en pantalla int Game::calculateScreenPower() { - int power = 0; - - for (auto balloon : balloons) { - if (balloon->isEnabled()) { - power += balloon->getPower(); - } - } - - return power; + return std::accumulate(balloons.begin(), balloons.end(), 0, + [](int acc, Balloon *b) { return b->isEnabled() ? acc + b->getPower() : acc; }); } // Inicializa las variables que contienen puntos de ruta para mover objetos @@ -3234,28 +3155,6 @@ bool Game::allPlayersAreDead() { return success; } -// Comprueba los eventos que hay en cola -void Game::checkEvents() { - while (SDL_PollEvent(eventHandler) != 0) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_EVENT_QUIT) { - section->name = SECTION_PROG_QUIT; - break; - } - - else if (eventHandler->type == SDL_EVENT_WINDOW_FOCUS_LOST) { - section->subsection = SUBSECTION_GAME_PAUSE; - } -#ifdef PAUSE - else if (eventHandler->type == SDL_EVENT_KEY_DOWN) { - if (eventHandler->key.scancode == SDL_SCANCODE_P) { - pause = !pause; - } - } -#endif - } -} - // Elimina todos los objetos contenidos en vectores void Game::deleteAllVectorObjects() { for (auto player : players) { @@ -3284,33 +3183,6 @@ void Game::deleteAllVectorObjects() { smartSprites.clear(); } -// Recarga las texturas -void Game::reloadTextures() { - for (auto texture : itemTextures) { - texture->reLoad(); - } - - for (auto texture : balloonTextures) { - texture->reLoad(); - } - - for (auto texture : player1Textures) { - texture->reLoad(); - } - - for (auto texture : player2Textures) { - texture->reLoad(); - } - - bulletTexture->reLoad(); - gameBuildingsTexture->reLoad(); - gameCloudsTexture->reLoad(); - gameGrassTexture->reLoad(); - gamePowerMeterTexture->reLoad(); - gameSkyColorsTexture->reLoad(); - gameTextTexture->reLoad(); -} - // Establece la máxima puntuación desde fichero o desde las puntuaciones online void Game::setHiScore() { // Carga el fichero de puntos diff --git a/source/game/game.h b/source/game/game.h index c623f03..e3ef843 100644 --- a/source/game/game.h +++ b/source/game/game.h @@ -259,9 +259,6 @@ class Game { // Dibuja el juego void render(); - // Comprueba los eventos que hay en cola - void checkEvents(); - // Inicializa las variables necesarias para la sección 'Game' void init(); @@ -340,9 +337,6 @@ class Game { // Incrementa la velocidad de los globos void incBalloonSpeed(); - // Decrementa la velocidad de los globos - void decBalloonSpeed(); - // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase void updateBalloonSpeed(); @@ -352,9 +346,6 @@ class Game { // Explosiona un globo. Lo destruye void destroyBalloon(Balloon *balloon); - // Explosiona todos los globos - void popAllBalloons(); - // Destruye todos los globos void destroyAllBalloons(); @@ -364,9 +355,6 @@ class Game { // Pone en marcha todos los globos void startAllBalloons(); - // Obtiene el numero de globos activos - Uint8 countBalloons(); - // Vacia el vector de globos void freeBalloons(); @@ -407,7 +395,7 @@ class Game { void freeItems(); // Crea un objeto SmartSprite - void createItemScoreSprite(int x, int y, SmartSprite *sprite); + void createItemScoreSprite(int x, int y, const SmartSprite *sprite); // Vacia el vector de smartsprites void freeSmartSprites(); @@ -505,9 +493,6 @@ class Game { // Inicializa el estado de game over void enterGameOverScreen(); - // Comprueba los eventos de la pantalla de game over - void checkGameOverEvents(); - // Indica si se puede crear una powerball bool canPowerBallBeCreated(); @@ -529,9 +514,6 @@ class Game { // Elimina todos los objetos contenidos en vectores void deleteAllVectorObjects(); - // Recarga las texturas - void reloadTextures(); - // Establece la máxima puntuación desde fichero o desde las puntuaciones online void setHiScore(); @@ -552,5 +534,5 @@ class Game { bool hasFinished() const; // Procesa un evento - void handleEvent(SDL_Event *event); + void handleEvent(const SDL_Event *event); }; diff --git a/source/game/scenes/intro.cpp b/source/game/scenes/intro.cpp index bfac324..2981595 100644 --- a/source/game/scenes/intro.cpp +++ b/source/game/scenes/intro.cpp @@ -145,8 +145,8 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) { texts[8]->setCaption(Lang::get()->getText(35)); texts[8]->setSpeed(16); - for (auto text : texts) { - text->center(GAMECANVAS_CENTER_X); + for (auto *t : texts) { + t->center(GAMECANVAS_CENTER_X); } JA_PlayMusic(music, 0); @@ -166,25 +166,6 @@ Intro::~Intro() { } } -// Carga los recursos (ya no carga nada, se mantiene por si hay callers) -bool Intro::loadMedia() { - return true; -} - -// Comprueba los eventos -void Intro::checkEvents() { -#ifndef __EMSCRIPTEN__ - // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_EVENT_QUIT) { - section->name = SECTION_PROG_QUIT; - break; - } - } -#endif -} - // Comprueba las entradas void Intro::checkInput() { #ifndef __EMSCRIPTEN__ @@ -352,8 +333,8 @@ void Intro::update() { bitmap->update(); } - for (auto text : texts) { - text->update(); + for (auto *t : texts) { + t->update(); } // Actualiza las escenas de la intro @@ -374,8 +355,8 @@ void Intro::render() { bitmap->render(); } - for (auto text : texts) { - text->render(); + for (auto *t : texts) { + t->render(); } // Vuelca el contenido del renderizador en pantalla @@ -398,6 +379,6 @@ void Intro::iterate() { } // Procesa un evento individual -void Intro::handleEvent(SDL_Event *event) { +void Intro::handleEvent(const SDL_Event *event) { // SDL_EVENT_QUIT ya lo maneja Director } diff --git a/source/game/scenes/intro.h b/source/game/scenes/intro.h index a8aab26..133846d 100644 --- a/source/game/scenes/intro.h +++ b/source/game/scenes/intro.h @@ -34,12 +34,6 @@ class Intro { // Dibuja el objeto en pantalla void render(); - // Carga los recursos - bool loadMedia(); - - // Comprueba los eventos - void checkEvents(); - // Comprueba las entradas void checkInput(); @@ -60,5 +54,5 @@ class Intro { void iterate(); // Procesa un evento - void handleEvent(SDL_Event *event); + void handleEvent(const SDL_Event *event); }; diff --git a/source/game/scenes/logo.cpp b/source/game/scenes/logo.cpp index 69a7a5c..8b32d02 100644 --- a/source/game/scenes/logo.cpp +++ b/source/game/scenes/logo.cpp @@ -56,20 +56,6 @@ void Logo::checkLogoEnd() { } } -// Comprueba los eventos -void Logo::checkEvents() { -#ifndef __EMSCRIPTEN__ - // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_EVENT_QUIT) { - section->name = SECTION_PROG_QUIT; - break; - } - } -#endif -} - // Comprueba las entradas void Logo::checkInput() { #ifndef __EMSCRIPTEN__ @@ -148,6 +134,6 @@ void Logo::iterate() { } // Procesa un evento individual -void Logo::handleEvent(SDL_Event *event) { +void Logo::handleEvent(const SDL_Event *event) { // SDL_EVENT_QUIT ya lo maneja Director } diff --git a/source/game/scenes/logo.h b/source/game/scenes/logo.h index a27ddba..bd37010 100644 --- a/source/game/scenes/logo.h +++ b/source/game/scenes/logo.h @@ -29,9 +29,6 @@ class Logo { // Comprueba si ha terminado el logo void checkLogoEnd(); - // Comprueba los eventos - void checkEvents(); - // Comprueba las entradas void checkInput(); @@ -52,5 +49,5 @@ class Logo { void iterate(); // Procesa un evento - void handleEvent(SDL_Event *event); + void handleEvent(const SDL_Event *event); }; diff --git a/source/game/scenes/title.cpp b/source/game/scenes/title.cpp index c354153..18864f2 100644 --- a/source/game/scenes/title.cpp +++ b/source/game/scenes/title.cpp @@ -112,16 +112,16 @@ void Title::init() { // Pone valores por defecto a las opciones de control Options::inputs.clear(); - input_t i; - i.id = 0; - i.name = "KEYBOARD"; - i.deviceType = INPUT_USE_KEYBOARD; - Options::inputs.push_back(i); + input_t inp; + inp.id = 0; + inp.name = "KEYBOARD"; + inp.deviceType = INPUT_USE_KEYBOARD; + Options::inputs.push_back(inp); - i.id = 0; - i.name = "GAME CONTROLLER"; - i.deviceType = INPUT_USE_GAMECONTROLLER; - Options::inputs.push_back(i); + inp.id = 0; + inp.name = "GAME CONTROLLER"; + inp.deviceType = INPUT_USE_GAMECONTROLLER; + Options::inputs.push_back(inp); // Comprueba si hay mandos conectados checkInputDevices(); @@ -609,32 +609,6 @@ void Title::render() { } } -// Comprueba los eventos -void Title::checkEvents() { - // Comprueba los eventos que hay en la cola - while (SDL_PollEvent(eventHandler) != 0) { - // Evento de salida de la aplicación - if (eventHandler->type == SDL_EVENT_QUIT) { - section->name = SECTION_PROG_QUIT; - break; - } - - else if (eventHandler->type == SDL_EVENT_RENDER_DEVICE_RESET || eventHandler->type == SDL_EVENT_RENDER_TARGETS_RESET) { - reLoadTextures(); - } - - if (section->subsection == SUBSECTION_TITLE_3) { // Si se pulsa alguna tecla durante la tercera sección del titulo - if ((eventHandler->type == SDL_EVENT_KEY_UP) || (eventHandler->type == SDL_EVENT_JOYSTICK_BUTTON_UP)) { - // Muestra el menu - menuVisible = true; - - // Reinicia el contador - counter = TITLE_COUNTER; - } - } - } -} - // Comprueba las entradas void Title::checkInput() { #ifndef __EMSCRIPTEN__ @@ -915,7 +889,7 @@ void Title::iterate() { } // Procesa un evento individual -void Title::handleEvent(SDL_Event *event) { +void Title::handleEvent(const SDL_Event *event) { // Si hay un sub-estado activo, delega el evento if (instructionsActive && instructions) { // SDL_EVENT_QUIT ya lo maneja Director diff --git a/source/game/scenes/title.h b/source/game/scenes/title.h index 3848f0a..6957220 100644 --- a/source/game/scenes/title.h +++ b/source/game/scenes/title.h @@ -107,9 +107,6 @@ class Title { // Dibuja el objeto en pantalla void render(); - // Comprueba los eventos - void checkEvents(); - // Comprueba las entradas void checkInput(); @@ -157,5 +154,5 @@ class Title { void iterate(); // Procesa un evento - void handleEvent(SDL_Event *event); + void handleEvent(const SDL_Event *event); }; diff --git a/source/game/ui/menu.cpp b/source/game/ui/menu.cpp index a435120..ba6ea14 100644 --- a/source/game/ui/menu.cpp +++ b/source/game/ui/menu.cpp @@ -2,6 +2,7 @@ #include // for max, min #include // for char_traits, basic_ifstream, basic_istream +#include // for accumulate #include // for basic_stringstream #include "core/audio/jail_audio.hpp" // for JA_LoadSound, JA_PlaySound, JA_DeleteSound @@ -11,7 +12,10 @@ #include "core/resources/resource_helper.h" // Constructor -Menu::Menu(SDL_Renderer *renderer, std::string file) { +Menu::Menu(SDL_Renderer *renderer, const std::string &file) + : colorGreyed{128, 128, 128}, + font_png(""), + font_txt("") { // Copia punteros this->renderer = renderer; @@ -21,7 +25,6 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) { soundCancel = nullptr; // Inicializa variables - name = ""; selector.index = 0; selector.previousIndex = 0; itemSelected = MENU_NO_OPTION; @@ -38,10 +41,7 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) { centerX = 0; centerY = 0; widestItem = 0; - colorGreyed = {128, 128, 128}; defaultActionWhenCancel = 0; - font_png = ""; - font_txt = ""; // Selector selector.originY = 0; @@ -63,7 +63,7 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) { // Inicializa las variables desde un fichero. Si no se pasa fichero, el // llamante (p.ej. Resource::preloadAll) usará loadFromBytes después — // y ese método ya llama a setSelectorItemColors() y reset() al final. - if (file != "") { + if (!file.empty()) { load(file); setSelectorItemColors(); reset(); @@ -99,24 +99,24 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) { while (std::getline(file, line)) { if (line == "[item]") { - item_t item; - item.label = ""; - item.hPaddingDown = 1; - item.selectable = true; - item.greyed = false; - item.linkedDown = false; - item.visible = true; - item.line = false; + item_t newItem; + newItem.label = ""; + newItem.hPaddingDown = 1; + newItem.selectable = true; + newItem.greyed = false; + newItem.linkedDown = false; + newItem.visible = true; + newItem.line = false; do { std::getline(file, line); int pos = line.find("="); - if (!setItem(&item, line.substr(0, pos), line.substr(pos + 1, line.length()))) { + if (!setItem(&newItem, line.substr(0, pos), line.substr(pos + 1, line.length()))) { success = false; } } while (line != "[/item]"); - addItem(item); + addItem(newItem); } else { int pos = line.find("="); if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) { @@ -137,7 +137,7 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) { } // Carga la configuración del menu desde un archivo de texto -bool Menu::load(std::string file_path) { +bool Menu::load(const std::string &file_path) { const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1); std::ifstream file(file_path); if (!file.good()) { @@ -158,7 +158,7 @@ bool Menu::loadFromBytes(const std::vector &bytes, const std::string &n } // Asigna variables a partir de dos cadenas -bool Menu::setItem(item_t *item, std::string var, std::string value) { +bool Menu::setItem(item_t *item, const std::string &var, const std::string &value) { // Indicador de éxito en la asignación bool success = true; @@ -201,7 +201,7 @@ bool Menu::setItem(item_t *item, std::string var, std::string value) { } // Asigna variables a partir de dos cadenas -bool Menu::setVars(std::string var, std::string value) { +bool Menu::setVars(const std::string &var, const std::string &value) { // Indicador de éxito en la asignación bool success = true; @@ -319,7 +319,7 @@ bool Menu::setVars(std::string var, std::string value) { } // Carga los ficheros de audio -void Menu::loadAudioFile(std::string file, int sound) { +void Menu::loadAudioFile(const std::string &file, int sound) { switch (sound) { case SOUND_ACCEPT: soundAccept = JA_LoadSound(file.c_str()); @@ -339,7 +339,7 @@ void Menu::loadAudioFile(std::string file, int sound) { } // Obtiene el nombre del menu -std::string Menu::getName() { +const std::string &Menu::getName() const { return name; } @@ -430,14 +430,8 @@ void Menu::setSelectorPos(int index) { // Obtiene la anchura del elemento más ancho del menu int Menu::getWidestItem() { - int result = 0; - - // Obtenemos la anchura del item mas ancho - for (auto &i : item) { - result = std::max(result, i.rect.w); - } - - return result; + return std::accumulate(item.begin(), item.end(), 0, + [](int acc, const item_t &i) { return std::max(acc, i.rect.w); }); } // Deja el menu apuntando al primer elemento @@ -474,7 +468,7 @@ void Menu::reorganize() { } // Deja el menu apuntando al siguiente elemento -bool Menu::increaseSelectorIndex() { +void Menu::increaseSelectorIndex() { // Guarda el indice actual antes de modificarlo selector.previousIndex = selector.index; @@ -499,12 +493,10 @@ bool Menu::increaseSelectorIndex() { if (selector.incH != 0) { selector.resizing = true; } - - return true; } // Deja el menu apuntando al elemento anterior -bool Menu::decreaseSelectorIndex() { +void Menu::decreaseSelectorIndex() { // Guarda el indice actual antes de modificarlo selector.previousIndex = selector.index; @@ -538,8 +530,6 @@ bool Menu::decreaseSelectorIndex() { if (selector.incH != 0) { selector.resizing = true; } - - return true; } // Actualiza la logica del menu @@ -752,7 +742,7 @@ void Menu::addItem(item_t temp) { } // Cambia el texto de un item -void Menu::setItemCaption(int index, std::string text) { +void Menu::setItemCaption(int index, const std::string &text) { item[index].label = text; item[index].rect.w = this->text->lenght(item[index].label); item[index].rect.h = this->text->getCharacterSize(); @@ -767,18 +757,16 @@ void Menu::setDefaultActionWhenCancel(int item) { // Gestiona la entrada de teclado y mando durante el menu void Menu::checkInput() { if (Input::get()->checkInput(input_up, REPEAT_FALSE)) { - if (decreaseSelectorIndex()) { - if (soundMove) { - JA_PlaySound(soundMove); - } + decreaseSelectorIndex(); + if (soundMove) { + JA_PlaySound(soundMove); } } if (Input::get()->checkInput(input_down, REPEAT_FALSE)) { - if (increaseSelectorIndex()) { - if (soundMove) { - JA_PlaySound(soundMove); - } + increaseSelectorIndex(); + if (soundMove) { + JA_PlaySound(soundMove); } } @@ -804,12 +792,8 @@ int Menu::findWidth() { // Calcula el alto del menu int Menu::findHeight() { - int height = 0; - - // Obtenemos la altura de la suma de alturas de los items - for (auto &i : item) { - height += i.rect.h + i.hPaddingDown; - } + const int height = std::accumulate(item.begin(), item.end(), 0, + [](int acc, const item_t &i) { return acc + i.rect.h + i.hPaddingDown; }); return height - item.back().hPaddingDown; } @@ -853,7 +837,7 @@ int Menu::getSelectorHeight(int value) { } // Establece el nombre del menu -void Menu::setName(std::string name) { +void Menu::setName(const std::string &name) { this->name = name; } @@ -869,7 +853,7 @@ void Menu::setBackgroundType(int value) { } // Establece la fuente de texto que se utilizará -void Menu::setText(std::string font_png, std::string font_txt) { +void Menu::setText(const std::string &font_png, const std::string &font_txt) { if (!text) { text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer); } diff --git a/source/game/ui/menu.h b/source/game/ui/menu.h index 14707a0..75dc1ce 100644 --- a/source/game/ui/menu.h +++ b/source/game/ui/menu.h @@ -96,25 +96,25 @@ class Menu { std::string font_txt; // Carga la configuración del menu desde un archivo de texto - bool load(std::string file_path); + bool load(const std::string &file_path); // Parser compartido (recibe cualquier istream) bool parseFromStream(std::istream &file, const std::string &filename); // Asigna variables a partir de dos cadenas - bool setVars(std::string var, std::string value); + bool setVars(const std::string &var, const std::string &value); // Asigna variables a partir de dos cadenas - bool setItem(item_t *item, std::string var, std::string value); + bool setItem(item_t *item, const std::string &var, const std::string &value); // Actualiza el menu para recolocarlo correctamente y establecer el tamaño void reorganize(); // Deja el menu apuntando al siguiente elemento - bool increaseSelectorIndex(); + void increaseSelectorIndex(); // Deja el menu apuntando al elemento anterior - bool decreaseSelectorIndex(); + void decreaseSelectorIndex(); // Actualiza la posicion y el estado del selector void updateSelector(); @@ -142,7 +142,7 @@ class Menu { public: // Constructor - Menu(SDL_Renderer *renderer, std::string file = ""); + explicit Menu(SDL_Renderer *renderer, const std::string &file = ""); // Destructor ~Menu(); @@ -151,10 +151,10 @@ class Menu { bool loadFromBytes(const std::vector &bytes, const std::string &nameForLogs = ""); // Carga los ficheros de audio - void loadAudioFile(std::string file, int sound); + void loadAudioFile(const std::string &file, int sound); // Obtiene el nombre del menu - std::string getName(); + const std::string &getName() const; // Obtiene el valor de la variable int getItemSelected(); @@ -193,7 +193,7 @@ class Menu { void addItem(item_t item); // Cambia el texto de un item - void setItemCaption(int index, std::string text); + void setItemCaption(int index, const std::string &text); // Establece el indice del item que se usará por defecto al cancelar el menu void setDefaultActionWhenCancel(int item); @@ -214,7 +214,7 @@ class Menu { void setVisible(int index, bool value); // Establece el nombre del menu - void setName(std::string name); + void setName(const std::string &name); // Establece la posición del menu void setPos(int x, int y); @@ -223,7 +223,7 @@ class Menu { void setBackgroundType(int value); // Establece la fuente de texto que se utilizará - void setText(std::string font_png, std::string font_txt); + void setText(const std::string &font_png, const std::string &font_txt); // Establece el rectangulo de fondo del menu void setRectSize(int w = 0, int h = 0); diff --git a/source/utils/utils.cpp b/source/utils/utils.cpp index 36ba3bd..7b2f8ff 100644 --- a/source/utils/utils.cpp +++ b/source/utils/utils.cpp @@ -1,8 +1,9 @@ #include "utils/utils.h" -#include // for abs, free, malloc - -#include // for round, abs +#include // for transform +#include // for tolower +#include // for round, abs +#include // for abs // Calcula el cuadrado de la distancia entre dos puntos double distanceSquared(int x1, int y1, int x2, int y2) { @@ -12,7 +13,7 @@ double distanceSquared(int x1, int y1, int x2, int y2) { } // Detector de colisiones entre dos circulos -bool checkCollision(circle_t &a, circle_t &b) { +bool checkCollision(const circle_t &a, const circle_t &b) { // Calcula el radio total al cuadrado int totalRadiusSquared = a.r + b.r; totalRadiusSquared = totalRadiusSquared * totalRadiusSquared; @@ -28,7 +29,7 @@ bool checkCollision(circle_t &a, circle_t &b) { } // Detector de colisiones entre un circulo y un rectangulo -bool checkCollision(circle_t &a, SDL_Rect &b) { +bool checkCollision(const circle_t &a, const SDL_Rect &b) { // Closest point on collision box int cX, cY; @@ -61,7 +62,7 @@ bool checkCollision(circle_t &a, SDL_Rect &b) { } // Detector de colisiones entre dos rectangulos -bool checkCollision(SDL_Rect &a, SDL_Rect &b) { +bool checkCollision(const SDL_Rect &a, const SDL_Rect &b) { // Calcula las caras del rectangulo a const int leftA = a.x; const int rightA = a.x + a.w; @@ -96,7 +97,7 @@ bool checkCollision(SDL_Rect &a, SDL_Rect &b) { } // Detector de colisiones entre un punto y un rectangulo -bool checkCollision(SDL_Point &p, SDL_Rect &r) { +bool checkCollision(const SDL_Point &p, const SDL_Rect &r) { // Comprueba si el punto está a la izquierda del rectangulo if (p.x < r.x) { return false; @@ -122,7 +123,7 @@ bool checkCollision(SDL_Point &p, SDL_Rect &r) { } // Detector de colisiones entre una linea horizontal y un rectangulo -bool checkCollision(h_line_t &l, SDL_Rect &r) { +bool checkCollision(const h_line_t &l, const SDL_Rect &r) { // Comprueba si la linea esta por encima del rectangulo if (l.y < r.y) { return false; @@ -148,7 +149,7 @@ bool checkCollision(h_line_t &l, SDL_Rect &r) { } // Detector de colisiones entre una linea vertical y un rectangulo -bool checkCollision(v_line_t &l, SDL_Rect &r) { +bool checkCollision(const v_line_t &l, const SDL_Rect &r) { // Comprueba si la linea esta por la izquierda del rectangulo if (l.x < r.x) { return false; @@ -174,7 +175,7 @@ bool checkCollision(v_line_t &l, SDL_Rect &r) { } // Detector de colisiones entre una linea horizontal y un punto -bool checkCollision(h_line_t &l, SDL_Point &p) { +bool checkCollision(const h_line_t &l, const SDL_Point &p) { // Comprueba si el punto esta sobre la linea if (p.y > l.y) { return false; @@ -200,7 +201,7 @@ bool checkCollision(h_line_t &l, SDL_Point &p) { } // Detector de colisiones entre dos lineas -SDL_Point checkCollision(line_t &l1, line_t &l2) { +SDL_Point checkCollision(const line_t &l1, const line_t &l2) { const float x1 = l1.x1; const float y1 = l1.y1; const float x2 = l1.x2; @@ -227,7 +228,7 @@ SDL_Point checkCollision(line_t &l1, line_t &l2) { } // Detector de colisiones entre dos lineas -SDL_Point checkCollision(d_line_t &l1, v_line_t &l2) { +SDL_Point checkCollision(const d_line_t &l1, const v_line_t &l2) { const float x1 = l1.x1; const float y1 = l1.y1; const float x2 = l1.x2; @@ -290,7 +291,7 @@ void normalizeLine(d_line_t &l) { } // Detector de colisiones entre un punto y una linea diagonal -bool checkCollision(SDL_Point &p, d_line_t &l) { +bool checkCollision(const SDL_Point &p, const d_line_t &l) { // Comprueba si el punto está en alineado con la linea if (abs(p.x - l.x1) != abs(p.y - l.y1)) { return false; @@ -330,7 +331,7 @@ bool checkCollision(SDL_Point &p, d_line_t &l) { } // Devuelve un color_t a partir de un string -color_t stringToColor(palette_e pal, std::string str) { +color_t stringToColor(palette_e pal, const std::string &str) { if (pal == p_zxspectrum) { if (str == "black") { return {0x00, 0x00, 0x00}; @@ -467,7 +468,7 @@ color_t stringToColor(palette_e pal, std::string str) { } // Convierte una cadena en un valor booleano -bool stringToBool(std::string str) { +bool stringToBool(const std::string &str) { if (str == "true") { return true; } else { @@ -485,15 +486,9 @@ std::string boolToString(bool value) { } // Convierte una cadena a minusculas -std::string toLower(std::string str) { - const char *original = str.c_str(); - char *lower = (char *)malloc(str.size() + 1); - for (int i = 0; i < (int)str.size(); ++i) { - char c = original[i]; - lower[i] = (c >= 65 && c <= 90) ? c + 32 : c; - } - lower[str.size()] = 0; - std::string nova(lower); - free(lower); - return nova; +std::string toLower(const std::string &str) { + std::string result; + result.reserve(str.size()); + std::transform(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return result; } \ No newline at end of file diff --git a/source/utils/utils.h b/source/utils/utils.h index a69d76d..38ceac9 100644 --- a/source/utils/utils.h +++ b/source/utils/utils.h @@ -86,46 +86,46 @@ struct input_t { double distanceSquared(int x1, int y1, int x2, int y2); // Detector de colisiones entre dos circulos -bool checkCollision(circle_t &a, circle_t &b); +bool checkCollision(const circle_t &a, const circle_t &b); // Detector de colisiones entre un circulo y un rectangulo -bool checkCollision(circle_t &a, SDL_Rect &b); +bool checkCollision(const circle_t &a, const SDL_Rect &b); // Detector de colisiones entre un dos rectangulos -bool checkCollision(SDL_Rect &a, SDL_Rect &b); +bool checkCollision(const SDL_Rect &a, const SDL_Rect &b); // Detector de colisiones entre un punto y un rectangulo -bool checkCollision(SDL_Point &p, SDL_Rect &r); +bool checkCollision(const SDL_Point &p, const SDL_Rect &r); // Detector de colisiones entre una linea horizontal y un rectangulo -bool checkCollision(h_line_t &l, SDL_Rect &r); +bool checkCollision(const h_line_t &l, const SDL_Rect &r); // Detector de colisiones entre una linea vertical y un rectangulo -bool checkCollision(v_line_t &l, SDL_Rect &r); +bool checkCollision(const v_line_t &l, const SDL_Rect &r); // Detector de colisiones entre una linea horizontal y un punto -bool checkCollision(h_line_t &l, SDL_Point &p); +bool checkCollision(const h_line_t &l, const SDL_Point &p); // Detector de colisiones entre dos lineas -SDL_Point checkCollision(line_t &l1, line_t &l2); +SDL_Point checkCollision(const line_t &l1, const line_t &l2); // Detector de colisiones entre dos lineas -SDL_Point checkCollision(d_line_t &l1, v_line_t &l2); +SDL_Point checkCollision(const d_line_t &l1, const v_line_t &l2); // Detector de colisiones entre un punto y una linea diagonal -bool checkCollision(SDL_Point &p, d_line_t &l); +bool checkCollision(const SDL_Point &p, const d_line_t &l); // Normaliza una linea diagonal void normalizeLine(d_line_t &l); // Devuelve un color_t a partir de un string -color_t stringToColor(palette_e pal, std::string str); +color_t stringToColor(palette_e pal, const std::string &str); // Convierte una cadena en un valor booleano -bool stringToBool(std::string str); +bool stringToBool(const std::string &str); // Convierte un valor booleano en una cadena std::string boolToString(bool value); // Convierte una cadena a minusculas -std::string toLower(std::string str); +std::string toLower(const std::string &str);