This commit is contained in:
2026-04-17 22:20:37 +02:00
parent 513eacf356
commit 20b9a95619
38 changed files with 310 additions and 622 deletions

View File

@@ -96,15 +96,15 @@ inline int JA_FeedMusicChunk(JA_Music_t* music) {
if (!music || !music->vorbis || !music->stream) return 0; if (!music || !music->vorbis || !music->stream) return 0;
short chunk[JA_MUSIC_CHUNK_SHORTS]; 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( const int samples_per_channel = stb_vorbis_get_samples_short_interleaved(
music->vorbis, music->vorbis,
channels, numChannels,
chunk, chunk,
JA_MUSIC_CHUNK_SHORTS); JA_MUSIC_CHUNK_SHORTS);
if (samples_per_channel <= 0) return 0; 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); SDL_PutAudioStreamData(music->stream, chunk, bytes);
return samples_per_channel; return samples_per_channel;
} }

View File

@@ -2,6 +2,7 @@
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <algorithm> // for any_of
#include <iostream> // for basic_ostream, operator<<, cout, basi... #include <iostream> // for basic_ostream, operator<<, cout, basi...
// Emscripten-only: SDL 3.4+ ja no casa el GUID dels mandos de Chrome Android // Emscripten-only: SDL 3.4+ ja no casa el GUID dels mandos de Chrome Android
@@ -57,10 +58,12 @@ auto Input::get() -> Input * {
} }
// Constructor // Constructor
Input::Input(std::string file) { Input::Input(const std::string &file)
// Fichero gamecontrollerdb.txt : numGamepads(0),
dbPath = file; dbPath(file),
verbose(true),
disabledUntil(d_notDisabled),
enabled(true) {
// Inicializa las variables // Inicializa las variables
keyBindings_t kb; keyBindings_t kb;
kb.scancode = 0; kb.scancode = 0;
@@ -71,10 +74,6 @@ Input::Input(std::string file) {
gcb.button = SDL_GAMEPAD_BUTTON_INVALID; gcb.button = SDL_GAMEPAD_BUTTON_INVALID;
gcb.active = false; gcb.active = false;
gameControllerBindings.resize(input_number_of_inputs, gcb); gameControllerBindings.resize(input_number_of_inputs, gcb);
numGamepads = 0;
verbose = true;
enabled = true;
} }
// Destructor // Destructor
@@ -311,11 +310,9 @@ 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) // Si el mando ya está registrado no hace nada (ej. evento retroactivo tras el scan inicial)
for (SDL_JoystickID existing : connectedControllerIds) { if (std::any_of(connectedControllerIds.begin(), connectedControllerIds.end(), [jid](SDL_JoystickID existing) { return existing == jid; })) {
if (existing == jid) {
return false; return false;
} }
}
installWebStandardMapping(jid); installWebStandardMapping(jid);
SDL_Gamepad *pad = SDL_OpenGamepad(jid); SDL_Gamepad *pad = SDL_OpenGamepad(jid);

View File

@@ -80,7 +80,7 @@ class Input {
std::string buildControllerName(SDL_Gamepad *pad, int padIndex); std::string buildControllerName(SDL_Gamepad *pad, int padIndex);
// Constructor privado (usar Input::init) // Constructor privado (usar Input::init)
Input(std::string file); explicit Input(const std::string &file);
// Instancia única // Instancia única
static Input *instance; static Input *instance;

View File

@@ -22,6 +22,8 @@ static animatedSprite_t parseAnimationStream(std::istream &file, Texture *textur
while (std::getline(file, line)) { while (std::getline(file, line)) {
if (line == "[animation]") { if (line == "[animation]") {
animation_t buffer; animation_t buffer;
buffer.speed = 0;
buffer.loop = -1;
buffer.counter = 0; buffer.counter = 0;
buffer.currentFrame = 0; buffer.currentFrame = 0;
buffer.completed = false; buffer.completed = false;
@@ -82,7 +84,7 @@ static animatedSprite_t parseAnimationStream(std::istream &file, Texture *textur
} }
// Carga la animación desde un fichero // 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); const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1);
std::ifstream file(filePath); std::ifstream file(filePath);
if (!file.good()) { if (!file.good()) {
@@ -109,42 +111,34 @@ animatedSprite_t loadAnimationFromMemory(Texture *texture, const std::vector<uin
} }
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, std::string file, std::vector<std::string> *buffer) { AnimatedSprite::AnimatedSprite(Texture *texture, SDL_Renderer *renderer, const std::string &file, std::vector<std::string> *buffer)
: currentAnimation(0) {
// Copia los punteros // Copia los punteros
setTexture(texture); setTexture(texture);
setRenderer(renderer); setRenderer(renderer);
// Carga las animaciones // Carga las animaciones
if (file != "") { if (!file.empty()) {
animatedSprite_t as = loadAnimationFromFile(texture, file); animatedSprite_t as = loadAnimationFromFile(texture, file);
// Copia los datos de las animaciones // Copia los datos de las animaciones
for (auto animation : as.animations) { animation.insert(animation.end(), as.animations.begin(), as.animations.end());
this->animation.push_back(animation);
}
} }
else if (buffer) { else if (buffer) {
loadFromVector(buffer); loadFromVector(buffer);
} }
// Inicializa variables
currentAnimation = 0;
} }
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation) { AnimatedSprite::AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation)
: currentAnimation(0) {
// Copia los punteros // Copia los punteros
setTexture(animation->texture); setTexture(animation->texture);
setRenderer(renderer); setRenderer(renderer);
// Inicializa variables
currentAnimation = 0;
// Copia los datos de las animaciones // Copia los datos de las animaciones
for (auto a : animation->animations) { this->animation.insert(this->animation.end(), animation->animations.begin(), animation->animations.end());
this->animation.push_back(a);
}
} }
// Destructor // Destructor
@@ -156,10 +150,10 @@ AnimatedSprite::~AnimatedSprite() {
} }
// Obtiene el indice de la animación a partir del nombre // 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; int index = -1;
for (auto a : animation) { for (const auto &a : animation) {
index++; index++;
if (a.name == name) { if (a.name == name) {
return index; return index;
@@ -222,12 +216,12 @@ void AnimatedSprite::setCurrentFrame(int num) {
} }
// Establece el valor del contador // 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; animation[getIndex(name)].counter = num;
} }
// Establece la velocidad de una animación // 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; 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 // 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; animation[getIndex(name)].loop = loop;
} }
@@ -247,7 +241,7 @@ void AnimatedSprite::setAnimationLoop(int index, int loop) {
} }
// Establece el valor de la variable // 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; animation[getIndex(name)].completed = value;
} }
@@ -262,7 +256,7 @@ bool AnimatedSprite::animationIsCompleted() {
} }
// Devuelve el rectangulo de una animación y frame concreto // 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]; return animation[getIndex(name)].frames[index];
} }
@@ -292,6 +286,8 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source) {
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") { if (line == "[animation]") {
animation_t buffer; animation_t buffer;
buffer.speed = 0;
buffer.loop = -1;
buffer.counter = 0; buffer.counter = 0;
buffer.currentFrame = 0; buffer.currentFrame = 0;
buffer.completed = false; buffer.completed = false;
@@ -391,7 +387,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source) {
} }
// Establece la animacion actual // Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(std::string name) { void AnimatedSprite::setCurrentAnimation(const std::string &name) {
const int newAnimation = getIndex(name); const int newAnimation = getIndex(name);
if (currentAnimation != newAnimation) { if (currentAnimation != newAnimation) {
currentAnimation = newAnimation; currentAnimation = newAnimation;

View File

@@ -25,7 +25,7 @@ struct animatedSprite_t {
}; };
// Carga la animación desde un fichero // 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 // Carga la animación desde bytes en memoria
animatedSprite_t loadAnimationFromMemory(Texture *texture, const std::vector<uint8_t> &bytes, const std::string &nameForLogs = "", bool verbose = false); animatedSprite_t loadAnimationFromMemory(Texture *texture, const std::vector<uint8_t> &bytes, const std::string &nameForLogs = "", bool verbose = false);
@@ -38,7 +38,7 @@ class AnimatedSprite : public MovingSprite {
public: public:
// Constructor // Constructor
AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr); explicit AnimatedSprite(Texture *texture = nullptr, SDL_Renderer *renderer = nullptr, const std::string &file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation); AnimatedSprite(SDL_Renderer *renderer, animatedSprite_t *animation);
// Destructor // Destructor
@@ -54,35 +54,35 @@ class AnimatedSprite : public MovingSprite {
void setCurrentFrame(int num); void setCurrentFrame(int num);
// Establece el valor del contador // 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 // 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); void setAnimationSpeed(int index, int speed);
// Establece el frame al que vuelve la animación al finalizar // 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); void setAnimationLoop(int index, int loop);
// Establece el valor de la variable // 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); void setAnimationCompleted(int index, bool value);
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool animationIsCompleted(); bool animationIsCompleted();
// Devuelve el rectangulo de una animación y frame concreto // 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); SDL_Rect getAnimationClip(int indexA = 0, Uint8 indexF = 0);
// Obtiene el indice de la animación a partir del nombre // 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 // Carga la animación desde un vector
bool loadFromVector(std::vector<std::string> *source); bool loadFromVector(std::vector<std::string> *source);
// Establece la animacion actual // Establece la animacion actual
void setCurrentAnimation(std::string name = "default"); void setCurrentAnimation(const std::string &name = "default");
void setCurrentAnimation(int index = 0); void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto // Actualiza las variables del objeto

View File

@@ -8,9 +8,8 @@
#include "game/defaults.hpp" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH #include "game/defaults.hpp" // for GAMECANVAS_HEIGHT, GAMECANVAS_WIDTH
// Constructor // Constructor
Fade::Fade(SDL_Renderer *renderer) { Fade::Fade(SDL_Renderer *renderer)
mRenderer = renderer; : mRenderer(renderer) {
mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT); mBackbuffer = SDL_CreateTexture(mRenderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, GAMECANVAS_WIDTH, GAMECANVAS_HEIGHT);
if (mBackbuffer != nullptr) { if (mBackbuffer != nullptr) {
SDL_SetTextureScaleMode(mBackbuffer, SDL_SCALEMODE_NEAREST); SDL_SetTextureScaleMode(mBackbuffer, SDL_SCALEMODE_NEAREST);
@@ -53,7 +52,6 @@ void Fade::render() {
int alpha = mCounter * 4; int alpha = mCounter * 4;
if (alpha >= 255) { if (alpha >= 255) {
alpha = 255;
mFullscreenDone = true; mFullscreenDone = true;
// Deja todos los buffers del mismo color // Deja todos los buffers del mismo color

View File

@@ -10,23 +10,23 @@ constexpr int FADE_RANDOM_SQUARE = 2;
// Clase Fade // Clase Fade
class Fade { class Fade {
private: private:
SDL_Renderer *mRenderer; // El renderizador de la ventana SDL_Renderer *mRenderer = nullptr; // El renderizador de la ventana
SDL_Texture *mBackbuffer; // Textura para usar como backbuffer SDL_Texture *mBackbuffer = nullptr; // Textura para usar como backbuffer
Uint8 mFadeType; // Tipo de fade a realizar Uint8 mFadeType = FADE_FULLSCREEN; // Tipo de fade a realizar
Uint16 mCounter; // Contador interno Uint16 mCounter = 0; // Contador interno
bool mEnabled; // Indica si el fade está activo bool mEnabled = false; // Indica si el fade está activo
bool mFinished; // Indica si ha terminado la transición bool mFinished = false; // Indica si ha terminado la transición
Uint8 mR, mG, mB; // Colores para el fade Uint8 mR = 0, mG = 0, mB = 0; // Colores para el fade
Uint8 mROriginal, mGOriginal, mBOriginal; // Colores originales para FADE_RANDOM_SQUARE Uint8 mROriginal = 0, mGOriginal = 0, mBOriginal = 0; // Colores originales para FADE_RANDOM_SQUARE
Uint32 mLastSquareTicks; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE) Uint32 mLastSquareTicks = 0; // Ticks del último cuadrado dibujado (FADE_RANDOM_SQUARE)
Uint16 mSquaresDrawn; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE) Uint16 mSquaresDrawn = 0; // Número de cuadrados dibujados (FADE_RANDOM_SQUARE)
bool mFullscreenDone; // Indica si el fade fullscreen ha terminado la fase de fundido 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 mRect1{}; // Rectangulo usado para crear los efectos de transición
SDL_Rect mRect2; // Rectangulo usado para crear los efectos de transición SDL_Rect mRect2{}; // Rectangulo usado para crear los efectos de transición
public: public:
// Constructor // Constructor
Fade(SDL_Renderer *renderer); explicit Fade(SDL_Renderer *renderer);
// Destructor // Destructor
~Fade(); ~Fade();

View File

@@ -3,53 +3,26 @@
#include "core/rendering/texture.h" // for Texture #include "core/rendering/texture.h" // for Texture
// Constructor // Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture, SDL_Renderer *renderer) { 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 : Sprite(0, 0, w, h, texture, renderer),
this->texture = texture; x(x),
this->renderer = renderer; y(y),
xPrev(x),
// Establece el alto y el ancho del sprite yPrev(y),
this->w = w; vx(velx),
this->h = h; vy(vely),
ax(accelx),
// Establece la posición X,Y del sprite ay(accely),
this->x = x; zoomW(1),
this->y = y; zoomH(1),
xPrev = x; angle(0.0),
yPrev = y; rotateEnabled(false),
rotateSpeed(0),
// Establece la velocidad X,Y del sprite rotateAmount(0.0),
vx = velx; counter(0),
vy = vely; center(nullptr),
currentFlip(SDL_FLIP_NONE) {
// 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;
};
// Reinicia todas las variables // Reinicia todas las variables
void MovingSprite::clear() { void MovingSprite::clear() {

View File

@@ -33,7 +33,7 @@ class MovingSprite : public Sprite {
public: public:
// Constructor // 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 // Mueve el sprite
void move(); void move();

View File

@@ -77,7 +77,8 @@ auto Screen::get() -> Screen * {
} }
// Constructor // Constructor
Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) { Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
: borderColor{0x00, 0x00, 0x00} {
// Inicializa variables // Inicializa variables
this->window = window; this->window = window;
this->renderer = renderer; this->renderer = renderer;
@@ -85,9 +86,6 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer) {
gameCanvasWidth = GAMECANVAS_WIDTH; gameCanvasWidth = GAMECANVAS_WIDTH;
gameCanvasHeight = GAMECANVAS_HEIGHT; 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) // Establece el modo de video (fullscreen/ventana + logical presentation)
// ANTES de crear la textura — SDL3 GPU necesita la 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. // del renderer ya aplicada al swapchain quan es reclama la ventana per a GPU.

View File

@@ -3,48 +3,26 @@
#include "core/rendering/texture.h" // for Texture #include "core/rendering/texture.h" // for Texture
// Constructor // Constructor
Sprite::Sprite(int x, int y, int w, int h, Texture *texture, SDL_Renderer *renderer) { Sprite::Sprite(int x, int y, int w, int h, Texture *texture, SDL_Renderer *renderer)
// Establece la posición X,Y del sprite : x(x),
this->x = x; y(y),
this->y = y; w(w),
h(h),
// Establece el alto y el ancho del sprite renderer(renderer),
this->w = w; texture(texture),
this->h = h; spriteClip{0, 0, w, h},
enabled(true) {
// 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) { Sprite::Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer)
// Establece la posición X,Y del sprite : x(rect.x),
x = rect.x; y(rect.y),
y = rect.y; w(rect.w),
h(rect.h),
// Establece el alto y el ancho del sprite renderer(renderer),
w = rect.w; texture(texture),
h = rect.h; spriteClip{0, 0, rect.w, rect.h},
enabled(true) {
// 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;
} }
// Destructor // Destructor

View File

@@ -19,7 +19,7 @@ class Sprite {
public: public:
// Constructor // 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); Sprite(SDL_Rect rect, Texture *texture, SDL_Renderer *renderer);
// Destructor // Destructor

View File

@@ -39,8 +39,10 @@ static void computeTextFileOffsets(textFile_t &tf) {
} }
// Llena una estructuta textFile_t desde un fichero // 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; textFile_t tf;
tf.boxWidth = 0;
tf.boxHeight = 0;
for (int i = 0; i < 128; ++i) { for (int i = 0; i < 128; ++i) {
tf.offset[i].x = 0; tf.offset[i].x = 0;
tf.offset[i].y = 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 // Llena una estructura textFile_t desde bytes en memoria
textFile_t LoadTextFileFromMemory(const std::vector<uint8_t> &bytes, bool verbose) { textFile_t LoadTextFileFromMemory(const std::vector<uint8_t> &bytes, bool verbose) {
textFile_t tf; textFile_t tf;
tf.boxWidth = 0;
tf.boxHeight = 0;
for (int i = 0; i < 128; ++i) { for (int i = 0; i < 128; ++i) {
tf.offset[i].x = 0; tf.offset[i].x = 0;
tf.offset[i].y = 0; tf.offset[i].y = 0;
@@ -83,7 +87,7 @@ textFile_t LoadTextFileFromMemory(const std::vector<uint8_t> &bytes, bool verbos
} }
// Constructor // 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 // Carga los offsets desde el fichero
textFile_t tf = LoadTextFile(textFile); textFile_t tf = LoadTextFile(textFile);
@@ -105,7 +109,7 @@ Text::Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer)
} }
// Constructor // 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 // Carga los offsets desde el fichero
textFile_t tf = LoadTextFile(textFile); textFile_t tf = LoadTextFile(textFile);
@@ -172,7 +176,7 @@ Text::~Text() {
} }
// Escribe texto en pantalla // Escribe texto en pantalla
void Text::write(int x, int y, std::string text, int kerning, int lenght) { void Text::write(int x, int y, const std::string &text, int kerning, int lenght) {
int shift = 0; int shift = 0;
if (lenght == -1) { 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 // 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); sprite->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
sprite->getTexture()->setColor(255, 255, 255); sprite->getTexture()->setColor(255, 255, 255);
} }
// Escribe el texto con sombra // 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); sprite->getTexture()->setColor(color.r, color.g, color.b);
write(x + shadowDistance, y + shadowDistance, text, kerning, lenght); write(x + shadowDistance, y + shadowDistance, text, kerning, lenght);
sprite->getTexture()->setColor(255, 255, 255); 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 // Escribe el texto centrado en un punto x
void Text::writeCentered(int x, int y, std::string text, int kerning, int lenght) { void Text::writeCentered(int x, int y, const std::string &text, int kerning, int lenght) {
x -= (Text::lenght(text, kerning) / 2); x -= (Text::lenght(text, kerning) / 2);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
} }
// Escribe texto con extras // Escribe texto con extras
void Text::writeDX(Uint8 flags, int x, int y, std::string text, int kerning, color_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 centered = ((flags & TXT_CENTER) == TXT_CENTER);
const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW); const bool shadowed = ((flags & TXT_SHADOW) == TXT_SHADOW);
const bool colored = ((flags & TXT_COLOR) == TXT_COLOR); 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 // 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; int shift = 0;
for (int i = 0; i < (int)text.length(); ++i) for (int i = 0; i < (int)text.length(); ++i)

View File

@@ -28,7 +28,7 @@ struct textFile_t {
}; };
// Llena una estructuta textFile_t desde un fichero // 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 // Llena una estructura textFile_t desde bytes en memoria
textFile_t LoadTextFileFromMemory(const std::vector<uint8_t> &bytes, bool verbose = false); textFile_t LoadTextFileFromMemory(const std::vector<uint8_t> &bytes, bool verbose = false);
@@ -48,8 +48,8 @@ class Text {
public: public:
// Constructor // Constructor
Text(std::string bitmapFile, std::string textFile, SDL_Renderer *renderer); Text(const std::string &bitmapFile, const std::string &textFile, SDL_Renderer *renderer);
Text(std::string textFile, Texture *texture, SDL_Renderer *renderer); Text(const std::string &textFile, Texture *texture, SDL_Renderer *renderer);
Text(textFile_t *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) // Constructor desde bytes en memoria: comparte ownership del texture (no lo libera)
@@ -58,23 +58,27 @@ class Text {
// Destructor // Destructor
~Text(); ~Text();
// No copiable (gestiona memoria dinámica)
Text(const Text &) = delete;
Text &operator=(const Text &) = delete;
// Escribe el texto en pantalla // Escribe el texto en pantalla
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); void write(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe el texto con colores // Escribe el texto con colores
void writeColored(int x, int y, std::string text, color_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 // 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 // Escribe el texto centrado en un punto x
void writeCentered(int x, int y, std::string text, int kerning = 1, int lenght = -1); void writeCentered(int x, int y, const std::string &text, int kerning = 1, int lenght = -1);
// Escribe texto con extras // Escribe texto con extras
void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, color_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 // 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 // Devuelve el valor de la variable
int getCharacterSize(); int getCharacterSize();

View File

@@ -15,30 +15,25 @@ void Texture::setGlobalScaleMode(SDL_ScaleMode mode) {
} }
// Constructor // Constructor
Texture::Texture(SDL_Renderer *renderer, std::string path, bool verbose) { Texture::Texture(SDL_Renderer *renderer, const std::string &path, bool verbose)
// Copia punteros : texture(nullptr),
this->renderer = renderer; renderer(renderer),
this->path = path; width(0),
height(0),
// Inicializa path(path) {
texture = nullptr;
width = 0;
height = 0;
// Carga el fichero en la textura // Carga el fichero en la textura
if (path != "") { if (!path.empty()) {
loadFromFile(path, renderer, verbose); loadFromFile(path, renderer, verbose);
} }
} }
// Constructor desde bytes // Constructor desde bytes
Texture::Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose) { Texture::Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose)
this->renderer = renderer; : texture(nullptr),
this->path = ""; renderer(renderer),
texture = nullptr; width(0),
width = 0; height(0),
height = 0; path("") {
if (!bytes.empty()) { if (!bytes.empty()) {
loadFromMemory(bytes.data(), bytes.size(), renderer, verbose); loadFromMemory(bytes.data(), bytes.size(), renderer, verbose);
} }
@@ -53,7 +48,7 @@ Texture::~Texture() {
// Helper: convierte píxeles RGBA decodificados por stbi en SDL_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) { 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; 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<void *>(data), pitch);
if (loadedSurface == nullptr) { if (loadedSurface == nullptr) {
return nullptr; return nullptr;
} }
@@ -68,7 +63,7 @@ static SDL_Texture *createTextureFromPixels(SDL_Renderer *renderer, unsigned cha
} }
// Carga una imagen desde un fichero // 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); const std::string filename = path.substr(path.find_last_of("\\/") + 1);
int req_format = STBI_rgb_alpha; int req_format = STBI_rgb_alpha;
int w, h, orig_format; int w, h, orig_format;

View File

@@ -24,7 +24,7 @@ class Texture {
static void setGlobalScaleMode(SDL_ScaleMode mode); static void setGlobalScaleMode(SDL_ScaleMode mode);
// Constructor // 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) // Constructor desde bytes (PNG en memoria)
Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose = false); Texture(SDL_Renderer *renderer, const std::vector<uint8_t> &bytes, bool verbose = false);
@@ -33,7 +33,7 @@ class Texture {
~Texture(); ~Texture();
// Carga una imagen desde un fichero // 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 // Carga una imagen desde bytes en memoria
bool loadFromMemory(const uint8_t *data, size_t size, SDL_Renderer *renderer, bool verbose = false); bool loadFromMemory(const uint8_t *data, size_t size, SDL_Renderer *renderer, bool verbose = false);

View File

@@ -3,23 +3,20 @@
#include "core/rendering/text.h" // for Text #include "core/rendering/text.h" // for Text
// Constructor // Constructor
Writer::Writer(Text *text) { Writer::Writer(Text *text)
// Copia los punteros : text(text),
this->text = text; posX(0),
posY(0),
// Inicializa variables kerning(0),
posX = 0; caption(""),
posY = 0; speed(0),
kerning = 0; writingCounter(0),
caption = ""; index(0),
speed = 0; lenght(0),
writingCounter = 0; completed(false),
index = 0; enabled(false),
lenght = 0; enabledCounter(0),
completed = false; finished(false) {
enabled = false;
enabledCounter = 0;
finished = false;
} }
// Actualiza el objeto // Actualiza el objeto
@@ -73,7 +70,7 @@ void Writer::setKerning(int value) {
} }
// Establece el valor de la variable // Establece el valor de la variable
void Writer::setCaption(std::string text) { void Writer::setCaption(const std::string &text) {
caption = text; caption = text;
lenght = text.length(); lenght = text.length();
} }

View File

@@ -25,7 +25,7 @@ class Writer {
public: public:
// Constructor // Constructor
Writer(Text *text); explicit Writer(Text *text);
// Actualiza el objeto // Actualiza el objeto
void update(); void update();
@@ -43,7 +43,7 @@ class Writer {
void setKerning(int value); void setKerning(int value);
// Establece el valor de la variable // Establece el valor de la variable
void setCaption(std::string text); void setCaption(const std::string &text);
// Establece el valor de la variable // Establece el valor de la variable
void setSpeed(int value); void setSpeed(int value);

View File

@@ -25,14 +25,14 @@ auto Asset::get() -> Asset * {
} }
// Constructor // Constructor
Asset::Asset(std::string executablePath) { Asset::Asset(const std::string &executablePath)
this->executablePath = executablePath.substr(0, executablePath.find_last_of("\\/")); : longestName(0),
longestName = 0; executablePath(executablePath.substr(0, executablePath.find_last_of("\\/"))),
verbose = true; verbose(true) {
} }
// Añade un elemento a la lista // 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; item_t temp;
temp.file = absolute ? file : executablePath + file; temp.file = absolute ? file : executablePath + file;
temp.type = type; 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 // Devuelve el fichero de un elemento de la lista a partir de una cadena
std::string Asset::get(std::string text) { std::string Asset::get(const std::string &text) {
for (auto f : fileList) { for (const auto &f : fileList) {
const size_t lastIndex = f.file.find_last_of("/") + 1; const size_t lastIndex = f.file.find_last_of("/") + 1;
const std::string file = f.file.substr(lastIndex, std::string::npos); 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 // Comprueba si hay ficheros de ese tipo
bool any = false; bool any = false;
for (auto f : fileList) { for (const auto &f : fileList) {
if ((f.required) && (f.type == type)) { if ((f.required) && (f.type == type)) {
any = true; any = true;
} }
@@ -88,7 +88,7 @@ bool Asset::check() {
std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl; 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)) { if ((f.required) && (f.type == type)) {
success &= checkFile(f.file); success &= checkFile(f.file);
} }
@@ -111,7 +111,7 @@ bool Asset::check() {
} }
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool Asset::checkFile(std::string path) { bool Asset::checkFile(const std::string &path) {
bool success = false; bool success = false;
std::string result = "ERROR"; std::string result = "ERROR";

View File

@@ -34,13 +34,13 @@ class Asset {
bool verbose; // Indica si ha de mostrar información por pantalla bool verbose; // Indica si ha de mostrar información por pantalla
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool checkFile(std::string executablePath); bool checkFile(const std::string &executablePath);
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string getTypeName(int type); std::string getTypeName(int type);
// Constructor privado (usar Asset::init) // Constructor privado (usar Asset::init)
Asset(std::string path); explicit Asset(const std::string &path);
// Instancia única // Instancia única
static Asset *instance; static Asset *instance;
@@ -52,10 +52,10 @@ class Asset {
static auto get() -> Asset *; // Obtiene el puntero a la instancia static auto get() -> Asset *; // Obtiene el puntero a la instancia
// Añade un elemento a la lista // 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 // 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 // Devuelve toda la lista de items registrados
const std::vector<item_t> &getAll() const { return fileList; } const std::vector<item_t> &getAll() const { return fileList; }

View File

@@ -30,7 +30,7 @@ class Resource {
const std::vector<uint8_t> &getDemoBytes() const { return demoBytes_; } const std::vector<uint8_t> &getDemoBytes() const { return demoBytes_; }
private: private:
Resource(SDL_Renderer *renderer); explicit Resource(SDL_Renderer *renderer);
~Resource(); ~Resource();
void preloadAll(); void preloadAll();

View File

@@ -5,6 +5,7 @@
#include <filesystem> #include <filesystem>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <numeric>
#include <utility> #include <utility>
const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCRS_RESOURCES__2026"; const std::string ResourcePack::DEFAULT_ENCRYPT_KEY = "CCRS_RESOURCES__2026";
@@ -17,11 +18,8 @@ ResourcePack::~ResourcePack() {
} }
uint32_t ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) { uint32_t ResourcePack::calculateChecksum(const std::vector<uint8_t>& data) {
uint32_t checksum = 0x12345678; return std::accumulate(data.begin(), data.end(), uint32_t(0x12345678),
for (unsigned char i : data) { [](uint32_t acc, uint8_t b) { return ((acc << 5) + acc) + b; });
checksum = ((checksum << 5) + checksum) + i;
}
return checksum;
} }
void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) { void ResourcePack::encryptData(std::vector<uint8_t>& data, const std::string& key) {

View File

@@ -261,15 +261,13 @@ Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 c
stoppedCounter = 0; stoppedCounter = 0;
blinking = false; blinking = false;
visible = true; visible = true;
invulnerable = true;
beingCreated = true;
creationCounter = creationtimer; creationCounter = creationtimer;
creationCounterIni = creationtimer; creationCounterIni = creationtimer;
popping = false; popping = false;
// Actualiza valores // Valores iniciales dependentes del timer
beingCreated = creationCounter == 0 ? false : true; beingCreated = creationCounter != 0;
invulnerable = beingCreated == false ? false : true; invulnerable = beingCreated;
counter = 0; counter = 0;
travelY = 1.0f; travelY = 1.0f;

View File

@@ -107,9 +107,6 @@ void Item::move() {
// Si el objeto se sale por la parte inferior // Si el objeto se sale por la parte inferior
if (posY + height > PLAY_AREA_BOTTOM) { if (posY + height > PLAY_AREA_BOTTOM) {
// Corrige
posY -= velY;
// Detiene el objeto // Detiene el objeto
velY = 0; velY = 0;
velX = 0; velX = 0;

View File

@@ -8,7 +8,7 @@
#include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT #include "game/defaults.hpp" // for PLAY_AREA_LEFT, PLAY_AREA_RIGHT
// Constructor // Constructor
Player::Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations) { Player::Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations) {
// Copia los punteros // Copia los punteros
this->renderer = renderer; this->renderer = renderer;
@@ -189,20 +189,13 @@ void Player::render() {
// Establece el estado del jugador cuando camina // Establece el estado del jugador cuando camina
void Player::setWalkingStatus(Uint8 status) { void Player::setWalkingStatus(Uint8 status) {
// Si cambiamos de estado, reiniciamos la animación
if (statusWalking != status) {
statusWalking = status; statusWalking = status;
// legsSprite->setCurrentFrame(0);
}
} }
// Establece el estado del jugador cuando dispara // Establece el estado del jugador cuando dispara
void Player::setFiringStatus(Uint8 status) { 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 // Establece la animación correspondiente al estado
void Player::setAnimation() { void Player::setAnimation() {
@@ -521,7 +514,7 @@ void Player::updatePowerUpHeadOffset() {
} }
// Pone las texturas del jugador // Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<Texture *> texture) { void Player::setPlayerTextures(const std::vector<Texture *> &texture) {
headSprite->setTexture(texture[0]); headSprite->setTexture(texture[0]);
bodySprite->setTexture(texture[1]); bodySprite->setTexture(texture[1]);
legsSprite->setTexture(texture[2]); legsSprite->setTexture(texture[2]);

View File

@@ -81,7 +81,7 @@ class Player {
public: public:
// Constructor // Constructor
Player(float x, int y, SDL_Renderer *renderer, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations); Player(float x, int y, SDL_Renderer *renderer, const std::vector<Texture *> &texture, const std::vector<std::vector<std::string> *> &animations);
// Destructor // Destructor
~Player(); ~Player();
@@ -96,7 +96,7 @@ class Player {
void render(); void render();
// Pone las texturas del jugador // Pone las texturas del jugador
void setPlayerTextures(std::vector<Texture *> texture); void setPlayerTextures(const std::vector<Texture *> &texture);
// Actua en consecuencia de la entrada recibida // Actua en consecuencia de la entrada recibida
void setInput(Uint8 input); void setInput(Uint8 input);

View File

@@ -4,6 +4,7 @@
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include <algorithm> // for max, min #include <algorithm> // for max, min
#include <numeric> // for accumulate
#include <fstream> // for basic_ifstream #include <fstream> // for basic_ifstream
#include <iostream> // for basic_ostream, char_traits, operator<< #include <iostream> // for basic_ostream, char_traits, operator<<
@@ -30,7 +31,8 @@
struct JA_Sound_t; struct JA_Sound_t;
// Constructor // 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 // Copia los punteros
this->renderer = renderer; this->renderer = renderer;
this->section = section; this->section = section;
@@ -43,7 +45,6 @@ Game::Game(int numPlayers, int currentStage, SDL_Renderer *renderer, bool demo,
#else #else
this->currentStage = currentStage; this->currentStage = currentStage;
#endif #endif
lastStageReached = currentStage;
if (numPlayers == 1) { // Si solo juega un jugador, permite jugar tanto con teclado como con mando if (numPlayers == 1) { // Si solo juega un jugador, permite jugar tanto con teclado como con mando
onePlayerControl = Options::inputs[0].deviceType; onePlayerControl = Options::inputs[0].deviceType;
Options::inputs[0].deviceType = INPUT_USE_ANY; 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 // #24 - Treinta enemigos BALLOON1. Del centro hacia los extremos. Juntos. Simetricos
j = 24; j = 24;
enemyFormation[j].numberOfEnemies = 30; enemyFormation[j].numberOfEnemies = 30;
incX = 0;
incTime = 5; incTime = 5;
for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) { for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) {
Uint8 half = enemyFormation[j].numberOfEnemies / 2; Uint8 half = enemyFormation[j].numberOfEnemies / 2;
@@ -981,7 +981,6 @@ void Game::initEnemyFormations() {
// #25 - Treinta enemigos BALLOON1. Del centro hacia adentro. Juntos. Simetricos // #25 - Treinta enemigos BALLOON1. Del centro hacia adentro. Juntos. Simetricos
j = 25; j = 25;
enemyFormation[j].numberOfEnemies = 30; enemyFormation[j].numberOfEnemies = 30;
incX = BALLOON_WIDTH_1 + 1;
incTime = 5; incTime = 5;
for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) { for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) {
Uint8 half = enemyFormation[j].numberOfEnemies / 2; Uint8 half = enemyFormation[j].numberOfEnemies / 2;
@@ -1486,12 +1485,12 @@ void Game::updateStage() {
// Actualiza el estado de muerte // Actualiza el estado de muerte
void Game::updateDeath() { void Game::updateDeath() {
// Comprueba si todos los jugadores estan muertos // Comprueba si todos los jugadores estan muertos
bool allPlayersAreDead = true; bool allDead = true;
for (auto player : players) { for (auto player : players) {
allPlayersAreDead &= (!player->isAlive()); allDead &= (!player->isAlive());
} }
if (allPlayersAreDead) { if (allDead) {
if (deathCounter > 0) { if (deathCounter > 0) {
deathCounter--; 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 // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void Game::updateBalloonSpeed() { void Game::updateBalloonSpeed() {
const float percent = (float)stage[currentStage].currentPower / (float)stage[currentStage].powerToComplete; const float percent = (float)stage[currentStage].currentPower / (float)stage[currentStage].powerToComplete;
@@ -1761,17 +1736,6 @@ void Game::destroyBalloon(Balloon *balloon) {
evaluateAndSetMenace(); 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 // Destruye todos los globos
void Game::destroyAllBalloons() { void Game::destroyAllBalloons() {
for (auto balloon : balloons) { 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 // Vacia el vector de globos
void Game::freeBalloons() { void Game::freeBalloons() {
if (balloons.empty() == false) { if (balloons.empty() == false) {
@@ -2090,7 +2039,7 @@ void Game::freeItems() {
} }
// Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto // 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); SmartSprite *ss = new SmartSprite(nullptr, renderer);
smartSprites.push_back(ss); smartSprites.push_back(ss);
@@ -2235,12 +2184,8 @@ void Game::updateDeathSequence() {
// Calcula y establece el valor de amenaza en funcion de los globos activos // Calcula y establece el valor de amenaza en funcion de los globos activos
void Game::evaluateAndSetMenace() { void Game::evaluateAndSetMenace() {
menaceCurrent = 0; menaceCurrent = std::accumulate(balloons.begin(), balloons.end(), Uint8(0),
for (auto balloon : balloons) { [](Uint8 acc, Balloon *b) { return b->isEnabled() ? acc + b->getMenace() : acc; });
if (balloon->isEnabled()) {
menaceCurrent += balloon->getMenace();
}
}
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -2685,19 +2630,19 @@ void Game::renderMessages() {
// STAGE NUMBER // STAGE NUMBER
if (stageBitmapCounter < STAGE_COUNTER) { if (stageBitmapCounter < STAGE_COUNTER) {
const int stageNum = stage[currentStage].number; const int stageNum = stage[currentStage].number;
std::string text; std::string stageText;
if (stageNum == 10) { // Ultima fase if (stageNum == 10) { // Ultima fase
text = Lang::get()->getText(79); stageText = Lang::get()->getText(79);
} else { // X fases restantes } 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 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 } else { // Escribe el texto de juego completado
text = Lang::get()->getText(50); stageText = Lang::get()->getText(50);
textNokiaBig2->writeDX(TXT_CENTER, PLAY_AREA_CENTER_X, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 1, shdwTxtColor); 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); 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 // Procesa un evento individual
void Game::handleEvent(SDL_Event *event) { void Game::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director // SDL_EVENT_QUIT ya lo maneja Director
if (event->type == SDL_EVENT_WINDOW_FOCUS_LOST) { 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 // Dibuja los elementos de la pantalla de game over
void Game::renderGameOverScreen() { void Game::renderGameOverScreen() {
// Prepara para empezar a dibujar en la textura de juego // 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 // Calcula el poder actual de los globos en pantalla
int Game::calculateScreenPower() { int Game::calculateScreenPower() {
int power = 0; return std::accumulate(balloons.begin(), balloons.end(), 0,
[](int acc, Balloon *b) { return b->isEnabled() ? acc + b->getPower() : acc; });
for (auto balloon : balloons) {
if (balloon->isEnabled()) {
power += balloon->getPower();
}
}
return power;
} }
// Inicializa las variables que contienen puntos de ruta para mover objetos // Inicializa las variables que contienen puntos de ruta para mover objetos
@@ -3234,28 +3155,6 @@ bool Game::allPlayersAreDead() {
return success; 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 // Elimina todos los objetos contenidos en vectores
void Game::deleteAllVectorObjects() { void Game::deleteAllVectorObjects() {
for (auto player : players) { for (auto player : players) {
@@ -3284,33 +3183,6 @@ void Game::deleteAllVectorObjects() {
smartSprites.clear(); 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 // Establece la máxima puntuación desde fichero o desde las puntuaciones online
void Game::setHiScore() { void Game::setHiScore() {
// Carga el fichero de puntos // Carga el fichero de puntos

View File

@@ -259,9 +259,6 @@ class Game {
// Dibuja el juego // Dibuja el juego
void render(); void render();
// Comprueba los eventos que hay en cola
void checkEvents();
// Inicializa las variables necesarias para la sección 'Game' // Inicializa las variables necesarias para la sección 'Game'
void init(); void init();
@@ -340,9 +337,6 @@ class Game {
// Incrementa la velocidad de los globos // Incrementa la velocidad de los globos
void incBalloonSpeed(); void incBalloonSpeed();
// Decrementa la velocidad de los globos
void decBalloonSpeed();
// Actualiza la velocidad de los globos en funcion del poder acumulado de la fase // Actualiza la velocidad de los globos en funcion del poder acumulado de la fase
void updateBalloonSpeed(); void updateBalloonSpeed();
@@ -352,9 +346,6 @@ class Game {
// Explosiona un globo. Lo destruye // Explosiona un globo. Lo destruye
void destroyBalloon(Balloon *balloon); void destroyBalloon(Balloon *balloon);
// Explosiona todos los globos
void popAllBalloons();
// Destruye todos los globos // Destruye todos los globos
void destroyAllBalloons(); void destroyAllBalloons();
@@ -364,9 +355,6 @@ class Game {
// Pone en marcha todos los globos // Pone en marcha todos los globos
void startAllBalloons(); void startAllBalloons();
// Obtiene el numero de globos activos
Uint8 countBalloons();
// Vacia el vector de globos // Vacia el vector de globos
void freeBalloons(); void freeBalloons();
@@ -407,7 +395,7 @@ class Game {
void freeItems(); void freeItems();
// Crea un objeto SmartSprite // 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 // Vacia el vector de smartsprites
void freeSmartSprites(); void freeSmartSprites();
@@ -505,9 +493,6 @@ class Game {
// Inicializa el estado de game over // Inicializa el estado de game over
void enterGameOverScreen(); void enterGameOverScreen();
// Comprueba los eventos de la pantalla de game over
void checkGameOverEvents();
// Indica si se puede crear una powerball // Indica si se puede crear una powerball
bool canPowerBallBeCreated(); bool canPowerBallBeCreated();
@@ -529,9 +514,6 @@ class Game {
// Elimina todos los objetos contenidos en vectores // Elimina todos los objetos contenidos en vectores
void deleteAllVectorObjects(); void deleteAllVectorObjects();
// Recarga las texturas
void reloadTextures();
// Establece la máxima puntuación desde fichero o desde las puntuaciones online // Establece la máxima puntuación desde fichero o desde las puntuaciones online
void setHiScore(); void setHiScore();
@@ -552,5 +534,5 @@ class Game {
bool hasFinished() const; bool hasFinished() const;
// Procesa un evento // Procesa un evento
void handleEvent(SDL_Event *event); void handleEvent(const SDL_Event *event);
}; };

View File

@@ -145,8 +145,8 @@ Intro::Intro(SDL_Renderer *renderer, section_t *section) {
texts[8]->setCaption(Lang::get()->getText(35)); texts[8]->setCaption(Lang::get()->getText(35));
texts[8]->setSpeed(16); texts[8]->setSpeed(16);
for (auto text : texts) { for (auto *t : texts) {
text->center(GAMECANVAS_CENTER_X); t->center(GAMECANVAS_CENTER_X);
} }
JA_PlayMusic(music, 0); 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 // Comprueba las entradas
void Intro::checkInput() { void Intro::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
@@ -352,8 +333,8 @@ void Intro::update() {
bitmap->update(); bitmap->update();
} }
for (auto text : texts) { for (auto *t : texts) {
text->update(); t->update();
} }
// Actualiza las escenas de la intro // Actualiza las escenas de la intro
@@ -374,8 +355,8 @@ void Intro::render() {
bitmap->render(); bitmap->render();
} }
for (auto text : texts) { for (auto *t : texts) {
text->render(); t->render();
} }
// Vuelca el contenido del renderizador en pantalla // Vuelca el contenido del renderizador en pantalla
@@ -398,6 +379,6 @@ void Intro::iterate() {
} }
// Procesa un evento individual // Procesa un evento individual
void Intro::handleEvent(SDL_Event *event) { void Intro::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director // SDL_EVENT_QUIT ya lo maneja Director
} }

View File

@@ -34,12 +34,6 @@ class Intro {
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void render(); void render();
// Carga los recursos
bool loadMedia();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas // Comprueba las entradas
void checkInput(); void checkInput();
@@ -60,5 +54,5 @@ class Intro {
void iterate(); void iterate();
// Procesa un evento // Procesa un evento
void handleEvent(SDL_Event *event); void handleEvent(const SDL_Event *event);
}; };

View File

@@ -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 // Comprueba las entradas
void Logo::checkInput() { void Logo::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
@@ -148,6 +134,6 @@ void Logo::iterate() {
} }
// Procesa un evento individual // Procesa un evento individual
void Logo::handleEvent(SDL_Event *event) { void Logo::handleEvent(const SDL_Event *event) {
// SDL_EVENT_QUIT ya lo maneja Director // SDL_EVENT_QUIT ya lo maneja Director
} }

View File

@@ -29,9 +29,6 @@ class Logo {
// Comprueba si ha terminado el logo // Comprueba si ha terminado el logo
void checkLogoEnd(); void checkLogoEnd();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas // Comprueba las entradas
void checkInput(); void checkInput();
@@ -52,5 +49,5 @@ class Logo {
void iterate(); void iterate();
// Procesa un evento // Procesa un evento
void handleEvent(SDL_Event *event); void handleEvent(const SDL_Event *event);
}; };

View File

@@ -112,16 +112,16 @@ void Title::init() {
// Pone valores por defecto a las opciones de control // Pone valores por defecto a las opciones de control
Options::inputs.clear(); Options::inputs.clear();
input_t i; input_t inp;
i.id = 0; inp.id = 0;
i.name = "KEYBOARD"; inp.name = "KEYBOARD";
i.deviceType = INPUT_USE_KEYBOARD; inp.deviceType = INPUT_USE_KEYBOARD;
Options::inputs.push_back(i); Options::inputs.push_back(inp);
i.id = 0; inp.id = 0;
i.name = "GAME CONTROLLER"; inp.name = "GAME CONTROLLER";
i.deviceType = INPUT_USE_GAMECONTROLLER; inp.deviceType = INPUT_USE_GAMECONTROLLER;
Options::inputs.push_back(i); Options::inputs.push_back(inp);
// Comprueba si hay mandos conectados // Comprueba si hay mandos conectados
checkInputDevices(); 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 // Comprueba las entradas
void Title::checkInput() { void Title::checkInput() {
#ifndef __EMSCRIPTEN__ #ifndef __EMSCRIPTEN__
@@ -915,7 +889,7 @@ void Title::iterate() {
} }
// Procesa un evento individual // 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 // Si hay un sub-estado activo, delega el evento
if (instructionsActive && instructions) { if (instructionsActive && instructions) {
// SDL_EVENT_QUIT ya lo maneja Director // SDL_EVENT_QUIT ya lo maneja Director

View File

@@ -107,9 +107,6 @@ class Title {
// Dibuja el objeto en pantalla // Dibuja el objeto en pantalla
void render(); void render();
// Comprueba los eventos
void checkEvents();
// Comprueba las entradas // Comprueba las entradas
void checkInput(); void checkInput();
@@ -157,5 +154,5 @@ class Title {
void iterate(); void iterate();
// Procesa un evento // Procesa un evento
void handleEvent(SDL_Event *event); void handleEvent(const SDL_Event *event);
}; };

View File

@@ -2,6 +2,7 @@
#include <algorithm> // for max, min #include <algorithm> // for max, min
#include <fstream> // for char_traits, basic_ifstream, basic_istream #include <fstream> // for char_traits, basic_ifstream, basic_istream
#include <numeric> // for accumulate
#include <sstream> // for basic_stringstream #include <sstream> // for basic_stringstream
#include "core/audio/jail_audio.hpp" // for JA_LoadSound, JA_PlaySound, JA_DeleteSound #include "core/audio/jail_audio.hpp" // for JA_LoadSound, JA_PlaySound, JA_DeleteSound
@@ -11,7 +12,10 @@
#include "core/resources/resource_helper.h" #include "core/resources/resource_helper.h"
// Constructor // 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 // Copia punteros
this->renderer = renderer; this->renderer = renderer;
@@ -21,7 +25,6 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) {
soundCancel = nullptr; soundCancel = nullptr;
// Inicializa variables // Inicializa variables
name = "";
selector.index = 0; selector.index = 0;
selector.previousIndex = 0; selector.previousIndex = 0;
itemSelected = MENU_NO_OPTION; itemSelected = MENU_NO_OPTION;
@@ -38,10 +41,7 @@ Menu::Menu(SDL_Renderer *renderer, std::string file) {
centerX = 0; centerX = 0;
centerY = 0; centerY = 0;
widestItem = 0; widestItem = 0;
colorGreyed = {128, 128, 128};
defaultActionWhenCancel = 0; defaultActionWhenCancel = 0;
font_png = "";
font_txt = "";
// Selector // Selector
selector.originY = 0; 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 // Inicializa las variables desde un fichero. Si no se pasa fichero, el
// llamante (p.ej. Resource::preloadAll) usará loadFromBytes después — // llamante (p.ej. Resource::preloadAll) usará loadFromBytes después —
// y ese método ya llama a setSelectorItemColors() y reset() al final. // y ese método ya llama a setSelectorItemColors() y reset() al final.
if (file != "") { if (!file.empty()) {
load(file); load(file);
setSelectorItemColors(); setSelectorItemColors();
reset(); reset();
@@ -99,24 +99,24 @@ bool Menu::parseFromStream(std::istream &file, const std::string &filename) {
while (std::getline(file, line)) { while (std::getline(file, line)) {
if (line == "[item]") { if (line == "[item]") {
item_t item; item_t newItem;
item.label = ""; newItem.label = "";
item.hPaddingDown = 1; newItem.hPaddingDown = 1;
item.selectable = true; newItem.selectable = true;
item.greyed = false; newItem.greyed = false;
item.linkedDown = false; newItem.linkedDown = false;
item.visible = true; newItem.visible = true;
item.line = false; newItem.line = false;
do { do {
std::getline(file, line); std::getline(file, line);
int pos = line.find("="); 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; success = false;
} }
} while (line != "[/item]"); } while (line != "[/item]");
addItem(item); addItem(newItem);
} else { } else {
int pos = line.find("="); int pos = line.find("=");
if (!setVars(line.substr(0, pos), line.substr(pos + 1, line.length()))) { 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 // 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); const std::string filename = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(file_path); std::ifstream file(file_path);
if (!file.good()) { if (!file.good()) {
@@ -158,7 +158,7 @@ bool Menu::loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &n
} }
// Asigna variables a partir de dos cadenas // 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 // Indicador de éxito en la asignación
bool success = true; 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 // 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 // Indicador de éxito en la asignación
bool success = true; bool success = true;
@@ -319,7 +319,7 @@ bool Menu::setVars(std::string var, std::string value) {
} }
// Carga los ficheros de audio // Carga los ficheros de audio
void Menu::loadAudioFile(std::string file, int sound) { void Menu::loadAudioFile(const std::string &file, int sound) {
switch (sound) { switch (sound) {
case SOUND_ACCEPT: case SOUND_ACCEPT:
soundAccept = JA_LoadSound(file.c_str()); soundAccept = JA_LoadSound(file.c_str());
@@ -339,7 +339,7 @@ void Menu::loadAudioFile(std::string file, int sound) {
} }
// Obtiene el nombre del menu // Obtiene el nombre del menu
std::string Menu::getName() { const std::string &Menu::getName() const {
return name; return name;
} }
@@ -430,14 +430,8 @@ void Menu::setSelectorPos(int index) {
// Obtiene la anchura del elemento más ancho del menu // Obtiene la anchura del elemento más ancho del menu
int Menu::getWidestItem() { int Menu::getWidestItem() {
int result = 0; return std::accumulate(item.begin(), item.end(), 0,
[](int acc, const item_t &i) { return std::max(acc, i.rect.w); });
// Obtenemos la anchura del item mas ancho
for (auto &i : item) {
result = std::max(result, i.rect.w);
}
return result;
} }
// Deja el menu apuntando al primer elemento // Deja el menu apuntando al primer elemento
@@ -474,7 +468,7 @@ void Menu::reorganize() {
} }
// Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
bool Menu::increaseSelectorIndex() { void Menu::increaseSelectorIndex() {
// Guarda el indice actual antes de modificarlo // Guarda el indice actual antes de modificarlo
selector.previousIndex = selector.index; selector.previousIndex = selector.index;
@@ -499,12 +493,10 @@ bool Menu::increaseSelectorIndex() {
if (selector.incH != 0) { if (selector.incH != 0) {
selector.resizing = true; selector.resizing = true;
} }
return true;
} }
// Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
bool Menu::decreaseSelectorIndex() { void Menu::decreaseSelectorIndex() {
// Guarda el indice actual antes de modificarlo // Guarda el indice actual antes de modificarlo
selector.previousIndex = selector.index; selector.previousIndex = selector.index;
@@ -538,8 +530,6 @@ bool Menu::decreaseSelectorIndex() {
if (selector.incH != 0) { if (selector.incH != 0) {
selector.resizing = true; selector.resizing = true;
} }
return true;
} }
// Actualiza la logica del menu // Actualiza la logica del menu
@@ -752,7 +742,7 @@ void Menu::addItem(item_t temp) {
} }
// Cambia el texto de un item // 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].label = text;
item[index].rect.w = this->text->lenght(item[index].label); item[index].rect.w = this->text->lenght(item[index].label);
item[index].rect.h = this->text->getCharacterSize(); item[index].rect.h = this->text->getCharacterSize();
@@ -767,20 +757,18 @@ void Menu::setDefaultActionWhenCancel(int item) {
// Gestiona la entrada de teclado y mando durante el menu // Gestiona la entrada de teclado y mando durante el menu
void Menu::checkInput() { void Menu::checkInput() {
if (Input::get()->checkInput(input_up, REPEAT_FALSE)) { if (Input::get()->checkInput(input_up, REPEAT_FALSE)) {
if (decreaseSelectorIndex()) { decreaseSelectorIndex();
if (soundMove) { if (soundMove) {
JA_PlaySound(soundMove); JA_PlaySound(soundMove);
} }
} }
}
if (Input::get()->checkInput(input_down, REPEAT_FALSE)) { if (Input::get()->checkInput(input_down, REPEAT_FALSE)) {
if (increaseSelectorIndex()) { increaseSelectorIndex();
if (soundMove) { if (soundMove) {
JA_PlaySound(soundMove); JA_PlaySound(soundMove);
} }
} }
}
if (Input::get()->checkInput(input_accept, REPEAT_FALSE)) { if (Input::get()->checkInput(input_accept, REPEAT_FALSE)) {
itemSelected = selector.index; itemSelected = selector.index;
@@ -804,12 +792,8 @@ int Menu::findWidth() {
// Calcula el alto del menu // Calcula el alto del menu
int Menu::findHeight() { int Menu::findHeight() {
int height = 0; const int height = std::accumulate(item.begin(), item.end(), 0,
[](int acc, const item_t &i) { return acc + i.rect.h + i.hPaddingDown; });
// Obtenemos la altura de la suma de alturas de los items
for (auto &i : item) {
height += i.rect.h + i.hPaddingDown;
}
return height - item.back().hPaddingDown; return height - item.back().hPaddingDown;
} }
@@ -853,7 +837,7 @@ int Menu::getSelectorHeight(int value) {
} }
// Establece el nombre del menu // Establece el nombre del menu
void Menu::setName(std::string name) { void Menu::setName(const std::string &name) {
this->name = name; this->name = name;
} }
@@ -869,7 +853,7 @@ void Menu::setBackgroundType(int value) {
} }
// Establece la fuente de texto que se utilizará // 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) { if (!text) {
text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer); text = new Text(Asset::get()->get(font_png), Asset::get()->get(font_txt), renderer);
} }

View File

@@ -96,25 +96,25 @@ class Menu {
std::string font_txt; std::string font_txt;
// Carga la configuración del menu desde un archivo de texto // 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) // Parser compartido (recibe cualquier istream)
bool parseFromStream(std::istream &file, const std::string &filename); bool parseFromStream(std::istream &file, const std::string &filename);
// Asigna variables a partir de dos cadenas // 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 // 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 // Actualiza el menu para recolocarlo correctamente y establecer el tamaño
void reorganize(); void reorganize();
// Deja el menu apuntando al siguiente elemento // Deja el menu apuntando al siguiente elemento
bool increaseSelectorIndex(); void increaseSelectorIndex();
// Deja el menu apuntando al elemento anterior // Deja el menu apuntando al elemento anterior
bool decreaseSelectorIndex(); void decreaseSelectorIndex();
// Actualiza la posicion y el estado del selector // Actualiza la posicion y el estado del selector
void updateSelector(); void updateSelector();
@@ -142,7 +142,7 @@ class Menu {
public: public:
// Constructor // Constructor
Menu(SDL_Renderer *renderer, std::string file = ""); explicit Menu(SDL_Renderer *renderer, const std::string &file = "");
// Destructor // Destructor
~Menu(); ~Menu();
@@ -151,10 +151,10 @@ class Menu {
bool loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs = ""); bool loadFromBytes(const std::vector<uint8_t> &bytes, const std::string &nameForLogs = "");
// Carga los ficheros de audio // 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 // Obtiene el nombre del menu
std::string getName(); const std::string &getName() const;
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getItemSelected(); int getItemSelected();
@@ -193,7 +193,7 @@ class Menu {
void addItem(item_t item); void addItem(item_t item);
// Cambia el texto de un 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 // Establece el indice del item que se usará por defecto al cancelar el menu
void setDefaultActionWhenCancel(int item); void setDefaultActionWhenCancel(int item);
@@ -214,7 +214,7 @@ class Menu {
void setVisible(int index, bool value); void setVisible(int index, bool value);
// Establece el nombre del menu // Establece el nombre del menu
void setName(std::string name); void setName(const std::string &name);
// Establece la posición del menu // Establece la posición del menu
void setPos(int x, int y); void setPos(int x, int y);
@@ -223,7 +223,7 @@ class Menu {
void setBackgroundType(int value); void setBackgroundType(int value);
// Establece la fuente de texto que se utilizará // 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 // Establece el rectangulo de fondo del menu
void setRectSize(int w = 0, int h = 0); void setRectSize(int w = 0, int h = 0);

View File

@@ -1,8 +1,9 @@
#include "utils/utils.h" #include "utils/utils.h"
#include <stdlib.h> // for abs, free, malloc #include <algorithm> // for transform
#include <cctype> // for tolower
#include <cmath> // for round, abs #include <cmath> // for round, abs
#include <cstdlib> // for abs
// Calcula el cuadrado de la distancia entre dos puntos // Calcula el cuadrado de la distancia entre dos puntos
double distanceSquared(int x1, int y1, int x2, int y2) { double distanceSquared(int x1, int y1, int x2, int y2) {
@@ -12,7 +13,7 @@ double distanceSquared(int x1, int y1, int x2, int y2) {
} }
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(circle_t &a, circle_t &b) { bool checkCollision(const circle_t &a, const circle_t &b) {
// Calcula el radio total al cuadrado // Calcula el radio total al cuadrado
int totalRadiusSquared = a.r + b.r; int totalRadiusSquared = a.r + b.r;
totalRadiusSquared = totalRadiusSquared * totalRadiusSquared; totalRadiusSquared = totalRadiusSquared * totalRadiusSquared;
@@ -28,7 +29,7 @@ bool checkCollision(circle_t &a, circle_t &b) {
} }
// Detector de colisiones entre un circulo y un rectangulo // 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 // Closest point on collision box
int cX, cY; int cX, cY;
@@ -61,7 +62,7 @@ bool checkCollision(circle_t &a, SDL_Rect &b) {
} }
// Detector de colisiones entre dos rectangulos // Detector de colisiones entre dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b) { bool checkCollision(const SDL_Rect &a, const SDL_Rect &b) {
// Calcula las caras del rectangulo a // Calcula las caras del rectangulo a
const int leftA = a.x; const int leftA = a.x;
const int rightA = a.x + a.w; 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 // 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 // Comprueba si el punto está a la izquierda del rectangulo
if (p.x < r.x) { if (p.x < r.x) {
return false; return false;
@@ -122,7 +123,7 @@ bool checkCollision(SDL_Point &p, SDL_Rect &r) {
} }
// Detector de colisiones entre una linea horizontal y un rectangulo // 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 // Comprueba si la linea esta por encima del rectangulo
if (l.y < r.y) { if (l.y < r.y) {
return false; 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 // 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 // Comprueba si la linea esta por la izquierda del rectangulo
if (l.x < r.x) { if (l.x < r.x) {
return false; 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 // 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 // Comprueba si el punto esta sobre la linea
if (p.y > l.y) { if (p.y > l.y) {
return false; return false;
@@ -200,7 +201,7 @@ bool checkCollision(h_line_t &l, SDL_Point &p) {
} }
// Detector de colisiones entre dos lineas // 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 x1 = l1.x1;
const float y1 = l1.y1; const float y1 = l1.y1;
const float x2 = l1.x2; const float x2 = l1.x2;
@@ -227,7 +228,7 @@ SDL_Point checkCollision(line_t &l1, line_t &l2) {
} }
// Detector de colisiones entre dos lineas // 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 x1 = l1.x1;
const float y1 = l1.y1; const float y1 = l1.y1;
const float x2 = l1.x2; 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 // 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 // Comprueba si el punto está en alineado con la linea
if (abs(p.x - l.x1) != abs(p.y - l.y1)) { if (abs(p.x - l.x1) != abs(p.y - l.y1)) {
return false; return false;
@@ -330,7 +331,7 @@ bool checkCollision(SDL_Point &p, d_line_t &l) {
} }
// Devuelve un color_t a partir de un string // 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 (pal == p_zxspectrum) {
if (str == "black") { if (str == "black") {
return {0x00, 0x00, 0x00}; return {0x00, 0x00, 0x00};
@@ -467,7 +468,7 @@ color_t stringToColor(palette_e pal, std::string str) {
} }
// Convierte una cadena en un valor booleano // Convierte una cadena en un valor booleano
bool stringToBool(std::string str) { bool stringToBool(const std::string &str) {
if (str == "true") { if (str == "true") {
return true; return true;
} else { } else {
@@ -485,15 +486,9 @@ std::string boolToString(bool value) {
} }
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str) { std::string toLower(const std::string &str) {
const char *original = str.c_str(); std::string result;
char *lower = (char *)malloc(str.size() + 1); result.reserve(str.size());
for (int i = 0; i < (int)str.size(); ++i) { std::transform(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
char c = original[i]; return result;
lower[i] = (c >= 65 && c <= 90) ? c + 32 : c;
}
lower[str.size()] = 0;
std::string nova(lower);
free(lower);
return nova;
} }

View File

@@ -86,46 +86,46 @@ struct input_t {
double distanceSquared(int x1, int y1, int x2, int y2); double distanceSquared(int x1, int y1, int x2, int y2);
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(circle_t &a, circle_t &b); bool checkCollision(const circle_t &a, const circle_t &b);
// Detector de colisiones entre un circulo y un rectangulo // 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 // Detector de colisiones entre un dos rectangulos
bool checkCollision(SDL_Rect &a, SDL_Rect &b); bool checkCollision(const SDL_Rect &a, const SDL_Rect &b);
// Detector de colisiones entre un punto y un rectangulo // Detector de colisiones entre un punto y un rectangulo
bool checkCollision(SDL_Point &p, SDL_Rect &r); bool checkCollision(const SDL_Point &p, const SDL_Rect &r);
// Detector de colisiones entre una linea horizontal y un rectangulo // 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 // 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 // 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 // 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 // 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 // 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 // Normaliza una linea diagonal
void normalizeLine(d_line_t &l); void normalizeLine(d_line_t &l);
// Devuelve un color_t a partir de un string // 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 // Convierte una cadena en un valor booleano
bool stringToBool(std::string str); bool stringToBool(const std::string &str);
// Convierte un valor booleano en una cadena // Convierte un valor booleano en una cadena
std::string boolToString(bool value); std::string boolToString(bool value);
// Convierte una cadena a minusculas // Convierte una cadena a minusculas
std::string toLower(std::string str); std::string toLower(const std::string &str);