Estandaritzant noms segons convencions

This commit is contained in:
2024-10-10 20:27:31 +02:00
parent 9e5f41644e
commit d6c3c89872
67 changed files with 1457 additions and 1504 deletions

View File

@@ -1,19 +1,19 @@
## GAME ## GAME
game.itemSize 20 game.item_size 20
game.width 320 game.width 320
game.height 240 game.height 240
game.playArea.rect.x 0 game.play_area.rect.x 0
game.playArea.rect.y 0 game.play_area.rect.y 0
game.playArea.rect.w 320 game.play_area.rect.w 320
game.playArea.rect.h 200 game.play_area.rect.h 200
## FADE ## FADE
fade.numSquaresWidth 160 fade.num_squares_width 160
fade.numSquaresHeight 120 fade.num_squares_height 120
fade.randomSquaresDelay 1 fade.random_squares_delay 1
fade.randomSquaresMult 500 fade.random_squares_mult 500
fade.postDuration 80 fade.post_duration 80
fade.venetianSize 16 fade.venetian_size 16
## SCOREBOARD ## SCOREBOARD
scoreboard.x 0 scoreboard.x 0
@@ -22,23 +22,23 @@ scoreboard.w 320
scoreboard.h 40 scoreboard.h 40
## TITLE ## TITLE
title.pressStartPosition 170 title.press_start_position 170
title.titleDuration 800 title.title_duration 800
title.arcadeEditionPosition 123 title.arcade_edition_position 123
title.titleCCPosition 80 title.title_c_c_position 80
## BACKGROUND ## BACKGROUND
background.attenuateColor.r 255 background.attenuate_color.r 255
background.attenuateColor.g 255 background.attenuate_color.g 255
background.attenuateColor.b 255 background.attenuate_color.b 255
background.attenuateAlpha 0 background.attenuate_alpha 0
## BALLOONS ## BALLOONS
balloon1.vel 2.75f balloon_1.vel 2.75f
balloon1.grav 0.09f balloon_1.grav 0.09f
balloon2.vel 3.70f balloon_2.vel 3.70f
balloon2.grav 0.10f balloon_2.grav 0.10f
balloon3.vel 4.70f balloon_3.vel 4.70f
balloon3.grav 0.10f balloon_3.grav 0.10f
balloon4.vel 5.45f balloon_4.vel 5.45f
balloon4.grav 0.10f balloon_4.grav 0.10f

View File

@@ -1,19 +1,19 @@
## GAME ## GAME
game.itemSize 20 game.item_size 20
game.width 320 game.width 320
game.height 256 game.height 256
game.playArea.rect.x 0 game.play_area.rect.x 0
game.playArea.rect.y 0 game.play_area.rect.y 0
game.playArea.rect.w 320 game.play_area.rect.w 320
game.playArea.rect.h 216 game.play_area.rect.h 216
## FADE ## FADE
fade.numSquaresWidth 160 fade.num_squares_width 160
fade.numSquaresHeight 128 fade.num_squares_height 128
fade.randomSquaresDelay 1 fade.random_squares_delay 1
fade.randomSquaresMult 500 fade.random_squares_mult 500
fade.postDuration 80 fade.post_duration 80
fade.venetianSize 16 fade.venetian_size 16
## SCOREBOARD ## SCOREBOARD
scoreboard.x 0 scoreboard.x 0
@@ -22,23 +22,23 @@ scoreboard.w 320
scoreboard.h 40 scoreboard.h 40
## TITLE ## TITLE
title.pressStartPosition 180 title.press_start_position 180
title.titleDuration 800 title.title_duration 800
title.arcadeEditionPosition 123 title.arcade_edition_position 123
title.titleCCPosition 80 title.title_c_c_position 80
## BACKGROUND ## BACKGROUND
background.attenuateColor.r 255 background.attenuate_color.r 255
background.attenuateColor.g 255 background.attenuate_color.g 255
background.attenuateColor.b 255 background.attenuate_color.b 255
background.attenuateAlpha 0 background.attenuate_alpha 0
## BALLOONS ## BALLOONS
balloon1.vel 2.75f balloon_1.vel 2.75f
balloon1.grav 0.09f balloon_1.grav 0.09f
balloon2.vel 3.70f balloon_2.vel 3.70f
balloon2.grav 0.10f balloon_2.grav 0.10f
balloon3.vel 4.70f balloon_3.vel 4.70f
balloon3.grav 0.10f balloon_3.grav 0.10f
balloon4.vel 5.45f balloon_4.vel 5.45f
balloon4.grav 0.10f balloon_4.grav 0.10f

View File

@@ -1,5 +1,5 @@
frameWidth=10 frame_width=10
frameHeight=10 frame_height=10
[animation] [animation]
name=orange name=orange

View File

@@ -1,5 +1,5 @@
frameWidth=16 frame_width=16
frameHeight=16 frame_height=16
[animation] [animation]
name=orange name=orange

View File

@@ -1,5 +1,5 @@
frameWidth=26 frame_width=26
frameHeight=26 frame_height=26
[animation] [animation]
name=orange name=orange

View File

@@ -1,5 +1,5 @@
frameWidth=48 frame_width=48
frameHeight=48 frame_height=48
[animation] [animation]
name=orange name=orange

View File

@@ -1,5 +1,5 @@
frameWidth=10 frame_width=10
frameHeight=10 frame_height=10
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=16 frame_width=16
frameHeight=16 frame_height=16
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=26 frame_width=26
frameHeight=26 frame_height=26
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=46 frame_width=46
frameHeight=46 frame_height=46
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=46 frame_width=46
frameHeight=46 frame_height=46
[animation] [animation]
name=powerball name=powerball

View File

@@ -1,5 +1,5 @@
frameWidth=20 frame_width=20
frameHeight=20 frame_height=20
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=20 frame_width=20
frameHeight=20 frame_height=20
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=28 frame_width=28
frameHeight=37 frame_height=37
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=20 frame_width=20
frameHeight=20 frame_height=20
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=20 frame_width=20
frameHeight=20 frame_height=20
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=20 frame_width=20
frameHeight=20 frame_height=20
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=30 frame_width=30
frameHeight=30 frame_height=30
[animation] [animation]
name=walk name=walk

View File

@@ -1,5 +1,5 @@
frameWidth=39 frame_width=39
frameHeight=44 frame_height=44
[animation] [animation]
name=default name=default

View File

@@ -1,5 +1,5 @@
frameWidth=16 frame_width=16
frameHeight=16 frame_height=16
[animation] [animation]
name=default name=default

View File

@@ -5,18 +5,18 @@
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Carga la animación desde un fichero // Carga la animación desde un fichero
animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath) AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string file_path)
{ {
// Inicializa variables // Inicializa variables
animatedSprite_t as; AnimatedFile af;
as.texture = texture; af.texture = texture;
auto framesPerRow = 0; auto frames_per_row = 0;
auto frameWidth = 0; auto frame_width = 0;
auto frameHeight = 0; auto frame_height = 0;
auto maxTiles = 0; auto max_tiles = 0;
const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::ifstream file(filePath); std::ifstream file(file_path);
std::string line; std::string line;
// El fichero se puede abrir // El fichero se puede abrir
@@ -24,7 +24,7 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Animation loaded: " << filename << std::endl; std::cout << "Animation loaded: " << file_name << std::endl;
#endif #endif
while (std::getline(file, line)) while (std::getline(file, line))
{ {
@@ -33,7 +33,7 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
{ {
Animation buffer; Animation buffer;
buffer.counter = 0; buffer.counter = 0;
buffer.currentFrame = 0; buffer.current_frame = 0;
buffer.completed = false; buffer.completed = false;
do do
@@ -66,13 +66,13 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
// Se introducen los valores separados por comas en un vector // Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length())); std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp; std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight}; SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ',')) while (getline(ss, tmp, ','))
{ {
// Comprueba que el tile no sea mayor que el maximo indice permitido // Comprueba que el tile no sea mayor que el maximo indice permitido
const auto numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp); const auto num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth; rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (numTile / framesPerRow) * frameHeight; rect.y = (num_tile / frames_per_row) * frame_height;
buffer.frames.push_back(rect); buffer.frames.push_back(rect);
} }
} }
@@ -80,14 +80,14 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
#endif #endif
} }
} }
} while (line != "[/animation]"); } while (line != "[/animation]");
// Añade la animación al vector de animaciones // Añade la animación al vector de animaciones
as.animations.push_back(buffer); af.animations.push_back(buffer);
} }
// En caso contrario se parsea el fichero para buscar las variables y los valores // En caso contrario se parsea el fichero para buscar las variables y los valores
@@ -99,39 +99,39 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (pos != (int)line.npos) if (pos != (int)line.npos)
{ {
if (line.substr(0, pos) == "framesPerRow") if (line.substr(0, pos) == "frames_per_row")
{ {
framesPerRow = std::stoi(line.substr(pos + 1, line.length())); frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frameWidth") else if (line.substr(0, pos) == "frame_width")
{ {
frameWidth = std::stoi(line.substr(pos + 1, line.length())); frame_width = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frameHeight") else if (line.substr(0, pos) == "frame_height")
{ {
frameHeight = std::stoi(line.substr(pos + 1, line.length())); frame_height = std::stoi(line.substr(pos + 1, line.length()));
} }
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl; std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
#endif #endif
} }
// Normaliza valores // Normaliza valores
if (framesPerRow == 0 && frameWidth > 0) if (frames_per_row == 0 && frame_width > 0)
{ {
framesPerRow = texture->getWidth() / frameWidth; frames_per_row = texture->getWidth() / frame_width;
} }
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) if (max_tiles == 0 && frame_width > 0 && frame_height > 0)
{ {
const auto w = texture->getWidth() / frameWidth; const auto w = texture->getWidth() / frame_width;
const auto h = texture->getHeight() / frameHeight; const auto h = texture->getHeight() / frame_height;
maxTiles = w * h; max_tiles = w * h;
} }
} }
} }
@@ -144,11 +144,11 @@ animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::st
else else
{ {
#ifdef VERBOSE #ifdef VERBOSE
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl;
#endif #endif
} }
return as; return af;
} }
// Constructor // Constructor
@@ -160,7 +160,7 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::string fil
// Carga las animaciones // Carga las animaciones
if (file != "") if (file != "")
{ {
animatedSprite_t as = loadAnimationFromFile(texture, file); AnimatedFile as = loadAnimationFromFile(texture, file);
// Copia los datos de las animaciones // Copia los datos de las animaciones
for (auto animation : as.animations) for (auto animation : as.animations)
@@ -175,17 +175,17 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::string fil
} }
// Inicializa variables // Inicializa variables
currentAnimation_ = 0; current_animation_ = 0;
} }
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(animatedSprite_t *animation) AnimatedSprite::AnimatedSprite(AnimatedFile *animation)
{ {
// Copia los punteros // Copia los punteros
setTexture(animation->texture); setTexture(animation->texture);
// Inicializa variables // Inicializa variables
currentAnimation_ = 0; current_animation_ = 0;
// Copia los datos de las animaciones // Copia los datos de las animaciones
for (auto a : animation->animations) for (auto a : animation->animations)
@@ -222,61 +222,61 @@ int AnimatedSprite::getIndex(std::string name)
// Calcula el frame correspondiente a la animación // Calcula el frame correspondiente a la animación
void AnimatedSprite::animate() void AnimatedSprite::animate()
{ {
if (!enabled_ || animations_[currentAnimation_].speed == 0) if (!enabled_ || animations_[current_animation_].speed == 0)
{ {
return; return;
} }
// Calcula el frame actual a partir del contador // Calcula el frame actual a partir del contador
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].counter / animations_[currentAnimation_].speed; animations_[current_animation_].current_frame = animations_[current_animation_].counter / animations_[current_animation_].speed;
// Si alcanza el final de la animación, reinicia el contador de la animación // Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame // en función de la variable loop y coloca el nuevo frame
if (animations_[currentAnimation_].currentFrame >= (int)animations_[currentAnimation_].frames.size()) if (animations_[current_animation_].current_frame >= (int)animations_[current_animation_].frames.size())
{ {
if (animations_[currentAnimation_].loop == -1) if (animations_[current_animation_].loop == -1)
{ // Si no hay loop, deja el último frame { // Si no hay loop, deja el último frame
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].frames.size(); animations_[current_animation_].current_frame = animations_[current_animation_].frames.size();
animations_[currentAnimation_].completed = true; animations_[current_animation_].completed = true;
} }
else else
{ // Si hay loop, vuelve al frame indicado { // Si hay loop, vuelve al frame indicado
animations_[currentAnimation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].loop; animations_[current_animation_].current_frame = animations_[current_animation_].loop;
} }
} }
// En caso contrario // En caso contrario
else else
{ {
// Escoge el frame correspondiente de la animación // Escoge el frame correspondiente de la animación
setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]); setSpriteClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
// Incrementa el contador de la animacion // Incrementa el contador de la animacion
animations_[currentAnimation_].counter++; animations_[current_animation_].counter++;
} }
} }
// Obtiene el número de frames de la animación actual // Obtiene el número de frames de la animación actual
int AnimatedSprite::getNumFrames() int AnimatedSprite::getNumFrames()
{ {
return (int)animations_[currentAnimation_].frames.size(); return (int)animations_[current_animation_].frames.size();
} }
// Establece el frame actual de la animación // Establece el frame actual de la animación
void AnimatedSprite::setCurrentFrame(int num) void AnimatedSprite::setCurrentFrame(int num)
{ {
// Descarta valores fuera de rango // Descarta valores fuera de rango
if (num >= (int)animations_[currentAnimation_].frames.size()) if (num >= (int)animations_[current_animation_].frames.size())
{ {
num = 0; num = 0;
} }
// Cambia el valor de la variable // Cambia el valor de la variable
animations_[currentAnimation_].currentFrame = num; animations_[current_animation_].current_frame = num;
animations_[currentAnimation_].counter = 0; animations_[current_animation_].counter = 0;
// Escoge el frame correspondiente de la animación // Escoge el frame correspondiente de la animación
setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]); setSpriteClip(animations_[current_animation_].frames[animations_[current_animation_].current_frame]);
} }
// Establece el valor del contador // Establece el valor del contador
@@ -324,7 +324,7 @@ void AnimatedSprite::setAnimationCompleted(int index, bool value)
// Comprueba si ha terminado la animación // Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted() bool AnimatedSprite::animationIsCompleted()
{ {
return animations_[currentAnimation_].completed; return animations_[current_animation_].completed;
} }
// Devuelve el rectangulo de una animación y frame concreto // Devuelve el rectangulo de una animación y frame concreto
@@ -343,10 +343,10 @@ SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF)
bool AnimatedSprite::loadFromVector(std::vector<std::string> *source) bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{ {
// Inicializa variables // Inicializa variables
auto framesPerRow = 0; auto frames_per_row = 0;
auto frameWidth = 0; auto frame_width = 0;
auto frameHeight = 0; auto frame_height = 0;
auto maxTiles = 0; auto max_tiles = 0;
// Indicador de éxito en el proceso // Indicador de éxito en el proceso
auto success = true; auto success = true;
@@ -364,7 +364,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{ {
Animation buffer; Animation buffer;
buffer.counter = 0; buffer.counter = 0;
buffer.currentFrame = 0; buffer.current_frame = 0;
buffer.completed = false; buffer.completed = false;
do do
@@ -399,13 +399,13 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
// Se introducen los valores separados por comas en un vector // Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length())); std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp; std::string tmp;
SDL_Rect rect = {0, 0, frameWidth, frameHeight}; SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ',')) while (getline(ss, tmp, ','))
{ {
// Comprueba que el tile no sea mayor que el maximo indice permitido // Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp); const int num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth; rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (numTile / framesPerRow) * frameHeight; rect.y = (num_tile / frames_per_row) * frame_height;
buffer.frames.push_back(rect); buffer.frames.push_back(rect);
} }
} }
@@ -433,19 +433,19 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (pos != (int)line.npos) if (pos != (int)line.npos)
{ {
if (line.substr(0, pos) == "framesPerRow") if (line.substr(0, pos) == "frames_per_row")
{ {
framesPerRow = std::stoi(line.substr(pos + 1, line.length())); frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frameWidth") else if (line.substr(0, pos) == "frame_width")
{ {
frameWidth = std::stoi(line.substr(pos + 1, line.length())); frame_width = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frameHeight") else if (line.substr(0, pos) == "frame_height")
{ {
frameHeight = std::stoi(line.substr(pos + 1, line.length())); frame_height = std::stoi(line.substr(pos + 1, line.length()));
} }
else else
@@ -457,16 +457,16 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
} }
// Normaliza valores // Normaliza valores
if (framesPerRow == 0 && frameWidth > 0) if (frames_per_row == 0 && frame_width > 0)
{ {
framesPerRow = texture_->getWidth() / frameWidth; frames_per_row = texture_->getWidth() / frame_width;
} }
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0) if (max_tiles == 0 && frame_width > 0 && frame_height > 0)
{ {
const int w = texture_->getWidth() / frameWidth; const int w = texture_->getWidth() / frame_width;
const int h = texture_->getHeight() / frameHeight; const int h = texture_->getHeight() / frame_height;
maxTiles = w * h; max_tiles = w * h;
} }
} }
} }
@@ -476,7 +476,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
} }
// Pone un valor por defecto // Pone un valor por defecto
setRect({0, 0, frameWidth, frameHeight}); setRect({0, 0, frame_width, frame_height});
return success; return success;
} }
@@ -484,26 +484,26 @@ 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(std::string name)
{ {
const auto newAnimation = getIndex(name); const auto new_animation = getIndex(name);
if (currentAnimation_ != newAnimation) if (current_animation_ != new_animation)
{ {
currentAnimation_ = newAnimation; current_animation_ = new_animation;
animations_[currentAnimation_].currentFrame = 0; animations_[current_animation_].current_frame = 0;
animations_[currentAnimation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[currentAnimation_].completed = false; animations_[current_animation_].completed = false;
} }
} }
// Establece la animacion actual // Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index) void AnimatedSprite::setCurrentAnimation(int index)
{ {
const auto newAnimation = index; const auto new_animation = index;
if (currentAnimation_ != newAnimation) if (current_animation_ != new_animation)
{ {
currentAnimation_ = newAnimation; current_animation_ = new_animation;
animations_[currentAnimation_].currentFrame = 0; animations_[current_animation_].current_frame = 0;
animations_[currentAnimation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[currentAnimation_].completed = false; animations_[current_animation_].completed = false;
} }
} }
@@ -535,7 +535,7 @@ void AnimatedSprite::setAnimationCounter(int value)
// Reinicia la animación // Reinicia la animación
void AnimatedSprite::resetAnimation() void AnimatedSprite::resetAnimation()
{ {
animations_[currentAnimation_].currentFrame = 0; animations_[current_animation_].current_frame = 0;
animations_[currentAnimation_].counter = 0; animations_[current_animation_].counter = 0;
animations_[currentAnimation_].completed = false; animations_[current_animation_].completed = false;
} }

View File

@@ -15,30 +15,30 @@ struct Animation
int speed; // Velocidad de la animación int speed; // Velocidad de la animación
int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva int loop; // Indica a que frame vuelve la animación al terminar. -1 para que no vuelva
bool completed; // Indica si ha finalizado la animación bool completed; // Indica si ha finalizado la animación
int currentFrame; // Frame actual int current_frame; // Frame actual
int counter; // Contador para las animaciones int counter; // Contador para las animaciones
}; };
struct animatedSprite_t struct AnimatedFile
{ {
std::vector<Animation> animations; // Vector con las diferentes animaciones std::vector<Animation> animations; // Vector con las diferentes animaciones
std::shared_ptr<Texture> texture; // Textura con los graficos para el sprite std::shared_ptr<Texture> texture; // Textura con los graficos para el sprite
}; };
// Carga la animación desde un fichero // Carga la animación desde un fichero
animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath); AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath);
class AnimatedSprite : public MovingSprite class AnimatedSprite : public MovingSprite
{ {
private: private:
// Variables // Variables
std::vector<Animation> animations_; // Vector con las diferentes animaciones std::vector<Animation> animations_; // Vector con las diferentes animaciones
int currentAnimation_; // Animacion activa int current_animation_; // Animacion activa
public: public:
// Constructor // Constructor
AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr); AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(animatedSprite_t *animation); AnimatedSprite(AnimatedFile *animation);
// Destructor // Destructor
~AnimatedSprite(); ~AnimatedSprite();

View File

@@ -1,16 +1,16 @@
#include "asset.h" #include "asset.h"
#include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_RWops #include <SDL2/SDL_rwops.h> // for SDL_RWFromFile, SDL_RWclose, SDL_RWops
#include <SDL2/SDL_stdinc.h> // for SDL_max #include <SDL2/SDL_stdinc.h> // for SDL_max
#include <stddef.h> // for size_t #include <stddef.h> // for size_t
#include <iostream> // for basic_ostream, operator<<, cout, endl #include <iostream> // for basic_ostream, operator<<, cout, endl
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Asset *Asset::asset = nullptr; Asset *Asset::asset = nullptr;
// [SINGLETON] Crearemos el objeto asset con esta función estática // [SINGLETON] Crearemos el objeto asset con esta función estática
void Asset::init(std::string executablePath) void Asset::init(std::string executable_path)
{ {
Asset::asset = new Asset(executablePath); Asset::asset = new Asset(executable_path);
} }
// [SINGLETON] Destruiremos el objeto asset con esta función estática // [SINGLETON] Destruiremos el objeto asset con esta función estática
@@ -26,37 +26,32 @@ Asset *Asset::get()
} }
// Constructor // Constructor
Asset::Asset(std::string executablePath) Asset::Asset(std::string executable_path)
{ {
this->executablePath = executablePath.substr(0, executablePath.find_last_of("\\/")); executable_path_ = executable_path.substr(0, executable_path.find_last_of("\\/"));
longestName = 0; longest_name_ = 0;
#ifdef VERBOSE
verbose = true;
#else
verbose = false;
#endif
} }
// 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(std::string file, AssetType type, bool required, bool absolute)
{ {
item_t temp; AssetItem ai;
temp.file = absolute ? file : executablePath + file; ai.file = absolute ? file : executable_path_ + file;
temp.type = type; ai.type = type;
temp.required = required; ai.required = required;
fileList.push_back(temp); file_list_.push_back(ai);
const std::string filename = file.substr(file.find_last_of("\\/") + 1); const std::string file_name = file.substr(file.find_last_of("\\/") + 1);
longestName = SDL_max(longestName, filename.size()); longest_name_ = SDL_max(longest_name_, file_name.size());
} }
// 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(std::string text) const
{ {
for (auto f : fileList) for (auto f : file_list_)
{ {
const size_t lastIndex = f.file.find_last_of("/") + 1; const size_t last_index = f.file.find_last_of("/") + 1;
const std::string file = f.file.substr(lastIndex, std::string::npos); const std::string file = f.file.substr(last_index, std::string::npos);
if (file == text) if (file == text)
{ {
@@ -64,35 +59,33 @@ std::string Asset::get(std::string text)
} }
} }
if (verbose) #ifdef VERBOSE
{ std::cout << "Warning: file " << text.c_str() << " not found" << std::endl;
std::cout << "Warning: file " << text.c_str() << " not found" << std::endl; #endif
}
return ""; return "";
} }
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
bool Asset::check() bool Asset::check() const
{ {
bool success = true; bool success = true;
if (verbose) #ifdef VERBOSE
{ std::cout << "\n** Checking files" << std::endl;
std::cout << "\n** Checking files" << std::endl;
std::cout << "Executable path is: " << executablePath << std::endl; std::cout << "Executable path is: " << executable_path_ << std::endl;
std::cout << "Sample filepath: " << fileList.back().file << std::endl; std::cout << "Sample filepath: " << file_list_.back().file << std::endl;
} #endif
// Comprueba la lista de ficheros clasificandolos por tipo // Comprueba la lista de ficheros clasificandolos por tipo
for (int type = 0; type < t_maxAssetType; ++type) for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type)
{ {
// 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 (auto f : file_list_)
{ {
if ((f.required) && (f.type == type)) if (f.required && f.type == static_cast<AssetType>(type))
{ {
any = true; any = true;
} }
@@ -101,14 +94,13 @@ bool Asset::check()
// Si hay ficheros de ese tipo, comprueba si existen // Si hay ficheros de ese tipo, comprueba si existen
if (any) if (any)
{ {
if (verbose) #ifdef VERBOSE
{ std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl;
std::cout << "\n>> " << getTypeName(type).c_str() << " FILES" << std::endl; #endif
}
for (auto f : fileList) for (auto f : file_list_)
{ {
if ((f.required) && (f.type == type)) if (f.required && f.type == static_cast<AssetType>(type))
{ {
success &= checkFile(f.file); success &= checkFile(f.file);
} }
@@ -116,32 +108,22 @@ bool Asset::check()
} }
} }
// Resultado // Resultado
if (verbose) #ifdef VERBOSE
{ std::cout << (success ? "\n** All files OK.\n" : "\n** A file is missing. Exiting.\n") << std::endl;
if (success) #endif
{
std::cout << "\n** All files OK.\n"
<< std::endl;
}
else
{
std::cout << "\n** A file is missing. Exiting.\n"
<< std::endl;
}
}
return success; return success;
} }
// Comprueba que existe un fichero // Comprueba que existe un fichero
bool Asset::checkFile(std::string path) bool Asset::checkFile(std::string path) const
{ {
bool success = false; bool success = false;
std::string result = "ERROR"; std::string result = "ERROR";
// Comprueba si existe el fichero // Comprueba si existe el fichero
const std::string filename = path.substr(path.find_last_of("\\/") + 1); const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
SDL_RWops *file = SDL_RWFromFile(path.c_str(), "rb"); SDL_RWops *file = SDL_RWFromFile(path.c_str(), "rb");
if (file != nullptr) if (file != nullptr)
@@ -151,57 +133,56 @@ bool Asset::checkFile(std::string path)
SDL_RWclose(file); SDL_RWclose(file);
} }
if (verbose) #ifdef VERBOSE
{ std::cout.setf(std::ios::left, std::ios::adjustfield);
std::cout.setf(std::ios::left, std::ios::adjustfield); std::cout << "Checking file: ";
std::cout << "Checking file: "; std::cout.width(longest_name_ + 2);
std::cout.width(longestName + 2); std::cout.fill('.');
std::cout.fill('.'); std::cout << file_name + " ";
std::cout << filename + " "; std::cout << " [" + result + "]" << std::endl;
std::cout << " [" + result + "]" << std::endl; #endif
}
return success; return success;
} }
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string Asset::getTypeName(int type) std::string Asset::getTypeName(int type) const
{ {
switch (type) switch (type)
{ {
case t_bitmap: case static_cast<int>(AssetType::BITMAP):
return "BITMAP"; return "BITMAP";
break; break;
case t_music: case static_cast<int>(AssetType::MUSIC):
return "MUSIC"; return "MUSIC";
break; break;
case t_sound: case static_cast<int>(AssetType::SOUND):
return "SOUND"; return "SOUND";
break; break;
case t_font: case static_cast<int>(AssetType::FONT):
return "FONT"; return "FONT";
break; break;
case t_lang: case static_cast<int>(AssetType::LANG):
return "LANG"; return "LANG";
break; break;
case t_data: case static_cast<int>(AssetType::DATA):
return "DATA"; return "DATA";
break; break;
case t_animation: case static_cast<int>(AssetType::ANIMATION):
return "ANIMATION"; return "ANIMATION";
break; break;
case t_palette: case static_cast<int>(AssetType::PALETTE):
return "PALETTE"; return "PALETTE";
break; break;
case t_item: case static_cast<int>(AssetType::ITEM):
return "ITEM"; return "ITEM";
break; break;
@@ -211,18 +192,12 @@ std::string Asset::getTypeName(int type)
} }
} }
// Establece si ha de mostrar texto por pantalla
void Asset::setVerbose(bool value)
{
verbose = value;
}
// Devuelve la lista de recursos de un tipo // Devuelve la lista de recursos de un tipo
std::vector<std::string> Asset::getListByType(assetType type) std::vector<std::string> Asset::getListByType(AssetType type) const
{ {
std::vector<std::string> list; std::vector<std::string> list;
for (auto f : fileList) for (auto f : file_list_)
{ {
if (f.type == type) if (f.type == type)
{ {

View File

@@ -3,18 +3,18 @@
#include <string> // for string, basic_string #include <string> // for string, basic_string
#include <vector> // for vector #include <vector> // for vector
enum assetType enum class AssetType
{ {
t_bitmap, BITMAP,
t_music, MUSIC,
t_sound, SOUND,
t_font, FONT,
t_lang, LANG,
t_data, DATA,
t_animation, ANIMATION,
t_palette, PALETTE,
t_item, ITEM,
t_maxAssetType MAX_ASSET_TYPE,
}; };
// Clase Asset // Clase Asset
@@ -25,25 +25,24 @@ private:
static Asset *asset; static Asset *asset;
// Estructura para definir un item // Estructura para definir un item
struct item_t struct AssetItem
{ {
std::string file; // Ruta del fichero desde la raiz del directorio std::string file; // Ruta del fichero desde la raiz del directorio
enum assetType type; // Indica el tipo de recurso enum AssetType type; // Indica el tipo de recurso
bool required; // Indica si es un fichero que debe de existir bool required; // Indica si es un fichero que debe de existir
// bool absolute; // Indica si la ruta que se ha proporcionado es una ruta absoluta // bool absolute; // Indica si la ruta que se ha proporcionado es una ruta absoluta
}; };
// Variables // Variables
int longestName; // Contiene la longitud del nombre de fichero mas largo int longest_name_; // Contiene la longitud del nombre de fichero mas largo
std::vector<item_t> fileList; // Listado con todas las rutas a los ficheros std::vector<AssetItem> file_list_; // Listado con todas las rutas a los ficheros
std::string executablePath; // Ruta al ejecutable std::string executable_path_; // Ruta al ejecutable
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(std::string executable_path) const;
// Devuelve el nombre del tipo de recurso // Devuelve el nombre del tipo de recurso
std::string getTypeName(int type); std::string getTypeName(int type) const;
// Constructor // Constructor
Asset(std::string path); Asset(std::string path);
@@ -62,17 +61,14 @@ public:
static Asset *get(); static Asset *get();
// 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(std::string file, 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(std::string text) const;
// Comprueba que existen todos los elementos // Comprueba que existen todos los elementos
bool check(); bool check() const;
// Establece si ha de mostrar texto por pantalla
void setVerbose(bool value);
// Devuelve la lista de recursos de un tipo // Devuelve la lista de recursos de un tipo
std::vector<std::string> getListByType(assetType type); std::vector<std::string> getListByType(AssetType type) const;
}; };

View File

@@ -1,108 +1,108 @@
#include "background.h" #include "background.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND #include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888 #include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <algorithm> // for max, min #include <algorithm> // for max, min
#include <string> // for basic_string #include <string> // for basic_string
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "param.h" // for param #include "param.h" // for param
// Constructor // Constructor
Background::Background(SDL_Renderer *renderer) Background::Background(SDL_Renderer *renderer)
: renderer(renderer) : renderer_(renderer)
{ {
// Carga las texturas // Carga las texturas
buildingsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_buildings.png")); buildings_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_buildings.png"));
topCloudsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds1.png")); top_clouds_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds1.png"));
bottomCloudsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds2.png")); bottom_clouds_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds2.png"));
grassTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_grass.png")); grass_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_grass.png"));
gradientsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_sky_colors.png")); gradients_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("game_sky_colors.png"));
// Inicializa variables // Inicializa variables
gradientNumber = 0; gradient_number_ = 0;
alpha = 0; alpha_ = 0;
cloudsSpeed = 0; clouds_speed_ = 0;
transition = 0; transition_ = 0;
counter = 0; counter_ = 0;
rect = {0, 0, gradientsTexture->getWidth() / 2, gradientsTexture->getHeight() / 2}; rect_ = {0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2};
srcRect = {0, 0, 320, 240}; src_rect_ = {0, 0, 320, 240};
dstRect = {0, 0, 320, 240}; dst_rect_ = {0, 0, 320, 240};
base = rect.h; base_ = rect_.h;
color = {param.background.attenuateColor.r, param.background.attenuateColor.g, param.background.attenuateColor.b}; color_ = {param.background.attenuateColor.r, param.background.attenuateColor.g, param.background.attenuateColor.b};
alphaColorText = alphaColorTextTemp = param.background.attenuateAlpha; alpha_color_text_ = alpha_color_text_temp_ = param.background.attenuateAlpha;
gradientRect[0] = {0, 0, rect.w, rect.h}; gradient_rect_[0] = {0, 0, rect_.w, rect_.h};
gradientRect[1] = {rect.w, 0, rect.w, rect.h}; gradient_rect_[1] = {rect_.w, 0, rect_.w, rect_.h};
gradientRect[2] = {0, rect.h, rect.w, rect.h}; gradient_rect_[2] = {0, rect_.h, rect_.w, rect_.h};
gradientRect[3] = {rect.w, rect.h, rect.w, rect.h}; gradient_rect_[3] = {rect_.w, rect_.h, rect_.w, rect_.h};
const int topCloudsTextureHeight = topCloudsTexture->getHeight() / 4; const int top_clouds_texture_height = top_clouds_texture_->getHeight() / 4;
const int bottomCloudsTextureHeight = bottomCloudsTexture->getHeight() / 4; const int bottom_clouds_texture_height = bottom_clouds_texture_->getHeight() / 4;
for (int i = 0; i < 4; ++i) for (int i = 0; i < 4; ++i)
{ {
topCloudsRect[i] = {0, i * topCloudsTextureHeight, topCloudsTexture->getWidth(), topCloudsTextureHeight}; top_clouds_rect_[i] = {0, i * top_clouds_texture_height, top_clouds_texture_->getWidth(), top_clouds_texture_height};
bottomCloudsRect[i] = {0, i * bottomCloudsTextureHeight, bottomCloudsTexture->getWidth(), bottomCloudsTextureHeight}; bottom_clouds_rect_[i] = {0, i * bottom_clouds_texture_height, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_height};
} }
// Crea los sprites // Crea los sprites
const int topClouds_y = base - 165; const int top_clouds_y = base_ - 165;
const int bottomClouds_y = base - 101; const int bottom_clouds_y = base_ - 101;
const float topCloudsSpeed = 0.1f; constexpr float top_clouds_speed = 0.1f;
const float bottomCloudsSpeed = 0.05f; constexpr float bottom_clouds_speed = 0.05f;
topCloudsSprite_A = std::make_unique<MovingSprite>(0, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); top_clouds_sprite_a_ = std::make_unique<MovingSprite>(0, top_clouds_y, rect_.w, top_clouds_texture_->getHeight(), -top_clouds_speed, 0.0f, 0.0f, 0.0f, top_clouds_texture_);
topCloudsSprite_B = std::make_unique<MovingSprite>(rect.w, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture); top_clouds_sprite_b_ = std::make_unique<MovingSprite>(rect_.w, top_clouds_y, rect_.w, top_clouds_texture_->getHeight(), -top_clouds_speed, 0.0f, 0.0f, 0.0f, top_clouds_texture_);
bottomCloudsSprite_A = std::make_unique<MovingSprite>(0, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(0, bottom_clouds_y, rect_.w, bottom_clouds_texture_->getHeight(), -bottom_clouds_speed, 0.0f, 0.0f, 0.0f, bottom_clouds_texture_);
bottomCloudsSprite_B = std::make_unique<MovingSprite>(rect.w, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture); bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(rect_.w, bottom_clouds_y, rect_.w, bottom_clouds_texture_->getHeight(), -bottom_clouds_speed, 0.0f, 0.0f, 0.0f, bottom_clouds_texture_);
buildingsSprite = std::make_unique<Sprite>(0, 0, buildingsTexture->getWidth(), buildingsTexture->getHeight(), buildingsTexture); buildings_sprite_ = std::make_unique<Sprite>(0, 0, buildings_texture_->getWidth(), buildings_texture_->getHeight(), buildings_texture_);
gradientSprite = std::make_unique<Sprite>(0, 0, rect.w, rect.h, gradientsTexture); gradient_sprite_ = std::make_unique<Sprite>(0, 0, rect_.w, rect_.h, gradients_texture_);
grassSprite = std::make_unique<Sprite>(0, 0, grassTexture->getWidth(), grassTexture->getHeight() / 2, grassTexture); grass_sprite_ = std::make_unique<Sprite>(0, 0, grass_texture_->getWidth(), grass_texture_->getHeight() / 2, grass_texture_);
// Inicializa objetos // Inicializa objetos
topCloudsSprite_A->setSpriteClip(0, 0, topCloudsTexture->getWidth(), topCloudsTexture->getHeight()); top_clouds_sprite_a_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
topCloudsSprite_B->setSpriteClip(0, 0, topCloudsTexture->getWidth(), topCloudsTexture->getHeight()); top_clouds_sprite_b_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
bottomCloudsSprite_A->setSpriteClip(0, 0, bottomCloudsTexture->getWidth(), bottomCloudsTexture->getHeight()); bottom_clouds_sprite_a_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
bottomCloudsSprite_B->setSpriteClip(0, 0, bottomCloudsTexture->getWidth(), bottomCloudsTexture->getHeight()); bottom_clouds_sprite_b_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
buildingsSprite->setPosY(base - buildingsSprite->getHeight()); buildings_sprite_->setPosY(base_ - buildings_sprite_->getHeight());
grassSprite->setPosY(base - grassSprite->getHeight()); grass_sprite_->setPosY(base_ - grass_sprite_->getHeight());
// Crea la textura para componer el fondo // Crea la textura para componer el fondo
canvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); canvas_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect_.w, rect_.h);
SDL_SetTextureBlendMode(canvas, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(canvas_, SDL_BLENDMODE_BLEND);
// Crea la textura para atenuar el fondo // Crea la textura para atenuar el fondo
colorTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect.w, rect.h); color_texture_ = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, rect_.w, rect_.h);
SDL_SetTextureBlendMode(colorTexture, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(color_texture_, SDL_BLENDMODE_BLEND);
setColor(color); setColor(color_);
SDL_SetTextureAlphaMod(colorTexture, alphaColorText); SDL_SetTextureAlphaMod(color_texture_, alpha_color_text_);
} }
// Destructor // Destructor
Background::~Background() Background::~Background()
{ {
SDL_DestroyTexture(canvas); SDL_DestroyTexture(canvas_);
SDL_DestroyTexture(colorTexture); SDL_DestroyTexture(color_texture_);
} }
// Actualiza la lógica del objeto // Actualiza la lógica del objeto
void Background::update() void Background::update()
{ {
// Actualiza el valor de alpha // Actualiza el valor de alpha_
updateAlphaColorText(); updateAlphaColorText();
// Actualiza las nubes // Actualiza las nubes
updateClouds(); updateClouds();
// Calcula el frame de la hierba // Calcula el frame de la hierba
grassSprite->setSpriteClip(0, (10 * (counter / 20 % 2)), 320, 10); grass_sprite_->setSpriteClip(0, (10 * (counter_ / 20 % 2)), 320, 10);
// Calcula el valor de alpha // Calcula el valor de alpha_
alpha = std::max((255 - (int)(255 * transition)), 0); alpha_ = std::max((255 - (int)(255 * transition_)), 0);
// Incrementa el contador // Incrementa el contador
counter++; counter_++;
fillCanvas(); fillCanvas();
} }
@@ -111,58 +111,58 @@ void Background::update()
void Background::renderGradient() void Background::renderGradient()
{ {
// Dibuja el gradiente 2 // Dibuja el gradiente 2
gradientsTexture->setAlpha(255); gradients_texture_->setAlpha(255);
gradientSprite->setSpriteClip(gradientRect[(gradientNumber + 1) % 4]); gradient_sprite_->setSpriteClip(gradient_rect_[(gradient_number_ + 1) % 4]);
gradientSprite->render(); gradient_sprite_->render();
// Dibuja el gradiente 1 con una opacidad cada vez menor // Dibuja el gradiente 1 con una opacidad cada vez menor
gradientsTexture->setAlpha(alpha); gradients_texture_->setAlpha(alpha_);
gradientSprite->setSpriteClip(gradientRect[gradientNumber]); gradient_sprite_->setSpriteClip(gradient_rect_[gradient_number_]);
gradientSprite->render(); gradient_sprite_->render();
} }
// Dibuja las nubes de arriba // Dibuja las nubes de arriba
void Background::renderTopClouds() void Background::renderTopClouds()
{ {
// Dibuja el primer conjunto de nubes // Dibuja el primer conjunto de nubes
topCloudsTexture->setAlpha(255); top_clouds_texture_->setAlpha(255);
topCloudsSprite_A->setSpriteClip(topCloudsRect[(gradientNumber + 1) % 4]); top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]);
topCloudsSprite_A->render(); top_clouds_sprite_a_->render();
topCloudsSprite_B->setSpriteClip(topCloudsRect[(gradientNumber + 1) % 4]); top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[(gradient_number_ + 1) % 4]);
topCloudsSprite_B->render(); top_clouds_sprite_b_->render();
// Dibuja el segundo conjunto de nubes // Dibuja el segundo conjunto de nubes
topCloudsTexture->setAlpha(alpha); top_clouds_texture_->setAlpha(alpha_);
topCloudsSprite_A->setSpriteClip(topCloudsRect[gradientNumber]); top_clouds_sprite_a_->setSpriteClip(top_clouds_rect_[gradient_number_]);
topCloudsSprite_A->render(); top_clouds_sprite_a_->render();
topCloudsSprite_B->setSpriteClip(topCloudsRect[gradientNumber]); top_clouds_sprite_b_->setSpriteClip(top_clouds_rect_[gradient_number_]);
topCloudsSprite_B->render(); top_clouds_sprite_b_->render();
} }
// Dibuja las nubes de abajo // Dibuja las nubes de abajo
void Background::renderBottomClouds() void Background::renderBottomClouds()
{ {
// Dibuja el primer conjunto de nubes // Dibuja el primer conjunto de nubes
bottomCloudsTexture->setAlpha(255); bottom_clouds_texture_->setAlpha(255);
bottomCloudsSprite_A->setSpriteClip(bottomCloudsRect[(gradientNumber + 1) % 4]); bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]);
bottomCloudsSprite_A->render(); bottom_clouds_sprite_a_->render();
bottomCloudsSprite_B->setSpriteClip(bottomCloudsRect[(gradientNumber + 1) % 4]); bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[(gradient_number_ + 1) % 4]);
bottomCloudsSprite_B->render(); bottom_clouds_sprite_b_->render();
// Dibuja el segundo conjunto de nubes // Dibuja el segundo conjunto de nubes
bottomCloudsTexture->setAlpha(alpha); bottom_clouds_texture_->setAlpha(alpha_);
bottomCloudsSprite_A->setSpriteClip(bottomCloudsRect[gradientNumber]); bottom_clouds_sprite_a_->setSpriteClip(bottom_clouds_rect_[gradient_number_]);
bottomCloudsSprite_A->render(); bottom_clouds_sprite_a_->render();
bottomCloudsSprite_B->setSpriteClip(bottomCloudsRect[gradientNumber]); bottom_clouds_sprite_b_->setSpriteClip(bottom_clouds_rect_[gradient_number_]);
bottomCloudsSprite_B->render(); bottom_clouds_sprite_b_->render();
} }
// Compone todos los elementos del fondo en la textura // Compone todos los elementos del fondo en la textura
void Background::fillCanvas() void Background::fillCanvas()
{ {
// Cambia el destino del renderizador // Cambia el destino del renderizador
SDL_Texture *temp = SDL_GetRenderTarget(renderer); auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer, canvas); SDL_SetRenderTarget(renderer_, canvas_);
// Dibuja el gradiente de fondo // Dibuja el gradiente de fondo
renderGradient(); renderGradient();
@@ -174,45 +174,45 @@ void Background::fillCanvas()
renderBottomClouds(); renderBottomClouds();
// Dibuja los edificios // Dibuja los edificios
buildingsSprite->render(); buildings_sprite_->render();
// Dibuja la hierba // Dibuja la hierba
grassSprite->render(); grass_sprite_->render();
// Deja el renderizador apuntando donde estaba // Deja el renderizador apuntando donde estaba
SDL_SetRenderTarget(renderer, temp); SDL_SetRenderTarget(renderer_, temp);
} }
// Dibuja el objeto // Dibuja el objeto
void Background::render() void Background::render()
{ {
// Fondo // Fondo
SDL_RenderCopy(renderer, canvas, &srcRect, &dstRect); SDL_RenderCopy(renderer_, canvas_, &src_rect_, &dst_rect_);
// Atenuación // Atenuación
SDL_RenderCopy(renderer, colorTexture, &srcRect, &dstRect); SDL_RenderCopy(renderer_, color_texture_, &src_rect_, &dst_rect_);
} }
// Vuelve a cargar las texturas // Vuelve a cargar las texturas
void Background::reloadTextures() void Background::reloadTextures()
{ {
buildingsTexture->reLoad(); buildings_texture_->reLoad();
topCloudsTexture->reLoad(); top_clouds_texture_->reLoad();
bottomCloudsTexture->reLoad(); bottom_clouds_texture_->reLoad();
grassTexture->reLoad(); grass_texture_->reLoad();
gradientsTexture->reLoad(); gradients_texture_->reLoad();
} }
// Ajusta el valor de la variable // Ajusta el valor de la variable
void Background::setCloudsSpeed(float value) void Background::setCloudsSpeed(float value)
{ {
cloudsSpeed = value; clouds_speed_ = value;
} }
// Ajusta el valor de la variable // Ajusta el valor de la variable
void Background::setGradientNumber(int value) void Background::setGradientNumber(int value)
{ {
gradientNumber = value % 4; gradient_number_ = value % 4;
} }
// Ajusta el valor de la variable // Ajusta el valor de la variable
@@ -220,73 +220,73 @@ void Background::setTransition(float value)
{ {
value = std::min(value, 1.0f); value = std::min(value, 1.0f);
value = std::max(value, 0.0f); value = std::max(value, 0.0f);
transition = value; transition_ = value;
} }
// Establece la posición del objeto // Establece la posición del objeto
void Background::setPos(SDL_Rect pos) void Background::setPos(SDL_Rect pos)
{ {
this->dstRect = pos; dst_rect_ = pos;
// Si cambian las medidas del destino, hay que cambiar las del origen para evitar deformar la imagen // Si cambian las medidas del destino, hay que cambiar las del origen para evitar deformar la imagen
this->srcRect.x = 0; src_rect_.x = 0;
this->srcRect.y = rect.h - pos.h; src_rect_.y = rect_.h - pos.h;
this->srcRect.w = pos.w; src_rect_.w = pos.w;
this->srcRect.h = pos.h; src_rect_.h = pos.h;
} }
// Ajusta el valor de la variable // Ajusta el valor de la variable
void Background::setSrcRect(SDL_Rect value) void Background::setSrcRect(SDL_Rect value)
{ {
srcRect = value; src_rect_ = value;
} }
// Ajusta el valor de la variable // Ajusta el valor de la variable
void Background::setDstRect(SDL_Rect value) void Background::setDstRect(SDL_Rect value)
{ {
dstRect = value; dst_rect_ = value;
} }
// Establece el color de atenuación // Establece el color_ de atenuación
void Background::setColor(color_t color) void Background::setColor(Color color)
{ {
this->color = color; color_ = color;
// Colorea la textura // Colorea la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer); auto temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer, colorTexture); SDL_SetRenderTarget(renderer_, color_texture_);
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 255); SDL_SetRenderDrawColor(renderer_, color_.r, color_.g, color_.b, 255);
SDL_RenderClear(renderer); SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer, temp); SDL_SetRenderTarget(renderer_, temp);
} }
// Establece la transparencia de la atenuación // Establece la transparencia de la atenuación
void Background::setAlpha(int alpha) void Background::setAlpha(int alpha)
{ {
// Evita que se asignen valores fuera de rango // Evita que se asignen valores fuera de rango
alpha = std::min(alpha, 255); alpha_ = std::min(alpha, 255);
alpha = std::max(alpha, 0); alpha_ = std::max(alpha, 0);
// Guarda el valor actual // Guarda el valor actual
alphaColorTextTemp = alphaColorText; alpha_color_text_temp_ = alpha_color_text_;
// Establece el nuevo valor // Establece el nuevo valor
alphaColorText = alpha; alpha_color_text_ = alpha_;
} }
// Actualiza el valor de alpha // Actualiza el valor de alpha_
void Background::updateAlphaColorText() void Background::updateAlphaColorText()
{ {
if (alphaColorText == alphaColorTextTemp) if (alpha_color_text_ == alpha_color_text_temp_)
{ {
return; return;
} }
else else
{ {
alphaColorText > alphaColorTextTemp ? alphaColorTextTemp++ : alphaColorTextTemp--; alpha_color_text_ > alpha_color_text_temp_ ? ++alpha_color_text_temp_ : --alpha_color_text_temp_;
SDL_SetTextureAlphaMod(colorTexture, alphaColorTextTemp); SDL_SetTextureAlphaMod(color_texture_, alpha_color_text_temp_);
} }
} }
@@ -294,35 +294,35 @@ void Background::updateAlphaColorText()
void Background::updateClouds() void Background::updateClouds()
{ {
// Aplica la velocidad calculada a las nubes // Aplica la velocidad calculada a las nubes
topCloudsSprite_A->setVelX(cloudsSpeed); top_clouds_sprite_a_->setVelX(clouds_speed_);
topCloudsSprite_B->setVelX(cloudsSpeed); top_clouds_sprite_b_->setVelX(clouds_speed_);
bottomCloudsSprite_A->setVelX(cloudsSpeed / 2); bottom_clouds_sprite_a_->setVelX(clouds_speed_ / 2);
bottomCloudsSprite_B->setVelX(cloudsSpeed / 2); bottom_clouds_sprite_b_->setVelX(clouds_speed_ / 2);
// Mueve las nubes // Mueve las nubes
topCloudsSprite_A->move(); top_clouds_sprite_a_->move();
topCloudsSprite_B->move(); top_clouds_sprite_b_->move();
bottomCloudsSprite_A->move(); bottom_clouds_sprite_a_->move();
bottomCloudsSprite_B->move(); bottom_clouds_sprite_b_->move();
// Calcula el offset de las nubes // Calcula el offset de las nubes
if (topCloudsSprite_A->getPosX() < -topCloudsSprite_A->getWidth()) if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth())
{ {
topCloudsSprite_A->setPosX(topCloudsSprite_A->getWidth()); top_clouds_sprite_a_->setPosX(top_clouds_sprite_a_->getWidth());
} }
if (topCloudsSprite_B->getPosX() < -topCloudsSprite_B->getWidth()) if (top_clouds_sprite_b_->getPosX() < -top_clouds_sprite_b_->getWidth())
{ {
topCloudsSprite_B->setPosX(topCloudsSprite_B->getWidth()); top_clouds_sprite_b_->setPosX(top_clouds_sprite_b_->getWidth());
} }
if (bottomCloudsSprite_A->getPosX() < -bottomCloudsSprite_A->getWidth()) if (bottom_clouds_sprite_a_->getPosX() < -bottom_clouds_sprite_a_->getWidth())
{ {
bottomCloudsSprite_A->setPosX(bottomCloudsSprite_A->getWidth()); bottom_clouds_sprite_a_->setPosX(bottom_clouds_sprite_a_->getWidth());
} }
if (bottomCloudsSprite_B->getPosX() < -bottomCloudsSprite_B->getWidth()) if (bottom_clouds_sprite_b_->getPosX() < -bottom_clouds_sprite_b_->getWidth())
{ {
bottomCloudsSprite_B->setPosX(bottomCloudsSprite_B->getWidth()); bottom_clouds_sprite_b_->setPosX(bottom_clouds_sprite_b_->getWidth());
} }
} }

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture #include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include "utils.h" // for color_t #include "utils.h" // for Color
#include "moving_sprite.h" #include "moving_sprite.h"
#include "sprite.h" #include "sprite.h"
#include "texture.h" #include "texture.h"
@@ -38,7 +38,7 @@
- setDstRecr(SDL_Rect value) - setDstRecr(SDL_Rect value)
Rectangulo de destino donde se mostrará el rectángulo antrior. Automaticamente modifica srcRect para coincidor en tamaño con el destino. Rectangulo de destino donde se mostrará el rectángulo antrior. Automaticamente modifica srcRect para coincidor en tamaño con el destino.
- setColor(color_t color) - setColor(Color color)
Establece el color de la textura de superposición Establece el color de la textura de superposición
- setAlpha(int alpha) - setAlpha(int alpha)
@@ -50,42 +50,42 @@ class Background
{ {
private: private:
// Objetos y punteros // Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> buildingsTexture; // Textura con los edificios de fondo std::shared_ptr<Texture> buildings_texture_; // Textura con los edificios de fondo
std::shared_ptr<Texture> topCloudsTexture; // Textura con las nubes de fondo std::shared_ptr<Texture> top_clouds_texture_; // Textura con las nubes de fondo
std::shared_ptr<Texture> bottomCloudsTexture; // Textura con las nubes de fondo std::shared_ptr<Texture> bottom_clouds_texture_; // Textura con las nubes de fondo
std::shared_ptr<Texture> grassTexture; // Textura con la hierba del suelo std::shared_ptr<Texture> grass_texture_; // Textura con la hierba del suelo
std::shared_ptr<Texture> gradientsTexture; // Textura con los diferentes colores de fondo del juego std::shared_ptr<Texture> gradients_texture_; // Textura con los diferentes colores de fondo del juego
std::unique_ptr<MovingSprite> topCloudsSprite_A; // Sprite para las nubes superiores std::unique_ptr<MovingSprite> top_clouds_sprite_a_; // Sprite para las nubes superiores
std::unique_ptr<MovingSprite> topCloudsSprite_B; // Sprite para las nubes superiores std::unique_ptr<MovingSprite> top_clouds_sprite_b_; // Sprite para las nubes superiores
std::unique_ptr<MovingSprite> bottomCloudsSprite_A; // Sprite para las nubes inferiores std::unique_ptr<MovingSprite> bottom_clouds_sprite_a_; // Sprite para las nubes inferiores
std::unique_ptr<MovingSprite> bottomCloudsSprite_B; // Sprite para las nubes inferiores std::unique_ptr<MovingSprite> bottom_clouds_sprite_b_; // Sprite para las nubes inferiores
std::unique_ptr<Sprite> buildingsSprite; // Sprite con los edificios de fondo std::unique_ptr<Sprite> buildings_sprite_; // Sprite con los edificios de fondo
std::unique_ptr<Sprite> gradientSprite; // Sprite con los graficos del degradado de color de fondo std::unique_ptr<Sprite> gradient_sprite_; // Sprite con los graficos del degradado de color de fondo
std::unique_ptr<Sprite> grassSprite; // Sprite para la hierba std::unique_ptr<Sprite> grass_sprite_; // Sprite para la hierba
SDL_Texture *canvas; // Textura para componer el fondo SDL_Texture *canvas_; // Textura para componer el fondo
SDL_Texture *colorTexture; // Textura para atenuar el fondo SDL_Texture *color_texture_; // Textura para atenuar el fondo
// Variables // Variables
SDL_Rect gradientRect[4]; // Vector con las coordenadas de los 4 degradados para el cielo SDL_Rect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo
SDL_Rect topCloudsRect[4]; // Vector con las coordenadas de los 4 nubes de arriba SDL_Rect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba
SDL_Rect bottomCloudsRect[4]; // Vector con las coordenadas de los 4 nubes de abajo SDL_Rect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo
int gradientNumber; // Indica el número de degradado de fondo que se va a dibujar int gradient_number_; // Indica el número de degradado de fondo que se va a dibujar
int alpha; // Transparencia entre los dos degradados int alpha_; // Transparencia entre los dos degradados
float cloudsSpeed; // Velocidad a la que se desplazan las nubes float clouds_speed_; // Velocidad a la que se desplazan las nubes
float transition; // Nivel de transición del fondo 0..1 float transition_; // Nivel de transición del fondo 0..1
int counter; // Contador interno int counter_; // Contador interno
SDL_Rect rect; // Tamaño del objeto fondo SDL_Rect rect_; // Tamaño del objeto fondo
SDL_Rect srcRect; // Parte del objeto fondo que se va a dibujará en pantalla SDL_Rect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla
SDL_Rect dstRect; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla SDL_Rect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla
int base; // Linea de fondo coincidente con el area inferior de la zona de juego int base_; // Linea de fondo coincidente con el area inferior de la zona de juego
color_t color; // Color para atenuar el fondo Color color_; // Color para atenuar el fondo
int alphaColorText; // Alpha para atenuar el fondo int alpha_color_text_; // Alpha para atenuar el fondo
int alphaColorTextTemp; // Valor temporal para hacer la transición de alpha int alpha_color_text_temp_; // Valor temporal para hacer la transición de alpha
// Dibuja el gradiente de fondo // Dibuja el gradiente de fondo
void renderGradient(); void renderGradient();
@@ -140,7 +140,7 @@ public:
void setDstRect(SDL_Rect value); void setDstRect(SDL_Rect value);
// Establece el color de atenuación // Establece el color de atenuación
void setColor(color_t color); void setColor(Color color);
// Establece la transparencia de la atenuación // Establece la transparencia de la atenuación
void setAlpha(int alpha); void setAlpha(int alpha);

File diff suppressed because it is too large Load Diff

View File

@@ -1,71 +1,71 @@
#pragma once #pragma once
#include <SDL2/SDL_stdinc.h> // for Uint8, Uint16, Uint32 #include <SDL2/SDL_stdinc.h> // for Uint8, Uint16, Uint32
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include <memory>
#include "utils.h" // for circle_t #include "utils.h" // for Circle
#include "animated_sprite.h" #include "animated_sprite.h"
#include "texture.h" #include "texture.h"
// Cantidad de elementos del vector con los valores de la deformación del globo al rebotar // Cantidad de elementos del vector con los valores de la deformación del globo al rebotar
constexpr int MAX_BOUNCE = 10; constexpr int MAX_BOUNCE = 10;
// Tipos de globo // Tipos de globo
constexpr int BALLOON_1 = 1; constexpr int BALLOON_1 = 1;
constexpr int BALLOON_2 = 2; constexpr int BALLOON_2 = 2;
constexpr int BALLOON_3 = 3; constexpr int BALLOON_3 = 3;
constexpr int BALLOON_4 = 4; constexpr int BALLOON_4 = 4;
constexpr int HEXAGON_1 = 5; constexpr int HEXAGON_1 = 5;
constexpr int HEXAGON_2 = 6; constexpr int HEXAGON_2 = 6;
constexpr int HEXAGON_3 = 7; constexpr int HEXAGON_3 = 7;
constexpr int HEXAGON_4 = 8; constexpr int HEXAGON_4 = 8;
constexpr int POWER_BALL = 9; constexpr int POWER_BALL = 9;
// Puntos de globo // Puntos de globo
constexpr int BALLOON_SCORE_1 = 50; constexpr int BALLOON_SCORE_1 = 50;
constexpr int BALLOON_SCORE_2 = 100; constexpr int BALLOON_SCORE_2 = 100;
constexpr int BALLOON_SCORE_3 = 200; constexpr int BALLOON_SCORE_3 = 200;
constexpr int BALLOON_SCORE_4 = 400; constexpr int BALLOON_SCORE_4 = 400;
// Tamaños de globo // Tamaños de globo
constexpr int BALLOON_SIZE_1 = 1; constexpr int BALLOON_SIZE_1 = 1;
constexpr int BALLOON_SIZE_2 = 2; constexpr int BALLOON_SIZE_2 = 2;
constexpr int BALLOON_SIZE_3 = 3; constexpr int BALLOON_SIZE_3 = 3;
constexpr int BALLOON_SIZE_4 = 4; constexpr int BALLOON_SIZE_4 = 4;
// Clases de globo // Clases de globo
constexpr int BALLOON_CLASS = 0; constexpr int BALLOON_CLASS = 0;
constexpr int HEXAGON_CLASS = 1; constexpr int HEXAGON_CLASS = 1;
// Velocidad del globo // Velocidad del globo
constexpr float BALLOON_VELX_POSITIVE = 0.7f; constexpr float BALLOON_VELX_POSITIVE = 0.7f;
constexpr float BALLOON_VELX_NEGATIVE = -0.7f; constexpr float BALLOON_VELX_NEGATIVE = -0.7f;
// Indice para las animaciones de los globos // Indice para las animaciones de los globos
constexpr int BALLOON_MOVING_ANIMATION = 0; constexpr int BALLOON_MOVING_ANIMATION = 0;
constexpr int BALLOON_POP_ANIMATION = 1; constexpr int BALLOON_POP_ANIMATION = 1;
constexpr int BALLOON_BORN_ANIMATION = 2; constexpr int BALLOON_BORN_ANIMATION = 2;
// Cantidad posible de globos // Cantidad posible de globos
constexpr int MAX_BALLOONS = 100; constexpr int MAX_BALLOONS = 100;
// Velocidades a las que se mueven los globos // Velocidades a las que se mueven los globos
constexpr float BALLOON_SPEED_1 = 0.60f; constexpr float BALLOON_SPEED_1 = 0.60f;
constexpr float BALLOON_SPEED_2 = 0.70f; constexpr float BALLOON_SPEED_2 = 0.70f;
constexpr float BALLOON_SPEED_3 = 0.80f; constexpr float BALLOON_SPEED_3 = 0.80f;
constexpr float BALLOON_SPEED_4 = 0.90f; constexpr float BALLOON_SPEED_4 = 0.90f;
constexpr float BALLOON_SPEED_5 = 1.00f; constexpr float BALLOON_SPEED_5 = 1.00f;
// Tamaño de los globos // Tamaño de los globos
constexpr int BALLOON_WIDTH_1 = 10; constexpr int BALLOON_WIDTH_1 = 10;
constexpr int BALLOON_WIDTH_2 = 16; constexpr int BALLOON_WIDTH_2 = 16;
constexpr int BALLOON_WIDTH_3 = 26; constexpr int BALLOON_WIDTH_3 = 26;
constexpr int BALLOON_WIDTH_4 = 46; constexpr int BALLOON_WIDTH_4 = 46;
// PowerBall // PowerBall
constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10; constexpr int POWERBALL_SCREENPOWER_MINIMUM = 10;
constexpr int POWERBALL_COUNTER = 8; constexpr int POWERBALL_COUNTER = 8;
// Clase Balloon // Clase Balloon
class Balloon class Balloon
@@ -86,37 +86,37 @@ private:
}; };
// Objetos y punteros // Objetos y punteros
std::unique_ptr<AnimatedSprite> sprite; // Sprite del objeto globo std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
// Variables // Variables
float posX; // Posición en el eje X float pos_x_; // Posición en el eje X
float posY; // Posición en el eje Y float pos_y_; // Posición en el eje Y
Uint8 width; // Ancho Uint8 width_; // Ancho
Uint8 height; // Alto Uint8 height_; // Alto
float velX; // Velocidad en el eje X. Cantidad de pixeles a desplazarse float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float velY; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float gravity; // Aceleración en el eje Y. Modifica la velocidad float gravity_; // Aceleración en el eje Y. Modifica la velocidad
float defaultVelY; // Velocidad inicial que tienen al rebotar contra el suelo float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo
float maxVelY; // Máxima velocidad que puede alcanzar el objeto en el eje Y float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y
bool beingCreated; // Indica si el globo se está creando bool being_created_; // Indica si el globo se está creando
bool blinking; // Indica si el globo está intermitente bool blinking_; // Indica si el globo está intermitente
bool enabled; // Indica si el globo esta activo bool enabled_; // Indica si el globo esta activo
bool invulnerable; // Indica si el globo es invulnerable bool invulnerable_; // Indica si el globo es invulnerable
bool stopped; // Indica si el globo está parado bool stopped_; // Indica si el globo está parado
bool visible; // Indica si el globo es visible bool visible_; // Indica si el globo es visible
circle_t collider; // Circulo de colisión del objeto Circle collider_; // Circulo de colisión del objeto
Uint16 creationCounter; // Temporizador para controlar el estado "creandose" Uint16 creation_counter_; // Temporizador para controlar el estado "creandose"
Uint16 creationCounterIni; // Valor inicial para el temporizador para controlar el estado "creandose" Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
Uint16 score; // Puntos que da el globo al ser destruido Uint16 score_; // Puntos que da el globo al ser destruido
Uint16 stoppedCounter; // Contador para controlar el estado "parado" Uint16 stopped_counter_; // Contador para controlar el estado "parado"
Uint8 kind; // Tipo de globo Uint8 kind_; // Tipo de globo
Uint8 menace; // Cantidad de amenaza que genera el globo Uint8 menace_; // Cantidad de amenaza que genera el globo
Uint32 counter; // Contador interno Uint32 counter_; // Contador interno
float travelY; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad float travel_y_; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
float speed; // Velocidad a la que se mueven los globos float speed_; // Velocidad a la que se mueven los globos
Uint8 size; // Tamaño del globo Uint8 size_; // Tamaño del globo
Uint8 power; // Cantidad de poder que alberga el globo Uint8 power_; // Cantidad de poder que alberga el globo
Bouncing bouncing; // Contiene las variables para el efecto de rebote Bouncing bouncing_; // Contiene las variables para el efecto de rebote
// Alinea el circulo de colisión con la posición del objeto globo // Alinea el circulo de colisión con la posición del objeto globo
void updateColliders(); void updateColliders();
@@ -141,7 +141,7 @@ private:
public: public:
// Constructor // Constructor
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, std::shared_ptr<Texture> texture, std::vector<std::string> *animation); Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16 creation_timer, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Destructor // Destructor
~Balloon() = default; ~Balloon() = default;
@@ -183,7 +183,7 @@ public:
int getHeight() const; int getHeight() const;
// Establece el valor de la variable // Establece el valor de la variable
void setVelY(float velY); void setVelY(float vel_y);
// Establece el valor de la variable // Establece el valor de la variable
void setSpeed(float speed); void setSpeed(float speed);
@@ -234,7 +234,7 @@ public:
Uint16 getScore() const; Uint16 getScore() const;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); Circle &getCollider();
// Obtiene le valor de la variable // Obtiene le valor de la variable
Uint8 getMenace() const; Uint8 getMenace() const;

View File

@@ -11,46 +11,47 @@ constexpr int BULLET_VELX_LEFT = -2;
constexpr int BULLET_VELX_RIGHT = 2; constexpr int BULLET_VELX_RIGHT = 2;
// Constructor // Constructor
Bullet::Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr<Texture> texture) Bullet::Bullet(int x, int y, BulletType kind_, bool poweredUp, int owner, SDL_Rect *play_area, std::shared_ptr<Texture> texture)
: posX(x), posY(y), width(BULLET_WIDTH), height(BULLET_HEIGHT), velX(0), velY(BULLET_VELY), : pos_x_(x), pos_y_(y), width_(BULLET_WIDTH), height_(BULLET_HEIGHT), vel_x_(0), vel_y_(BULLET_VELY),
kind(kind), owner(owner), playArea(playArea) kind_(kind_), owner_(owner), play_area_(play_area)
{ {
velX = (kind == BulletType::LEFT) ? BULLET_VELX_LEFT : (kind == BulletType::RIGHT) ? BULLET_VELX_RIGHT : 0; vel_x_ = (kind_ == BulletType::LEFT) ? BULLET_VELX_LEFT : (kind_ == BulletType::RIGHT) ? BULLET_VELX_RIGHT
: 0;
auto spriteOffset = poweredUp ? 3 : 0; auto sprite_offset = poweredUp ? 3 : 0;
auto kindIndex = static_cast<int>(kind); auto kind_index = static_cast<int>(kind_);
sprite = std::make_unique<Sprite>(SDL_Rect{x, y, BULLET_WIDTH, BULLET_HEIGHT}, texture); sprite_ = std::make_unique<Sprite>(SDL_Rect{x, y, BULLET_WIDTH, BULLET_HEIGHT}, texture);
sprite->setSpriteClip((kindIndex + spriteOffset) * width, 0, sprite->getWidth(), sprite->getHeight()); sprite_->setSpriteClip((kind_index + sprite_offset) * width_, 0, sprite_->getWidth(), sprite_->getHeight());
collider.r = width / 2; collider_.r = width_ / 2;
shiftColliders(); shiftColliders();
} }
// Implementación de render (llama al render del sprite) // Implementación de render (llama al render del sprite_)
void Bullet::render() void Bullet::render()
{ {
sprite->render(); sprite_->render();
} }
// Implementación del movimiento usando BulletMoveStatus // Implementación del movimiento usando BulletMoveStatus
BulletMoveStatus Bullet::move() BulletMoveStatus Bullet::move()
{ {
posX += velX; pos_x_ += vel_x_;
if (posX < param.game.playArea.rect.x - width || posX > playArea->w) if (pos_x_ < param.game.play_area.rect.x - width_ || pos_x_ > play_area_->w)
{ {
disable(); disable();
return BulletMoveStatus::OUT; return BulletMoveStatus::OUT;
} }
posY += velY; pos_y_ += vel_y_;
if (posY < param.game.playArea.rect.y - height) if (pos_y_ < param.game.play_area.rect.y - height_)
{ {
disable(); disable();
return BulletMoveStatus::OUT; return BulletMoveStatus::OUT;
} }
sprite->setPosX(posX); sprite_->setPosX(pos_x_);
sprite->setPosY(posY); sprite_->setPosY(pos_y_);
shiftColliders(); shiftColliders();
return BulletMoveStatus::OK; return BulletMoveStatus::OK;
@@ -58,56 +59,56 @@ BulletMoveStatus Bullet::move()
bool Bullet::isEnabled() const bool Bullet::isEnabled() const
{ {
return kind != BulletType::NULL_TYPE; return kind_ != BulletType::NULL_TYPE;
} }
void Bullet::disable() void Bullet::disable()
{ {
kind = BulletType::NULL_TYPE; kind_ = BulletType::NULL_TYPE;
} }
int Bullet::getPosX() const int Bullet::getPosX() const
{ {
return posX; return pos_x_;
} }
int Bullet::getPosY() const int Bullet::getPosY() const
{ {
return posY; return pos_y_;
} }
void Bullet::setPosX(int x) void Bullet::setPosX(int x)
{ {
posX = x; pos_x_ = x;
} }
void Bullet::setPosY(int y) void Bullet::setPosY(int y)
{ {
posY = y; pos_y_ = y;
} }
int Bullet::getVelY() const int Bullet::getVelY() const
{ {
return velY; return vel_y_;
} }
BulletType Bullet::getKind() const BulletType Bullet::getKind() const
{ {
return kind; return kind_;
} }
int Bullet::getOwner() const int Bullet::getOwner() const
{ {
return owner; return owner_;
} }
circle_t &Bullet::getCollider() Circle &Bullet::getCollider()
{ {
return collider; return collider_;
} }
void Bullet::shiftColliders() void Bullet::shiftColliders()
{ {
collider.x = posX + collider.r; collider_.x = pos_x_ + collider_.r;
collider.y = posY + collider.r; collider_.y = pos_y_ + collider_.r;
} }

View File

@@ -4,8 +4,8 @@
#include <SDL2/SDL_stdinc.h> // for Uint8 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <memory> // for unique_ptr #include <memory> // for unique_ptr
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "utils.h" // for circle_t #include "utils.h" // for Circle
#include "texture.h" // lines 9-9 #include "texture.h" // lines 9-9
// Enumeración para los diferentes tipos de balas // Enumeración para los diferentes tipos de balas
enum class BulletType enum class BulletType
@@ -27,36 +27,50 @@ enum class BulletMoveStatus : Uint8
class Bullet class Bullet
{ {
private: private:
int posX; // Posición en el eje X int pos_x_; // Posición en el eje X
int posY; // Posición en el eje Y int pos_y_; // Posición en el eje Y
Uint8 width; // Ancho del objeto Uint8 width_; // Ancho del objeto
Uint8 height; // Alto del objeto Uint8 height_; // Alto del objeto
int velX; // Velocidad en el eje X int vel_x_; // Velocidad en el eje X
int velY; // Velocidad en el eje Y int vel_y_; // Velocidad en el eje Y
BulletType kind; // Tipo de objeto BulletType kind_; // Tipo de objeto
int owner; // Identificador del dueño del objeto int owner_; // Identificador del dueño del objeto
circle_t collider; // Círculo de colisión del objeto Circle collider_; // Círculo de colisión del objeto
SDL_Rect *playArea; // Rectángulo con la zona de juego SDL_Rect *play_area_; // Rectángulo con la zona de juego
std::unique_ptr<Sprite> sprite; // Sprite con los gráficos y métodos de pintado std::unique_ptr<Sprite> sprite_; // Sprite con los gráficos y métodos de pintado
void shiftColliders(); // Alinea el círculo de colisión con el objeto void shiftColliders(); // Alinea el círculo de colisión con el objeto
public: public:
Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr<Texture> texture); // Constructor
Bullet(int x, int y, BulletType kind, bool powered_up, int owner, SDL_Rect *play_area, std::shared_ptr<Texture> texture);
// Destructor
~Bullet() = default; ~Bullet() = default;
void render(); // Pinta el objeto en pantalla // Pinta el objeto en pantalla
BulletMoveStatus move(); // Actualiza la posición y estado del objeto void render();
bool isEnabled() const; // Comprueba si el objeto está habilitado // Actualiza la posición y estado del objeto
void disable(); // Deshabilita el objeto BulletMoveStatus move();
// Comprueba si el objeto está habilitado
bool isEnabled() const;
// Deshabilita el objeto
void disable();
// Obtiene la posición
int getPosX() const; int getPosX() const;
int getPosY() const; int getPosY() const;
// Establece la posición
void setPosX(int x); void setPosX(int x);
void setPosY(int y); void setPosY(int y);
// Obtiene parámetros
int getVelY() const; int getVelY() const;
BulletType getKind() const; BulletType getKind() const;
int getOwner() const; int getOwner() const;
circle_t &getCollider(); Circle &getCollider();
}; };

View File

@@ -4,7 +4,7 @@
#include "param.h" // for param #include "param.h" // for param
#include "section.h" // for name, name_e, options, options_e #include "section.h" // for name, name_e, options, options_e
#include "text.h" // for Text #include "text.h" // for Text
#include "utils.h" // for op_controller_t, options_t, param_t, paramGame_t #include "utils.h" // for OptionsController, Options, Param, ParamGame
// Constructor // Constructor
DefineButtons::DefineButtons(std::unique_ptr<Text> text) DefineButtons::DefineButtons(std::unique_ptr<Text> text)

View File

@@ -33,7 +33,7 @@
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for name_e, name, options, options_e #include "section.h" // for name_e, name, options, options_e
#include "title.h" // for Title #include "title.h" // for Title
#include "utils.h" // for music_file_t, sound_file_t, opt... #include "utils.h" // for MusicFile, SoundFile, opt...
#include <memory> #include <memory>
#ifndef _WIN32 #ifndef _WIN32
@@ -129,7 +129,7 @@ Director::~Director()
SDL_Quit(); SDL_Quit();
} }
// Inicializa el objeto input /// Inicializa el objeto input
void Director::initInput() void Director::initInput()
{ {
// Establece si ha de mostrar mensajes // Establece si ha de mostrar mensajes
@@ -350,135 +350,135 @@ bool Director::setFileList()
#endif #endif
// Ficheros de configuración // Ficheros de configuración
Asset::get()->add(systemFolder + "/config.txt", t_data, false, true); Asset::get()->add(systemFolder + "/config.txt", AssetType::DATA, false, true);
Asset::get()->add(systemFolder + "/score.bin", t_data, false, true); Asset::get()->add(systemFolder + "/score.bin", AssetType::DATA, false, true);
Asset::get()->add(prefix + "/data/config/param_320x240.txt", t_data); Asset::get()->add(prefix + "/data/config/param_320x240.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/param_320x256.txt", t_data); Asset::get()->add(prefix + "/data/config/param_320x256.txt", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/demo1.bin", t_data); Asset::get()->add(prefix + "/data/config/demo1.bin", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/demo2.bin", t_data); Asset::get()->add(prefix + "/data/config/demo2.bin", AssetType::DATA);
Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", t_data); Asset::get()->add(prefix + "/data/config/gamecontrollerdb.txt", AssetType::DATA);
// Musicas // Musicas
Asset::get()->add(prefix + "/data/music/intro.ogg", t_music); Asset::get()->add(prefix + "/data/music/intro.ogg", AssetType::MUSIC);
Asset::get()->add(prefix + "/data/music/playing.ogg", t_music); Asset::get()->add(prefix + "/data/music/playing.ogg", AssetType::MUSIC);
Asset::get()->add(prefix + "/data/music/title.ogg", t_music); Asset::get()->add(prefix + "/data/music/title.ogg", AssetType::MUSIC);
// Sonidos // Sonidos
Asset::get()->add(prefix + "/data/sound/balloon.wav", t_sound); Asset::get()->add(prefix + "/data/sound/balloon.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble1.wav", t_sound); Asset::get()->add(prefix + "/data/sound/bubble1.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble2.wav", t_sound); Asset::get()->add(prefix + "/data/sound/bubble2.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble3.wav", t_sound); Asset::get()->add(prefix + "/data/sound/bubble3.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bubble4.wav", t_sound); Asset::get()->add(prefix + "/data/sound/bubble4.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/bullet.wav", t_sound); Asset::get()->add(prefix + "/data/sound/bullet.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/coffeeout.wav", t_sound); Asset::get()->add(prefix + "/data/sound/coffeeout.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/hiscore.wav", t_sound); Asset::get()->add(prefix + "/data/sound/hiscore.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/itemdrop.wav", t_sound); Asset::get()->add(prefix + "/data/sound/itemdrop.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/itempickup.wav", t_sound); Asset::get()->add(prefix + "/data/sound/itempickup.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/player_collision.wav", t_sound); Asset::get()->add(prefix + "/data/sound/player_collision.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/stage_change.wav", t_sound); Asset::get()->add(prefix + "/data/sound/stage_change.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/title.wav", t_sound); Asset::get()->add(prefix + "/data/sound/title.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/clock.wav", t_sound); Asset::get()->add(prefix + "/data/sound/clock.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/powerball.wav", t_sound); Asset::get()->add(prefix + "/data/sound/powerball.wav", AssetType::SOUND);
Asset::get()->add(prefix + "/data/sound/notify.wav", t_sound); Asset::get()->add(prefix + "/data/sound/notify.wav", AssetType::SOUND);
// Shaders // Shaders
Asset::get()->add(prefix + "/data/shaders/crtpi.glsl", t_data); Asset::get()->add(prefix + "/data/shaders/crtpi.glsl", AssetType::DATA);
// Texturas // Texturas
Asset::get()->add(prefix + "/data/gfx/controllers/controllers.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/controllers/controllers.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/balloon1.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/balloon2.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/balloon3.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/balloon4.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/explosion1.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/explosion2.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/explosion3.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/explosion4.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/balloon/powerball.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/balloon/powerball.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/balloon/powerball.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/balloon/powerball.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/bullet/bullet.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/bullet/bullet.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_buildings.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_buildings.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_clouds1.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_clouds1.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_clouds2.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_clouds2.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_power_meter.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_power_meter.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_text.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/game/game_text.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames_mini.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/logo/logo_jailgames_mini.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/logo/logo_since_1998.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/logo/logo_since_1998.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_points1_disk.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_points2_gavina.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_points3_pacmar.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_clock.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_clock.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_clock.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_clock.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_coffee.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_coffee.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/item/item_coffee_machine.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/title/title_bg_tile.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/title/title_bg_tile.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_coffee.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/title/title_coffee.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_crisis.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/title/title_crisis.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_arcade_edition.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/title/title_arcade_edition.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_dust.png", t_bitmap); Asset::get()->add(prefix + "/data/gfx/title/title_dust.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/title/title_dust.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/player/player1.gif", t_bitmap); Asset::get()->add(prefix + "/data/gfx/player/player1.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal1.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player1_pal1.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal2.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player1_pal2.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player1_pal3.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player1_pal3.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2.gif", t_bitmap); Asset::get()->add(prefix + "/data/gfx/player/player2.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal1.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player2_pal1.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal2.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player2_pal2.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player2_pal3.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player2_pal3.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/player/player.ani", AssetType::ANIMATION);
Asset::get()->add(prefix + "/data/gfx/player/player_power.gif", t_bitmap); Asset::get()->add(prefix + "/data/gfx/player/player_power.gif", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/player/player_power_pal.gif", t_palette); Asset::get()->add(prefix + "/data/gfx/player/player_power_pal.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", t_animation); Asset::get()->add(prefix + "/data/gfx/player/player_power.ani", AssetType::ANIMATION);
// Fuentes de texto // Fuentes de texto
Asset::get()->add(prefix + "/data/font/8bithud.png", t_font); Asset::get()->add(prefix + "/data/font/8bithud.png", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/8bithud.txt", t_font); Asset::get()->add(prefix + "/data/font/8bithud.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia.png", t_font); Asset::get()->add(prefix + "/data/font/nokia.png", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia_big2.png", t_font); Asset::get()->add(prefix + "/data/font/nokia_big2.png", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia.txt", t_font); Asset::get()->add(prefix + "/data/font/nokia.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia2.png", t_font); Asset::get()->add(prefix + "/data/font/nokia2.png", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia2.txt", t_font); Asset::get()->add(prefix + "/data/font/nokia2.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/nokia_big2.txt", t_font); Asset::get()->add(prefix + "/data/font/nokia_big2.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2_big.png", t_font); Asset::get()->add(prefix + "/data/font/smb2_big.png", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2_big.txt", t_font); Asset::get()->add(prefix + "/data/font/smb2_big.txt", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2.gif", t_font); Asset::get()->add(prefix + "/data/font/smb2.gif", AssetType::FONT);
Asset::get()->add(prefix + "/data/font/smb2_pal1.gif", t_palette); Asset::get()->add(prefix + "/data/font/smb2_pal1.gif", AssetType::PALETTE);
Asset::get()->add(prefix + "/data/font/smb2.txt", t_font); Asset::get()->add(prefix + "/data/font/smb2.txt", AssetType::FONT);
// Textos // Textos
Asset::get()->add(prefix + "/data/lang/es_ES.txt", t_lang); Asset::get()->add(prefix + "/data/lang/es_ES.txt", AssetType::LANG);
Asset::get()->add(prefix + "/data/lang/en_UK.txt", t_lang); Asset::get()->add(prefix + "/data/lang/en_UK.txt", AssetType::LANG);
Asset::get()->add(prefix + "/data/lang/ba_BA.txt", t_lang); Asset::get()->add(prefix + "/data/lang/ba_BA.txt", AssetType::LANG);
return Asset::get()->check(); return Asset::get()->check();
} }
@@ -561,14 +561,14 @@ void Director::createSystemFolder(std::string folder)
void Director::loadSounds() void Director::loadSounds()
{ {
// Obtiene la lista con las rutas a los ficheros de sonidos // Obtiene la lista con las rutas a los ficheros de sonidos
std::vector<std::string> list = Asset::get()->getListByType(t_sound); std::vector<std::string> list = Asset::get()->getListByType(AssetType::SOUND);
sounds.clear(); sounds.clear();
for (auto l : list) for (auto l : list)
{ {
const size_t lastIndex = l.find_last_of("/") + 1; const size_t lastIndex = l.find_last_of("/") + 1;
const std::string name = l.substr(lastIndex, std::string::npos); const std::string name = l.substr(lastIndex, std::string::npos);
sound_file_t temp; SoundFile temp;
temp.name = name; // Añade el nombre del fichero temp.name = name; // Añade el nombre del fichero
temp.file = JA_LoadSound(l.c_str()); // Carga el fichero de audio temp.file = JA_LoadSound(l.c_str()); // Carga el fichero de audio
sounds.push_back(temp); sounds.push_back(temp);
@@ -579,14 +579,14 @@ void Director::loadSounds()
void Director::loadMusics() void Director::loadMusics()
{ {
// Obtiene la lista con las rutas a los ficheros musicales // Obtiene la lista con las rutas a los ficheros musicales
std::vector<std::string> list = Asset::get()->getListByType(t_music); std::vector<std::string> list = Asset::get()->getListByType(AssetType::MUSIC);
musics.clear(); musics.clear();
for (auto l : list) for (auto l : list)
{ {
const size_t lastIndex = l.find_last_of("/") + 1; const size_t lastIndex = l.find_last_of("/") + 1;
const std::string name = l.substr(lastIndex, std::string::npos); const std::string name = l.substr(lastIndex, std::string::npos);
music_file_t temp; MusicFile temp;
temp.name = name; // Añade el nombre del fichero temp.name = name; // Añade el nombre del fichero
temp.file = JA_LoadMusic(l.c_str()); // Carga el fichero de audio temp.file = JA_LoadMusic(l.c_str()); // Carga el fichero de audio
musics.push_back(temp); musics.push_back(temp);

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_video.h> // for SDL_Window #include <SDL2/SDL_video.h> // for SDL_Window
#include <string> // for string, basic_string #include <string> // for string, basic_string
#include <vector> // for vector #include <vector> // for vector
#include "lang.h" // for lang_e #include "lang.h" // for lang_e
#include "utils.h" // for music_file_t, sound_file_t #include "utils.h" // for MusicFile, SoundFile
// Textos // Textos
#define WINDOW_CAPTION "Coffee Crisis Arcade Edition" #define WINDOW_CAPTION "Coffee Crisis Arcade Edition"
@@ -14,15 +14,15 @@ class Director
{ {
private: private:
// Objetos y punteros // Objetos y punteros
SDL_Window *window; // La ventana donde dibujamos SDL_Window *window; // La ventana donde dibujamos
SDL_Renderer *renderer; // El renderizador de la ventana SDL_Renderer *renderer; // El renderizador de la ventana
// Variables // Variables
std::string executablePath; // Path del ejecutable std::string executablePath; // Path del ejecutable
std::string systemFolder; // Carpeta del sistema donde guardar datos std::string systemFolder; // Carpeta del sistema donde guardar datos
std::string paramFileArgument; // Argumento para gestionar el fichero con los parametros del programa std::string paramFileArgument; // Argumento para gestionar el fichero con los parametros del programa
std::vector<sound_file_t> sounds; // Vector con los sonidos std::vector<SoundFile> sounds; // Vector con los sonidos
std::vector<music_file_t> musics; // Vector con las musicas std::vector<MusicFile> musics; // Vector con las musicas
// Inicializa jail_audio // Inicializa jail_audio
void initJailAudio(); void initJailAudio();

View File

@@ -1,7 +1,7 @@
#include "enemy_formations.h" #include "enemy_formations.h"
#include "balloon.h" // for BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE #include "balloon.h" // for BALLOON_VELX_NEGATIVE, BALLOON_VELX_POSITIVE
#include "param.h" // for param #include "param.h" // for param
#include "utils.h" // for paramGame_t, param_t, zone_t, BLOCK #include "utils.h" // for ParamGame, Param, Zone, BLOCK
// Constructor // Constructor
EnemyFormations::EnemyFormations() EnemyFormations::EnemyFormations()
@@ -15,21 +15,21 @@ EnemyFormations::EnemyFormations()
void EnemyFormations::initEnemyFormations() void EnemyFormations::initEnemyFormations()
{ {
const int y4 = -BLOCK; const int y4 = -BLOCK;
const int x4_0 = param.game.playArea.rect.x; const int x4_0 = param.game.play_area.rect.x;
const int x4_100 = param.game.playArea.rect.w - BALLOON_WIDTH_4; const int x4_100 = param.game.play_area.rect.w - BALLOON_WIDTH_4;
const int y3 = -BLOCK; const int y3 = -BLOCK;
const int x3_0 = param.game.playArea.rect.x; const int x3_0 = param.game.play_area.rect.x;
const int x3_100 = param.game.playArea.rect.w - BALLOON_WIDTH_3; const int x3_100 = param.game.play_area.rect.w - BALLOON_WIDTH_3;
const int y2 = -BLOCK; const int y2 = -BLOCK;
const int x2_0 = param.game.playArea.rect.x; const int x2_0 = param.game.play_area.rect.x;
const int x2_100 = param.game.playArea.rect.w - BALLOON_WIDTH_2; const int x2_100 = param.game.play_area.rect.w - BALLOON_WIDTH_2;
const int y1 = -BLOCK; const int y1 = -BLOCK;
const int x1_0 = param.game.playArea.rect.x; const int x1_0 = param.game.play_area.rect.x;
const int x1_50 = param.game.playArea.centerX - (BALLOON_WIDTH_1 / 2); const int x1_50 = param.game.play_area.centerX - (BALLOON_WIDTH_1 / 2);
const int x1_100 = param.game.playArea.rect.w - BALLOON_WIDTH_1; const int x1_100 = param.game.play_area.rect.w - BALLOON_WIDTH_1;
// Inicializa a cero las variables // Inicializa a cero las variables
for (int i = 0; i < NUMBER_OF_ENEMY_FORMATIONS; i++) for (int i = 0; i < NUMBER_OF_ENEMY_FORMATIONS; i++)
@@ -67,11 +67,11 @@ void EnemyFormations::initEnemyFormations()
// #01 - Dos enemigos BALLOON4 uno a cada cuarto. Ambos van hacia el centro // #01 - Dos enemigos BALLOON4 uno a cada cuarto. Ambos van hacia el centro
j = 1; j = 1;
enemyFormation[j].numberOfEnemies = 2; enemyFormation[j].numberOfEnemies = 2;
incX = param.game.playArea.centerX; incX = param.game.play_area.centerX;
incTime = 0; incTime = 0;
for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++) for (int i = 0; i < enemyFormation[j].numberOfEnemies; i++)
{ {
enemyFormation[j].init[i].x = param.game.playArea.firstQuarterX - (BALLOON_WIDTH_4 / 2) + (i * incX); enemyFormation[j].init[i].x = param.game.play_area.firstQuarterX - (BALLOON_WIDTH_4 / 2) + (i * incX);
enemyFormation[j].init[i].y = y4; enemyFormation[j].init[i].y = y4;
enemyFormation[j].init[i].velX = BALLOON_VELX_NEGATIVE * (((i % 2) * 2) - 1); enemyFormation[j].init[i].velX = BALLOON_VELX_NEGATIVE * (((i % 2) * 2) - 1);
enemyFormation[j].init[i].kind = BALLOON_4; enemyFormation[j].init[i].kind = BALLOON_4;

View File

@@ -4,7 +4,7 @@
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include <algorithm> // for min, max #include <algorithm> // for min, max
#include "param.h" // for param #include "param.h" // for param
#include "utils.h" // for param_t, paramGame_t, paramFade_t #include "utils.h" // for Param, ParamGame, ParamFade
// Constructor // Constructor
Fade::Fade(SDL_Renderer *renderer) Fade::Fade(SDL_Renderer *renderer)
@@ -38,9 +38,9 @@ void Fade::init()
b = 0; b = 0;
postDuration = 20; postDuration = 20;
postCounter = 0; postCounter = 0;
numSquaresWidth = param.fade.numSquaresWidth; numSquaresWidth = param.fade.num_squares_width;
numSquaresHeight = param.fade.numSquaresHeight; numSquaresHeight = param.fade.num_squares_height;
fadeRandomSquaresDelay = param.fade.randomSquaresDelay; fadeRandomSquaresDelay = param.fade.random_squares_delay;
fadeRandomSquaresMult = param.fade.randomSquaresMult; fadeRandomSquaresMult = param.fade.randomSquaresMult;
} }

View File

@@ -74,7 +74,7 @@ Game::Game(int playerID, int currentStage, bool demo, JA_Music_t *music)
loadDemoFile(asset->get("demo2.bin"), &this->demo.dataFile[index2]); loadDemoFile(asset->get("demo2.bin"), &this->demo.dataFile[index2]);
} }
background->setPos(param.game.playArea.rect); background->setPos(param.game.play_area.rect);
n1000Sprite = std::make_shared<SmartSprite>(gameTextTexture); n1000Sprite = std::make_shared<SmartSprite>(gameTextTexture);
n2500Sprite = std::make_shared<SmartSprite>(gameTextTexture); n2500Sprite = std::make_shared<SmartSprite>(gameTextTexture);
@@ -85,7 +85,7 @@ Game::Game(int playerID, int currentStage, bool demo, JA_Music_t *music)
explosions->addTexture(3, explosionsTextures[2], explosionsAnimations[2]); explosions->addTexture(3, explosionsTextures[2], explosionsAnimations[2]);
explosions->addTexture(4, explosionsTextures[3], explosionsAnimations[3]); explosions->addTexture(4, explosionsTextures[3], explosionsAnimations[3]);
canvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.playArea.rect.w, param.game.playArea.rect.h); canvas = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h);
SDL_SetTextureBlendMode(canvas, SDL_BLENDMODE_BLEND); SDL_SetTextureBlendMode(canvas, SDL_BLENDMODE_BLEND);
// Inicializa las variables necesarias para la sección 'Game' // Inicializa las variables necesarias para la sección 'Game'
@@ -122,14 +122,14 @@ void Game::init(int playerID)
players.clear(); players.clear();
// Crea los dos jugadores // Crea los dos jugadores
auto player1 = std::make_unique<Player>(1, (param.game.playArea.firstQuarterX * ((0 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, &param.game.playArea.rect, playerTextures[0], playerAnimations); auto player1 = std::make_unique<Player>(1, (param.game.play_area.firstQuarterX * ((0 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo.enabled, &param.game.play_area.rect, playerTextures[0], playerAnimations);
player1->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL); player1->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL);
player1->setName(lang::getText(53)); player1->setName(lang::getText(53));
const auto controller1 = getController(player1->getId()); const auto controller1 = getController(player1->getId());
player1->setController(controller1); player1->setController(controller1);
players.push_back(std::move(player1)); players.push_back(std::move(player1));
auto player2 = std::make_unique<Player>(2, (param.game.playArea.firstQuarterX * ((1 * 2) + 1)) - 11, param.game.playArea.rect.h - 30, demo.enabled, &param.game.playArea.rect, playerTextures[1], playerAnimations); auto player2 = std::make_unique<Player>(2, (param.game.play_area.firstQuarterX * ((1 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo.enabled, &param.game.play_area.rect, playerTextures[1], playerAnimations);
player2->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL); player2->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL);
player2->setName(lang::getText(54)); player2->setName(lang::getText(54));
const auto controller2 = getController(player2->getId()); const auto controller2 = getController(player2->getId());
@@ -582,7 +582,7 @@ void Game::unloadMedia()
} }
// Carga el fichero de datos para la demo // Carga el fichero de datos para la demo
bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_DATA]) bool Game::loadDemoFile(std::string filePath, DemoKeys (*dataFile)[TOTAL_DEMO_DATA])
{ {
// Indicador de éxito en la carga // Indicador de éxito en la carga
auto success = true; auto success = true;
@@ -608,7 +608,7 @@ bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_
// Inicializas los datos y los guarda en el fichero // Inicializas los datos y los guarda en el fichero
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) for (int i = 0; i < TOTAL_DEMO_DATA; ++i)
{ {
demoKeys_t tmp; DemoKeys tmp;
tmp.left = 0; tmp.left = 0;
tmp.right = 0; tmp.right = 0;
tmp.noInput = 0; tmp.noInput = 0;
@@ -616,7 +616,7 @@ bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_
tmp.fireLeft = 0; tmp.fireLeft = 0;
tmp.fireRight = 0; tmp.fireRight = 0;
(*dataFile)[i] = tmp; (*dataFile)[i] = tmp;
SDL_RWwrite(file, &tmp, sizeof(demoKeys_t), 1); SDL_RWwrite(file, &tmp, sizeof(DemoKeys), 1);
} }
// Cerramos el fichero // Cerramos el fichero
@@ -641,8 +641,8 @@ bool Game::loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_
// Lee todos los datos del fichero y los deja en el destino // Lee todos los datos del fichero y los deja en el destino
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) for (int i = 0; i < TOTAL_DEMO_DATA; ++i)
{ {
demoKeys_t tmp; DemoKeys tmp;
SDL_RWread(file, &tmp, sizeof(demoKeys_t), 1); SDL_RWread(file, &tmp, sizeof(DemoKeys), 1);
(*dataFile)[i] = tmp; (*dataFile)[i] = tmp;
} }
@@ -666,7 +666,7 @@ bool Game::saveDemoFile(std::string filePath)
// Guardamos los datos // Guardamos los datos
for (int i = 0; i < TOTAL_DEMO_DATA; ++i) for (int i = 0; i < TOTAL_DEMO_DATA; ++i)
{ {
SDL_RWwrite(file, &demo.dataFile[0][i], sizeof(demoKeys_t), 1); SDL_RWwrite(file, &demo.dataFile[0][i], sizeof(DemoKeys), 1);
} }
#ifdef VERBOSE #ifdef VERBOSE
@@ -800,7 +800,7 @@ void Game::renderPlayers()
player->render(); player->render();
#ifdef DEBUG #ifdef DEBUG
// SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); // SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
// const circle_t c = player->getCollider(); // const Circle c = player->getCollider();
// DrawCircle(renderer, c.x, c.y, c.r); // DrawCircle(renderer, c.x, c.y, c.r);
#endif #endif
} }
@@ -921,9 +921,9 @@ void Game::createPowerBall()
constexpr auto values = 6; constexpr auto values = 6;
constexpr auto posY = -BLOCK; constexpr auto posY = -BLOCK;
const auto left = param.game.playArea.rect.x; const auto left = param.game.play_area.rect.x;
const auto center = param.game.playArea.centerX - (BALLOON_WIDTH_4 / 2); const auto center = param.game.play_area.centerX - (BALLOON_WIDTH_4 / 2);
const auto right = param.game.playArea.rect.w - BALLOON_WIDTH_4; const auto right = param.game.play_area.rect.w - BALLOON_WIDTH_4;
const auto vpos = BALLOON_VELX_POSITIVE; const auto vpos = BALLOON_VELX_POSITIVE;
const auto vneg = BALLOON_VELX_NEGATIVE; const auto vneg = BALLOON_VELX_NEGATIVE;
@@ -1405,7 +1405,7 @@ void Game::renderBullets()
// Crea un objeto bala // Crea un objeto bala
void Game::createBullet(int x, int y, BulletType kind, bool poweredUp, int owner) void Game::createBullet(int x, int y, BulletType kind, bool poweredUp, int owner)
{ {
auto b = std::make_unique<Bullet>(x, y, kind, poweredUp, owner, &(param.game.playArea.rect), bulletTexture); auto b = std::make_unique<Bullet>(x, y, kind, poweredUp, owner, &(param.game.play_area.rect), bulletTexture);
bullets.push_back(std::move(b)); bullets.push_back(std::move(b));
} }
@@ -1529,7 +1529,7 @@ int Game::dropItem()
// Crea un objeto item // Crea un objeto item
void Game::createItem(int kind, float x, float y) void Game::createItem(int kind, float x, float y)
{ {
auto item = std::make_unique<Item>(kind, x, y, &(param.game.playArea.rect), itemTextures[kind - 1], itemAnimations[kind - 1]); auto item = std::make_unique<Item>(kind, x, y, &(param.game.play_area.rect), itemTextures[kind - 1], itemAnimations[kind - 1]);
items.push_back(std::move(item)); items.push_back(std::move(item));
} }
@@ -1587,8 +1587,8 @@ void Game::throwCoffee(int x, int y)
ss->setPosX(x - 8); ss->setPosX(x - 8);
ss->setPosY(y - 8); ss->setPosY(y - 8);
ss->setWidth(param.game.itemSize); ss->setWidth(param.game.item_size);
ss->setHeight(param.game.itemSize); ss->setHeight(param.game.item_size);
ss->setVelX(-1.0f + ((rand() % 5) * 0.5f)); ss->setVelX(-1.0f + ((rand() % 5) * 0.5f));
ss->setVelY(-4.0f); ss->setVelY(-4.0f);
ss->setAccelX(0.0f); ss->setAccelX(0.0f);
@@ -1597,7 +1597,7 @@ void Game::throwCoffee(int x, int y)
ss->setDestY(param.game.height + 1); ss->setDestY(param.game.height + 1);
ss->setEnabled(true); ss->setEnabled(true);
ss->setFinishedCounter(1); ss->setFinishedCounter(1);
ss->setSpriteClip(0, param.game.itemSize, param.game.itemSize, param.game.itemSize); ss->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
ss->setRotate(true); ss->setRotate(true);
ss->setRotateSpeed(10); ss->setRotateSpeed(10);
ss->setRotateAmount(90.0); ss->setRotateAmount(90.0);
@@ -1909,7 +1909,7 @@ void Game::render()
screen->start(); screen->start();
// Copia la textura con la zona de juego a la pantalla // Copia la textura con la zona de juego a la pantalla
SDL_RenderCopy(renderer, canvas, nullptr, &param.game.playArea.rect); SDL_RenderCopy(renderer, canvas, nullptr, &param.game.play_area.rect);
// Dibuja el marcador // Dibuja el marcador
scoreboard->render(); scoreboard->render();
@@ -2206,7 +2206,7 @@ void Game::renderMessages()
// GetReady // GetReady
if (counter < STAGE_COUNTER && !demo.enabled) if (counter < STAGE_COUNTER && !demo.enabled)
{ {
textNokiaBig2->write((int)getReadyBitmapPath[counter], param.game.playArea.centerY - 8, lang::getText(75), -2); textNokiaBig2->write((int)getReadyBitmapPath[counter], param.game.play_area.centerY - 8, lang::getText(75), -2);
} }
// Time Stopped // Time Stopped
@@ -2214,7 +2214,7 @@ void Game::renderMessages()
{ {
if (timeStoppedCounter > 100 || timeStoppedCounter % 10 > 4) if (timeStoppedCounter > 100 || timeStoppedCounter % 10 > 4)
{ {
textNokia2->writeDX(TXT_CENTER, param.game.playArea.centerX, param.game.playArea.firstQuarterY, lang::getText(36) + std::to_string(timeStoppedCounter / 10), -1, noColor, 1, shdwTxtColor); textNokia2->writeDX(TXT_CENTER, param.game.play_area.centerX, param.game.play_area.firstQuarterY, lang::getText(36) + std::to_string(timeStoppedCounter / 10), -1, noColor, 1, shdwTxtColor);
} }
if (timeStoppedCounter > 100) if (timeStoppedCounter > 100)
@@ -2250,13 +2250,13 @@ void Game::renderMessages()
if (!gameCompleted) if (!gameCompleted)
{ // Escribe el número de fases restantes { // Escribe el número de fases restantes
textNokiaBig2->writeDX(TXT_CENTER, param.game.playArea.centerX, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 2, shdwTxtColor); textNokiaBig2->writeDX(TXT_CENTER, param.game.play_area.centerX, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 2, shdwTxtColor);
} }
else else
{ // Escribe el texto de juego completado { // Escribe el texto de juego completado
text = lang::getText(50); text = lang::getText(50);
textNokiaBig2->writeDX(TXT_CENTER, param.game.playArea.centerX, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 1, shdwTxtColor); textNokiaBig2->writeDX(TXT_CENTER, param.game.play_area.centerX, stageBitmapPath[stageBitmapCounter], text, -2, noColor, 1, shdwTxtColor);
textNokia2->writeDX(TXT_CENTER, param.game.playArea.centerX, stageBitmapPath[stageBitmapCounter] + textNokiaBig2->getCharacterSize() + 2, lang::getText(76), -1, noColor, 1, shdwTxtColor); textNokia2->writeDX(TXT_CENTER, param.game.play_area.centerX, stageBitmapPath[stageBitmapCounter] + textNokiaBig2->getCharacterSize() + 2, lang::getText(76), -1, noColor, 1, shdwTxtColor);
} }
} }
} }
@@ -2353,8 +2353,8 @@ void Game::initPaths()
// Letrero de STAGE # // Letrero de STAGE #
constexpr auto firstPart = STAGE_COUNTER / 4; // 50 constexpr auto firstPart = STAGE_COUNTER / 4; // 50
constexpr auto secondPart = firstPart * 3; // 150 constexpr auto secondPart = firstPart * 3; // 150
const auto centerPoint = param.game.playArea.centerY - (BLOCK * 2); const auto centerPoint = param.game.play_area.centerY - (BLOCK * 2);
const auto distance = (param.game.playArea.rect.h) - (param.game.playArea.centerY - 16); const auto distance = (param.game.play_area.rect.h) - (param.game.play_area.centerY - 16);
for (int i = 0; i < STAGE_COUNTER; ++i) for (int i = 0; i < STAGE_COUNTER; ++i)
{ {
@@ -2377,11 +2377,11 @@ void Game::initPaths()
// Letrero de GetReady // Letrero de GetReady
const auto size = textNokiaBig2->lenght(lang::getText(75), -2); const auto size = textNokiaBig2->lenght(lang::getText(75), -2);
const float start1 = param.game.playArea.rect.x - size; const float start1 = param.game.play_area.rect.x - size;
const float finish1 = param.game.playArea.centerX - (size / 2); const float finish1 = param.game.play_area.centerX - (size / 2);
const float start2 = finish1; const float start2 = finish1;
const float finish2 = param.game.playArea.rect.w; const float finish2 = param.game.play_area.rect.w;
const float distance1 = finish1 - start1; const float distance1 = finish1 - start1;
const float distance2 = finish2 - start2; const float distance2 = finish2 - start2;
@@ -2668,7 +2668,7 @@ void Game::pause(bool value)
// Añade una puntuación a la tabla de records // Añade una puntuación a la tabla de records
void Game::addScoreToScoreBoard(std::string name, int score) void Game::addScoreToScoreBoard(std::string name, int score)
{ {
const auto entry = (hiScoreEntry_t){trim(name), score}; const auto entry = (HiScoreEntry){trim(name), score};
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hiScoreTable); auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hiScoreTable);
manager->add(entry); manager->add(entry);
manager->saveToFile(asset->get("score.bin")); manager->saveToFile(asset->get("score.bin"));

View File

@@ -6,7 +6,7 @@
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "section.h" // for options_e #include "section.h" // for options_e
#include "utils.h" // for demoKeys_t, color_t, hiScoreEntry_t #include "utils.h" // for DemoKeys, Color, HiScoreEntry
#include <memory> #include <memory>
#include "asset.h" // lines 11-11 #include "asset.h" // lines 11-11
#include "background.h" // lines 12-12 #include "background.h" // lines 12-12
@@ -98,11 +98,11 @@ private:
struct demo_t struct demo_t
{ {
bool enabled; // Indica si está activo el modo demo bool enabled; // Indica si está activo el modo demo
bool recording; // Indica si está activado el modo para grabar la demo bool recording; // Indica si está activado el modo para grabar la demo
int counter; // Contador para el modo demo int counter; // Contador para el modo demo
demoKeys_t keys; // Variable con las pulsaciones de teclas del modo demo DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
demoKeys_t dataFile[2][TOTAL_DEMO_DATA]; // Vector con diferentes sets de datos con los movimientos para la demo DemoKeys dataFile[2][TOTAL_DEMO_DATA]; // Vector con diferentes sets de datos con los movimientos para la demo
}; };
// Objetos y punteros // Objetos y punteros
@@ -173,7 +173,7 @@ private:
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima bool hiScoreAchieved; // Indica si se ha superado la puntuación máxima
hiScoreEntry_t hiScore; // Máxima puntuación y nombre de quien la ostenta HiScoreEntry hiScore; // Máxima puntuación y nombre de quien la ostenta
int currentStage; // Indica la fase actual int currentStage; // Indica la fase actual
int stageBitmapCounter; // Contador para el tiempo visible del texto de Stage int stageBitmapCounter; // Contador para el tiempo visible del texto de Stage
float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto float stageBitmapPath[STAGE_COUNTER]; // Vector con los puntos Y por donde se desplaza el texto
@@ -197,7 +197,7 @@ private:
int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos int gameCompletedCounter; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
GameDifficulty difficulty; // Dificultad del juego GameDifficulty difficulty; // Dificultad del juego
float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad float difficultyScoreMultiplier; // Multiplicador de puntos en función de la dificultad
color_t difficultyColor; // Color asociado a la dificultad Color difficultyColor; // Color asociado a la dificultad
int lastStageReached; // Contiene el número de la última pantalla que se ha alcanzado int lastStageReached; // Contiene el número de la última pantalla que se ha alcanzado
demo_t demo; // Variable con todas las variables relacionadas con el modo demo demo_t demo; // Variable con todas las variables relacionadas con el modo demo
int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases int totalPowerToCompleteGame; // La suma del poder necesario para completar todas las fases
@@ -226,7 +226,7 @@ private:
void unloadMedia(); void unloadMedia();
// Carga el fichero de datos para la demo // Carga el fichero de datos para la demo
bool loadDemoFile(std::string filePath, demoKeys_t (*dataFile)[TOTAL_DEMO_DATA]); bool loadDemoFile(std::string filePath, DemoKeys (*dataFile)[TOTAL_DEMO_DATA]);
#ifdef RECORDING #ifdef RECORDING
// Guarda el fichero de datos para la demo // Guarda el fichero de datos para la demo
bool saveDemoFile(std::string filePath); bool saveDemoFile(std::string filePath);

View File

@@ -9,7 +9,7 @@
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SmartSprite
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for param_t, paramGame_t, paramTitle_t #include "utils.h" // for Param, ParamGame, ParamTitle
// Constructor // Constructor
GameLogo::GameLogo(int x, int y) GameLogo::GameLogo(int x, int y)

View File

@@ -7,7 +7,7 @@
#include "on_screen_help.h" #include "on_screen_help.h"
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for options_e, name, name_e, options #include "section.h" // for options_e, name, name_e, options
#include "utils.h" // for op_audio_t, options_t, op_music_t, boolToOnOff #include "utils.h" // for OptionsAudio, Options, OptionsMusic, boolToOnOff
namespace globalInputs namespace globalInputs
{ {

View File

@@ -5,17 +5,17 @@
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include <algorithm> // for max #include <algorithm> // for max
#include <vector> // for vector #include <vector> // for vector
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "background.h" // for Background #include "background.h" // for Background
#include "global_inputs.h" // for globalInputs::check #include "global_inputs.h" // for globalInputs::check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state #include "jail_audio.h" // for JA_GetMusicState, JA_Music_state
#include "lang.h" // for getText #include "lang.h" // for getText
#include "options.h" // for options #include "options.h" // for options
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "text.h" // for Text, TXT_CENTER, TXT_SHADOW, TXT_COLOR #include "text.h" // for Text, TXT_CENTER, TXT_SHADOW, TXT_COLOR
#include "utils.h" // for param_t, paramGame_t, hiScoreEntry_t #include "utils.h" // for Param, ParamGame, HiScoreEntry
// Constructor // Constructor
HiScoreTable::HiScoreTable(JA_Music_t *music) HiScoreTable::HiScoreTable(JA_Music_t *music)
@@ -44,7 +44,7 @@ HiScoreTable::HiScoreTable(JA_Music_t *music)
fadeMode = FadeMode::IN; fadeMode = FadeMode::IN;
// Inicializa objetos // Inicializa objetos
background->setPos(param.game.gameArea.rect); background->setPos(param.game.game_area.rect);
background->setCloudsSpeed(-0.1f); background->setCloudsSpeed(-0.1f);
background->setGradientNumber(1); background->setGradientNumber(1);
background->setTransition(0.8f); background->setTransition(0.8f);
@@ -121,7 +121,7 @@ void HiScoreTable::fillTexture()
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
// Escribe el texto: Mejores puntuaciones // Escribe el texto: Mejores puntuaciones
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, firstLine, lang::getText(42), 1, orangeColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, firstLine, lang::getText(42), 1, orangeColor, 1, shdwTxtColor);
// Escribe los nombres de la tabla de puntuaciones // Escribe los nombres de la tabla de puntuaciones
for (int i = 0; i < maxNames; ++i) for (int i = 0; i < maxNames; ++i)
@@ -136,7 +136,7 @@ void HiScoreTable::fillTexture()
dots = dots + "."; dots = dots + ".";
} }
const auto line = options.game.hiScoreTable[i].name + dots + score; const auto line = options.game.hiScoreTable[i].name + dots + score;
text->writeDX(TXT_CENTER | TXT_SHADOW, param.game.gameArea.centerX, (i * spaceBetweenLines) + firstLine + spaceBetweenHeader, line, 1, orangeColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_SHADOW, param.game.game_area.centerX, (i * spaceBetweenLines) + firstLine + spaceBetweenHeader, line, 1, orangeColor, 1, shdwTxtColor);
} }
// Cambia el destino de renderizado // Cambia el destino de renderizado

View File

@@ -18,7 +18,7 @@
#include "text.h" // for Text, TXT_CENTER, TXT_COLOR, TXT_SHADOW #include "text.h" // for Text, TXT_CENTER, TXT_COLOR, TXT_SHADOW
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "tiled_bg.h" // for Tiledbg, TILED_MODE_STATIC #include "tiled_bg.h" // for Tiledbg, TILED_MODE_STATIC
#include "utils.h" // for param_t, paramGame_t, color_t, shdwT... #include "utils.h" // for Param, ParamGame, Color, shdwT...
struct JA_Music_t; struct JA_Music_t;
// Constructor // Constructor
@@ -98,8 +98,8 @@ void Instructions::iniSprites()
// Inicializa los sprites // Inicializa los sprites
for (int i = 0; i < (int)itemTextures.size(); ++i) for (int i = 0; i < (int)itemTextures.size(); ++i)
{ {
auto sprite = std::make_unique<Sprite>(0, 0, param.game.itemSize, param.game.itemSize, itemTextures[i]); auto sprite = std::make_unique<Sprite>(0, 0, param.game.item_size, param.game.item_size, itemTextures[i]);
sprite->setPos((SDL_Point){spritePos.x, spritePos.y + ((param.game.itemSize + itemSpace) * i)}); sprite->setPos((SDL_Point){spritePos.x, spritePos.y + ((param.game.item_size + itemSpace) * i)});
sprites.push_back(std::move(sprite)); sprites.push_back(std::move(sprite));
} }
} }
@@ -107,33 +107,33 @@ void Instructions::iniSprites()
// Actualiza los sprites // Actualiza los sprites
void Instructions::updateSprites() void Instructions::updateSprites()
{ {
SDL_Rect srcRect = {0, 0, param.game.itemSize, param.game.itemSize}; SDL_Rect srcRect = {0, 0, param.game.item_size, param.game.item_size};
// Disquito // Disquito
srcRect.y = param.game.itemSize * (((counter + 12) / 36) % 2); srcRect.y = param.game.item_size * (((counter + 12) / 36) % 2);
sprites[0]->setSpriteClip(srcRect); sprites[0]->setSpriteClip(srcRect);
// Gavineixon // Gavineixon
srcRect.y = param.game.itemSize * (((counter + 9) / 36) % 2); srcRect.y = param.game.item_size * (((counter + 9) / 36) % 2);
sprites[1]->setSpriteClip(srcRect); sprites[1]->setSpriteClip(srcRect);
// Pacmar // Pacmar
srcRect.y = param.game.itemSize * (((counter + 6) / 36) % 2); srcRect.y = param.game.item_size * (((counter + 6) / 36) % 2);
sprites[2]->setSpriteClip(srcRect); sprites[2]->setSpriteClip(srcRect);
// Time Stopper // Time Stopper
srcRect.y = param.game.itemSize * (((counter + 3) / 36) % 2); srcRect.y = param.game.item_size * (((counter + 3) / 36) % 2);
sprites[3]->setSpriteClip(srcRect); sprites[3]->setSpriteClip(srcRect);
// Coffee // Coffee
srcRect.y = param.game.itemSize * (((counter + 0) / 36) % 2); srcRect.y = param.game.item_size * (((counter + 0) / 36) % 2);
sprites[4]->setSpriteClip(srcRect); sprites[4]->setSpriteClip(srcRect);
} }
// Rellena la textura de texto // Rellena la textura de texto
void Instructions::fillTexture() void Instructions::fillTexture()
{ {
const int despX = param.game.itemSize + 8; const int despX = param.game.item_size + 8;
// Modifica el renderizador para pintar en la textura // Modifica el renderizador para pintar en la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer); SDL_Texture *temp = SDL_GetRenderTarget(renderer);
@@ -152,7 +152,7 @@ void Instructions::fillTexture()
const int spacePostHeader = 20; const int spacePostHeader = 20;
const int spacePreHeader = 28; const int spacePreHeader = 28;
const int spaceBetweenLines = text->getCharacterSize() * 1.5f; const int spaceBetweenLines = text->getCharacterSize() * 1.5f;
const int spaceBetweenItemLines = param.game.itemSize + itemSpace; const int spaceBetweenItemLines = param.game.item_size + itemSpace;
const int spaceNewParagraph = spaceBetweenLines * 0.5f; const int spaceNewParagraph = spaceBetweenLines * 0.5f;
const int size = (numLines * spaceBetweenLines) + (numItemLines * spaceBetweenItemLines) + (numPostHeaders * spacePostHeader) + (numPreHeaders * spacePreHeader) + (spaceNewParagraph); const int size = (numLines * spaceBetweenLines) + (numItemLines * spaceBetweenItemLines) + (numPostHeaders * spacePostHeader) + (numPreHeaders * spacePreHeader) + (spaceNewParagraph);
@@ -168,20 +168,20 @@ void Instructions::fillTexture()
const int anchorItem = (param.game.width - (lenght + despX)) / 2; const int anchorItem = (param.game.width - (lenght + despX)) / 2;
// Escribe el texto de las instrucciones // Escribe el texto de las instrucciones
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, firstLine, lang::getText(11), 1, orangeColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, firstLine, lang::getText(11), 1, orangeColor, 1, shdwTxtColor);
const int anchor1 = firstLine + spacePostHeader; const int anchor1 = firstLine + spacePostHeader;
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, anchor1 + spaceBetweenLines * 0, lang::getText(12), 1, noColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, anchor1 + spaceBetweenLines * 0, lang::getText(12), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, anchor1 + spaceBetweenLines * 1, lang::getText(13), 1, noColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, anchor1 + spaceBetweenLines * 1, lang::getText(13), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, anchor1 + spaceNewParagraph + spaceBetweenLines * 2, lang::getText(14), 1, noColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, anchor1 + spaceNewParagraph + spaceBetweenLines * 2, lang::getText(14), 1, noColor, 1, shdwTxtColor);
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, anchor1 + spaceNewParagraph + spaceBetweenLines * 3, lang::getText(15), 1, noColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, anchor1 + spaceNewParagraph + spaceBetweenLines * 3, lang::getText(15), 1, noColor, 1, shdwTxtColor);
// Escribe el texto de los objetos y sus puntos // Escribe el texto de los objetos y sus puntos
const int anchor2 = anchor1 + spacePreHeader + spaceNewParagraph + spaceBetweenLines * 3; const int anchor2 = anchor1 + spacePreHeader + spaceNewParagraph + spaceBetweenLines * 3;
text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.gameArea.centerX, anchor2, lang::getText(16), 1, orangeColor, 1, shdwTxtColor); text->writeDX(TXT_CENTER | TXT_COLOR | TXT_SHADOW, param.game.game_area.centerX, anchor2, lang::getText(16), 1, orangeColor, 1, shdwTxtColor);
const int anchor3 = anchor2 + spacePostHeader; const int anchor3 = anchor2 + spacePostHeader;
// const int anchor4 = anchor3 + ((param.game.itemSize + text->getCharacterSize()) / 2); // const int anchor4 = anchor3 + ((param.game.item_size + text->getCharacterSize()) / 2);
text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 0, lang::getText(17), shdwTxtColor); text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 0, lang::getText(17), shdwTxtColor);
text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 1, lang::getText(18), shdwTxtColor); text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 1, lang::getText(18), shdwTxtColor);
text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 2, lang::getText(19), shdwTxtColor); text->writeShadowed(anchorItem + despX, anchor3 + spaceBetweenItemLines * 2, lang::getText(19), shdwTxtColor);
@@ -193,7 +193,7 @@ void Instructions::fillTexture()
// Da valor a la variable // Da valor a la variable
spritePos.x = anchorItem; spritePos.x = anchorItem;
spritePos.y = anchor3 - ((param.game.itemSize - text->getCharacterSize()) / 2); spritePos.y = anchor3 - ((param.game.item_size - text->getCharacterSize()) / 2);
} }
// Rellena el backbuffer // Rellena el backbuffer

View File

@@ -14,7 +14,7 @@
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SmartSprite
#include "text.h" // for Text #include "text.h" // for Text
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for paramGame_t, param_t, zone_t, BLOCK #include "utils.h" // for ParamGame, Param, Zone, BLOCK
#include "writer.h" // for Writer #include "writer.h" // for Writer
struct JA_Music_t; struct JA_Music_t;
@@ -44,13 +44,13 @@ Intro::Intro(JA_Music_t *music)
ss->setWidth(128); ss->setWidth(128);
ss->setHeight(96); ss->setHeight(96);
ss->setFinishedCounter(20); ss->setFinishedCounter(20);
ss->setDestX(param.game.gameArea.centerX - 64); ss->setDestX(param.game.game_area.centerX - 64);
ss->setDestY(param.game.gameArea.firstQuarterY - 24); ss->setDestY(param.game.game_area.firstQuarterY - 24);
bitmaps.push_back(std::move(ss)); bitmaps.push_back(std::move(ss));
} }
bitmaps[0]->setPosX(-128); bitmaps[0]->setPosX(-128);
bitmaps[0]->setPosY(param.game.gameArea.firstQuarterY - 24); bitmaps[0]->setPosY(param.game.game_area.firstQuarterY - 24);
bitmaps[0]->setVelX(0.0f); bitmaps[0]->setVelX(0.0f);
bitmaps[0]->setVelY(0.0f); bitmaps[0]->setVelY(0.0f);
bitmaps[0]->setAccelX(0.6f); bitmaps[0]->setAccelX(0.6f);
@@ -58,14 +58,14 @@ Intro::Intro(JA_Music_t *music)
bitmaps[0]->setSpriteClip(0, 0, 128, 96); bitmaps[0]->setSpriteClip(0, 0, 128, 96);
bitmaps[1]->setPosX(param.game.width); bitmaps[1]->setPosX(param.game.width);
bitmaps[1]->setPosY(param.game.gameArea.firstQuarterY - 24); bitmaps[1]->setPosY(param.game.game_area.firstQuarterY - 24);
bitmaps[1]->setVelX(-1.0f); bitmaps[1]->setVelX(-1.0f);
bitmaps[1]->setVelY(0.0f); bitmaps[1]->setVelY(0.0f);
bitmaps[1]->setAccelX(-0.3f); bitmaps[1]->setAccelX(-0.3f);
bitmaps[1]->setAccelY(0.0f); bitmaps[1]->setAccelY(0.0f);
bitmaps[1]->setSpriteClip(128, 0, 128, 96); bitmaps[1]->setSpriteClip(128, 0, 128, 96);
bitmaps[2]->setPosX(param.game.gameArea.centerX - 64); bitmaps[2]->setPosX(param.game.game_area.centerX - 64);
bitmaps[2]->setPosY(-96); bitmaps[2]->setPosY(-96);
bitmaps[2]->setVelX(0.0f); bitmaps[2]->setVelX(0.0f);
bitmaps[2]->setVelY(3.0f); bitmaps[2]->setVelY(3.0f);
@@ -74,7 +74,7 @@ Intro::Intro(JA_Music_t *music)
bitmaps[2]->setSpriteClip(0, 96, 128, 96); bitmaps[2]->setSpriteClip(0, 96, 128, 96);
bitmaps[2]->setFinishedCounter(250); bitmaps[2]->setFinishedCounter(250);
bitmaps[3]->setPosX(param.game.gameArea.centerX - 64); bitmaps[3]->setPosX(param.game.game_area.centerX - 64);
bitmaps[3]->setPosY(param.game.height); bitmaps[3]->setPosY(param.game.height);
bitmaps[3]->setVelX(0.0f); bitmaps[3]->setVelX(0.0f);
bitmaps[3]->setVelY(-0.7f); bitmaps[3]->setVelY(-0.7f);
@@ -82,7 +82,7 @@ Intro::Intro(JA_Music_t *music)
bitmaps[3]->setAccelY(0.0f); bitmaps[3]->setAccelY(0.0f);
bitmaps[3]->setSpriteClip(128, 96, 128, 96); bitmaps[3]->setSpriteClip(128, 96, 128, 96);
bitmaps[4]->setPosX(param.game.gameArea.centerX - 64); bitmaps[4]->setPosX(param.game.game_area.centerX - 64);
bitmaps[4]->setPosY(-96); bitmaps[4]->setPosY(-96);
bitmaps[4]->setVelX(0.0f); bitmaps[4]->setVelX(0.0f);
bitmaps[4]->setVelY(3.0f); bitmaps[4]->setVelY(3.0f);
@@ -91,7 +91,7 @@ Intro::Intro(JA_Music_t *music)
bitmaps[4]->setSpriteClip(0, 192, 128, 96); bitmaps[4]->setSpriteClip(0, 192, 128, 96);
bitmaps[5]->setPosX(param.game.width); bitmaps[5]->setPosX(param.game.width);
bitmaps[5]->setPosY(param.game.gameArea.firstQuarterY - 24); bitmaps[5]->setPosY(param.game.game_area.firstQuarterY - 24);
bitmaps[5]->setVelX(-0.7f); bitmaps[5]->setVelX(-0.7f);
bitmaps[5]->setVelY(0.0f); bitmaps[5]->setVelY(0.0f);
bitmaps[5]->setAccelX(0.0f); bitmaps[5]->setAccelX(0.0f);
@@ -149,7 +149,7 @@ Intro::Intro(JA_Music_t *music)
for (auto &text : texts) for (auto &text : texts)
{ {
text->center(param.game.gameArea.centerX); text->center(param.game.game_area.centerX);
} }
} }

View File

@@ -48,9 +48,9 @@ void Item::allignTo(int x)
{ {
posX = float(x - (width / 2)); posX = float(x - (width / 2));
if (posX < param.game.playArea.rect.x) if (posX < param.game.play_area.rect.x)
{ {
posX = param.game.playArea.rect.x + 1; posX = param.game.play_area.rect.x + 1;
} }
else if ((posX + width) > playArea->w) else if ((posX + width) > playArea->w)
{ {
@@ -95,7 +95,7 @@ void Item::move()
velY += accelY; velY += accelY;
// Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido // Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
if ((posX < param.game.playArea.rect.x) || (posX + width > playArea->w)) if ((posX < param.game.play_area.rect.x) || (posX + width > playArea->w))
{ {
// Corregir posición // Corregir posición
posX -= velX; posX -= velX;
@@ -105,10 +105,10 @@ void Item::move()
} }
// Si se sale por arriba rebota (excepto la maquina de café) // Si se sale por arriba rebota (excepto la maquina de café)
if ((posY < param.game.playArea.rect.y) && !(kind == ITEM_COFFEE_MACHINE)) if ((posY < param.game.play_area.rect.y) && !(kind == ITEM_COFFEE_MACHINE))
{ {
// Corrige // Corrige
posY = param.game.playArea.rect.y; posY = param.game.play_area.rect.y;
// Invierte el sentido // Invierte el sentido
velY = -velY; velY = -velY;
@@ -203,7 +203,7 @@ bool Item::isEnabled()
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Item::getCollider() Circle &Item::getCollider()
{ {
return collider; return collider;
} }

View File

@@ -1,11 +1,11 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_stdinc.h> // for Uint16 #include <SDL2/SDL_stdinc.h> // for Uint16
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include <memory>
#include "utils.h" // for circle_t #include "utils.h" // for Circle
#include "animated_sprite.h" #include "animated_sprite.h"
#include "texture.h" #include "texture.h"
@@ -37,8 +37,8 @@ private:
bool floorCollision; // Indica si el objeto colisiona con el suelo bool floorCollision; // Indica si el objeto colisiona con el suelo
int kind; // Especifica el tipo de objeto que es int kind; // Especifica el tipo de objeto que es
bool enabled; // Especifica si el objeto está habilitado bool enabled; // Especifica si el objeto está habilitado
circle_t collider; // Circulo de colisión del objeto Circle collider; // Circulo de colisión del objeto
SDL_Rect *playArea; // Rectangulo con la zona de juego SDL_Rect *playArea; // Rectangulo con la zona de juego
// Alinea el circulo de colisión con la posición del objeto // Alinea el circulo de colisión con la posición del objeto
void shiftColliders(); void shiftColliders();
@@ -92,7 +92,7 @@ public:
bool isEnabled(); bool isEnabled();
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); Circle &getCollider();
// Informa si el objeto ha colisionado con el suelo // Informa si el objeto ha colisionado con el suelo
bool isOnFloor(); bool isOnFloor();

View File

@@ -34,8 +34,8 @@ Logo::Logo()
endLogo_cm = 400; endLogo_cm = 400;
postLogoDuration = 20; postLogoDuration = 20;
speed = 8; speed = 8;
dest.x = param.game.gameArea.centerX - jailTexture->getWidth() / 2; dest.x = param.game.game_area.centerX - jailTexture->getWidth() / 2;
dest.y = param.game.gameArea.centerY - jailTexture->getHeight() / 2; dest.y = param.game.game_area.centerY - jailTexture->getHeight() / 2;
sinceSprite->setPosY(dest.y + jailTexture->getHeight() + 5); sinceSprite->setPosY(dest.y + jailTexture->getHeight() + 5);
sinceSprite->setSpriteClip(0, 0, sinceTexture->getWidth(), sinceTexture->getHeight()); sinceSprite->setSpriteClip(0, 0, sinceTexture->getWidth(), sinceTexture->getHeight());
sinceSprite->setEnabled(false); sinceSprite->setEnabled(false);
@@ -147,29 +147,28 @@ void Logo::updateJAILGAMES()
// Gestiona el color de las texturas // Gestiona el color de las texturas
void Logo::updateTextureColors() void Logo::updateTextureColors()
{ {
constexpr int inc = 4; constexpr int inc = 4;
// Manejo de 'sinceTexture' // Manejo de 'sinceTexture'
for (int i = 0; i <= 7; ++i) for (int i = 0; i <= 7; ++i)
{ {
if (counter == showSinceSprite_cm + inc * i) if (counter == showSinceSprite_cm + inc * i)
{ {
sinceTexture->setColor(color[i].r, color[i].g, color[i].b); sinceTexture->setColor(color[i].r, color[i].g, color[i].b);
} }
} }
// Manejo de 'jailTexture' y 'sinceTexture' en el fade // Manejo de 'jailTexture' y 'sinceTexture' en el fade
for (int i = 0; i <= 6; ++i) for (int i = 0; i <= 6; ++i)
{ {
if (counter == initFade_cm + inc * i) if (counter == initFade_cm + inc * i)
{ {
jailTexture->setColor(color[6 - i].r, color[6 - i].g, color[6 - i].b); jailTexture->setColor(color[6 - i].r, color[6 - i].g, color[6 - i].b);
sinceTexture->setColor(color[6 - i].r, color[6 - i].g, color[6 - i].b); sinceTexture->setColor(color[6 - i].r, color[6 - i].g, color[6 - i].b);
} }
} }
} }
// Actualiza las variables // Actualiza las variables
void Logo::update() void Logo::update()
{ {

View File

@@ -5,7 +5,7 @@
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include <memory>
#include "utils.h" // for color_t #include "utils.h" // for Color
#include "sprite.h" #include "sprite.h"
#include "texture.h" #include "texture.h"
@@ -28,16 +28,16 @@ private:
std::vector<std::unique_ptr<Sprite>> jailSprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES std::vector<std::unique_ptr<Sprite>> jailSprite; // Vector con los sprites de cada linea que forman el bitmap JAILGAMES
// Variables // Variables
std::vector<color_t> color; // Vector con los colores para el fade std::vector<Color> color; // Vector con los colores para el fade
int counter; // Contador int counter; // Contador
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int showSinceSprite_cm; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998" int showSinceSprite_cm; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
int initFade_cm; // Tiempo del contador cuando inicia el fade a negro int initFade_cm; // Tiempo del contador cuando inicia el fade a negro
int endLogo_cm; // Tiempo del contador para terminar el logo int endLogo_cm; // Tiempo del contador para terminar el logo
int postLogoDuration; // Tiempo que dura el logo con el fade al maximo int postLogoDuration; // Tiempo que dura el logo con el fade al maximo
int speed; // Velocidad de desplazamiento de cada linea int speed; // Velocidad de desplazamiento de cada linea
SDL_Point dest; // Posición X donde dibujar el logo SDL_Point dest; // Posición X donde dibujar el logo
// Actualiza las variables // Actualiza las variables
void update(); void update();

View File

@@ -4,13 +4,12 @@
#include <stdlib.h> // for free, malloc #include <stdlib.h> // for free, malloc
#include <algorithm> // for sort #include <algorithm> // for sort
#include <iostream> // for basic_ostream, char_traits, operator<< #include <iostream> // for basic_ostream, char_traits, operator<<
#include "utils.h" // for hiScoreEntry_t #include "utils.h" // for HiScoreEntry
// Constructor // Constructor
ManageHiScoreTable::ManageHiScoreTable(std::vector<hiScoreEntry_t> *table) ManageHiScoreTable::ManageHiScoreTable(std::vector<HiScoreEntry> *table)
: table(table) {} : table(table) {}
// Resetea la tabla a los valores por defecto // Resetea la tabla a los valores por defecto
void ManageHiScoreTable::clear() void ManageHiScoreTable::clear()
{ {
@@ -31,7 +30,7 @@ void ManageHiScoreTable::clear()
} }
// Añade un elemento a la tabla // Añade un elemento a la tabla
void ManageHiScoreTable::add(hiScoreEntry_t entry) void ManageHiScoreTable::add(HiScoreEntry entry)
{ {
// Añade la entrada a la tabla // Añade la entrada a la tabla
table->push_back(entry); table->push_back(entry);
@@ -51,7 +50,7 @@ void ManageHiScoreTable::sort()
{ {
struct struct
{ {
bool operator()(hiScoreEntry_t a, hiScoreEntry_t b) const { return a.score > b.score; } bool operator()(HiScoreEntry a, HiScoreEntry b) const { return a.score > b.score; }
} customLess; } customLess;
std::sort(table->begin(), table->end(), customLess); std::sort(table->begin(), table->end(), customLess);

View File

@@ -1,13 +1,13 @@
#pragma once #pragma once
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
struct hiScoreEntry_t; struct HiScoreEntry;
/* /*
Esta clase sirve para añadir elementos hiScoreEntry_r a un vector (tabla), de manera Esta clase sirve para añadir elementos hiScoreEntry_r a un vector (tabla), de manera
que la tabla siempre está ordenada. que la tabla siempre está ordenada.
Además tiene un método para dejar la tabla con sus valores iniciales y métodos para Además tiene un método para dejar la tabla con sus valores iniciales y métodos para
leer y escribir la tabla a un fichero leer y escribir la tabla a un fichero
*/ */
@@ -17,14 +17,14 @@ class ManageHiScoreTable
{ {
private: private:
// Variables // Variables
std::vector<hiScoreEntry_t> *table; // Tabla con los records std::vector<HiScoreEntry> *table; // Tabla con los records
// Ordena la tabla // Ordena la tabla
void sort(); void sort();
public: public:
// Constructor // Constructor
ManageHiScoreTable(std::vector<hiScoreEntry_t> *table); ManageHiScoreTable(std::vector<HiScoreEntry> *table);
// Destructor // Destructor
~ManageHiScoreTable() = default; ~ManageHiScoreTable() = default;
@@ -33,7 +33,7 @@ public:
void clear(); void clear();
// Añade un elemento a la tabla // Añade un elemento a la tabla
void add(hiScoreEntry_t entry); void add(HiScoreEntry entry);
// Carga la tabla con los datos de un fichero // Carga la tabla con los datos de un fichero
bool loadFromFile(std::string filePath); bool loadFromFile(std::string filePath);

View File

@@ -265,7 +265,7 @@ void Notify::showText(std::string text1, std::string text2, int icon)
} }
// Escribe el texto de la notificación // Escribe el texto de la notificación
color_t color = {255, 255, 255}; Color color = {255, 255, 255};
if (numTexts == 2) if (numTexts == 2)
{ // Dos lineas de texto { // Dos lineas de texto
text->writeColored(paddingIn + iconSpace, paddingIn, text1, color); text->writeColored(paddingIn + iconSpace, paddingIn, text1, color);

View File

@@ -5,7 +5,7 @@
#include <string> // for basic_string, string #include <string> // for basic_string, string
#include <vector> // for vector #include <vector> // for vector
#include <memory> #include <memory>
#include "utils.h" // for color_t #include "utils.h" // for Color
#include "text.h" #include "text.h"
#include "texture.h" #include "texture.h"
#include "sprite.h" #include "sprite.h"
@@ -62,7 +62,7 @@ private:
std::unique_ptr<Text> text; // Objeto para dibujar texto std::unique_ptr<Text> text; // Objeto para dibujar texto
// Variables // Variables
color_t bgColor; // Color de fondo de las notificaciones Color bgColor; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación int waitTime; // Tiempo que se ve la notificación
std::vector<Notification> notifications; // La lista de notificaciones activas std::vector<Notification> notifications; // La lista de notificaciones activas
JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación

View File

@@ -10,7 +10,7 @@
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "text.h" // for Text #include "text.h" // for Text
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for easeInOutSine, paramGame_t, param_t #include "utils.h" // for easeInOutSine, ParamGame, Param
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado // [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
OnScreenHelp *OnScreenHelp::onScreenHelp = nullptr; OnScreenHelp *OnScreenHelp::onScreenHelp = nullptr;

View File

@@ -7,10 +7,10 @@
#include "input.h" // for inputs_e, INPUT_USE_ANY, INPUT_... #include "input.h" // for inputs_e, INPUT_USE_ANY, INPUT_...
#include "lang.h" // for lang_e #include "lang.h" // for lang_e
#include "screen.h" // for ScreenVideoMode, ScreenFilter #include "screen.h" // for ScreenVideoMode, ScreenFilter
#include "utils.h" // for op_controller_t, options_t, op_... #include "utils.h" // for OptionsController, Options, op_...
// Variables // Variables
options_t options; Options options;
// Declaraciones // Declaraciones
bool setOptions(std::string var, std::string value); bool setOptions(std::string var, std::string value);
@@ -34,7 +34,7 @@ void initOptions()
options.notification.posV = pos_top; options.notification.posV = pos_top;
options.notification.posH = pos_left; options.notification.posH = pos_left;
options.notification.sound = false; options.notification.sound = false;
options.notification.color = (color_t){48, 48, 48}; options.notification.color = (Color){48, 48, 48};
// Opciones de audio // Opciones de audio
options.audio.music.enabled = true; options.audio.music.enabled = true;
@@ -49,7 +49,7 @@ void initOptions()
// Opciones de control // Opciones de control
options.controller.clear(); options.controller.clear();
op_controller_t c; OptionsController c;
const int numPlayers = 2; const int numPlayers = 2;
for (int index = 0; index < numPlayers; ++index) for (int index = 0; index < numPlayers; ++index)

View File

@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <string> // for string #include <string> // for string
struct options_t; struct Options;
// Variables // Variables
extern options_t options; extern Options options;
// Carga el fichero de configuración // Carga el fichero de configuración
bool loadOptionsFile(std::string filePath); bool loadOptionsFile(std::string filePath);

View File

@@ -1,9 +1,9 @@
#include "param.h" #include "param.h"
#include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi... #include <fstream> // for char_traits, basic_ostream, basic_ifstream, basi...
#include <iostream> // for cout #include <iostream> // for cout
#include "utils.h" // for param_t, paramGame_t, zone_t, paramBalloon_t #include "utils.h" // for Param, ParamGame, Zone, ParamBalloon
param_t param; Param param;
// Asigna variables a partir de dos cadenas // Asigna variables a partir de dos cadenas
bool setParams(std::string var, std::string value); bool setParams(std::string var, std::string value);
@@ -17,41 +17,41 @@ void initParam()
// GAME // GAME
param.game.width = 320; param.game.width = 320;
param.game.height = 256; param.game.height = 256;
param.game.itemSize = 20; param.game.item_size = 20;
param.game.gameArea.rect = {0, 0, param.game.width, param.game.height}; param.game.game_area.rect = {0, 0, param.game.width, param.game.height};
param.game.playArea.rect = {0, 0, param.game.width, 216}; param.game.play_area.rect = {0, 0, param.game.width, 216};
precalculateZones(); precalculateZones();
// SCOREBOARD // SCOREBOARD
param.scoreboard = {0, 216, param.game.width, 40}; param.scoreboard = {0, 216, param.game.width, 40};
// FADE // FADE
param.fade.numSquaresWidth = param.game.width / 2; param.fade.num_squares_width = param.game.width / 2;
param.fade.numSquaresHeight = param.game.height / 2; param.fade.num_squares_height = param.game.height / 2;
param.fade.randomSquaresDelay = 1; param.fade.random_squares_delay = 1;
param.fade.randomSquaresMult = 500; param.fade.random_squares_mult = 500;
param.fade.postDuration = 80; param.fade.post_duration = 80;
param.fade.venetianSize = 16; param.fade.venetian_size = 16;
// TITLE // TITLE
param.title.pressStartPosition = 160; param.title.press_start_position = 160;
param.title.titleDuration = 800; param.title.title_duration = 800;
param.title.arcadeEditionPosition = 123; param.title.arcade_edition_position = 123;
param.title.titleCCPosition = 11; param.title.title_c_c_position = 11;
// BACKGROUND // BACKGROUND
param.background.attenuateColor = {255, 255, 255}; param.background.attenuate_color = {255, 255, 255};
param.background.attenuateAlpha = 32; param.background.attenuate_alpha = 32;
// BALLOONS // BALLOONS
param.balloon1.vel = 2.60f; param.balloon_1.vel = 2.60f;
param.balloon1.grav = 0.09f; param.balloon_1.grav = 0.09f;
param.balloon2.vel = 3.50f; param.balloon_2.vel = 3.50f;
param.balloon2.grav = 0.10f; param.balloon_2.grav = 0.10f;
param.balloon3.vel = 4.50f; param.balloon_3.vel = 4.50f;
param.balloon3.grav = 0.10f; param.balloon_3.grav = 0.10f;
param.balloon4.vel = 4.95f; param.balloon_4.vel = 4.95f;
param.balloon4.grav = 0.10f; param.balloon_4.grav = 0.10f;
} }
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
@@ -168,60 +168,60 @@ bool setParams(std::string var, std::string value)
param.game.height = std::stoi(value); param.game.height = std::stoi(value);
} }
else if (var == "game.itemSize") else if (var == "game.item_size")
{ {
param.game.itemSize = std::stoi(value); param.game.item_size = std::stoi(value);
} }
else if (var == "game.playArea.rect.x") else if (var == "game.play_area.rect.x")
{ {
param.game.playArea.rect.x = std::stoi(value); param.game.play_area.rect.x = std::stoi(value);
} }
else if (var == "game.playArea.rect.y") else if (var == "game.play_area.rect.y")
{ {
param.game.playArea.rect.y = std::stoi(value); param.game.play_area.rect.y = std::stoi(value);
} }
else if (var == "game.playArea.rect.w") else if (var == "game.play_area.rect.w")
{ {
param.game.playArea.rect.w = std::stoi(value); param.game.play_area.rect.w = std::stoi(value);
} }
else if (var == "game.playArea.rect.h") else if (var == "game.play_area.rect.h")
{ {
param.game.playArea.rect.h = std::stoi(value); param.game.play_area.rect.h = std::stoi(value);
} }
// FADE // FADE
else if (var == "fade.numSquaresWidth") else if (var == "fade.num_squares_width")
{ {
param.fade.numSquaresWidth = std::stoi(value); param.fade.num_squares_width = std::stoi(value);
} }
else if (var == "fade.numSquaresHeight") else if (var == "fade.num_squares_height")
{ {
param.fade.numSquaresHeight = std::stoi(value); param.fade.num_squares_height = std::stoi(value);
} }
else if (var == "fade.randomSquaresDelay") else if (var == "fade.random_squares_delay")
{ {
param.fade.randomSquaresDelay = std::stoi(value); param.fade.random_squares_delay = std::stoi(value);
} }
else if (var == "fade.randomSquaresMult") else if (var == "fade.random_squares_mult")
{ {
param.fade.randomSquaresMult = std::stoi(value); param.fade.random_squares_mult = std::stoi(value);
} }
else if (var == "fade.postDuration") else if (var == "fade.post_duration")
{ {
param.fade.postDuration = std::stoi(value); param.fade.post_duration = std::stoi(value);
} }
else if (var == "fade.venetianSize") else if (var == "fade.venetian_size")
{ {
param.fade.venetianSize = std::stoi(value); param.fade.venetian_size = std::stoi(value);
} }
// SCOREBOARD // SCOREBOARD
@@ -246,86 +246,86 @@ bool setParams(std::string var, std::string value)
} }
// TITLE // TITLE
else if (var == "title.pressStartPosition") else if (var == "title.press_start_position")
{ {
param.title.pressStartPosition = std::stoi(value); param.title.press_start_position = std::stoi(value);
} }
else if (var == "title.titleDuration") else if (var == "title.title_duration")
{ {
param.title.titleDuration = std::stoi(value); param.title.title_duration = std::stoi(value);
} }
else if (var == "title.arcadeEditionPosition") else if (var == "title.arcade_edition_position")
{ {
param.title.arcadeEditionPosition = std::stoi(value); param.title.arcade_edition_position = std::stoi(value);
} }
else if (var == "title.titleCCPosition") else if (var == "title.title_c_c_position")
{ {
param.title.titleCCPosition = std::stoi(value); param.title.title_c_c_position = std::stoi(value);
} }
// BACKGROUND // BACKGROUND
else if (var == "background.attenuateColor.r") else if (var == "background.attenuate_color.r")
{ {
param.background.attenuateColor.r = std::stoi(value); param.background.attenuate_color.r = std::stoi(value);
} }
else if (var == "background.attenuateColor.g") else if (var == "background.attenuate_color.g")
{ {
param.background.attenuateColor.g = std::stoi(value); param.background.attenuate_color.g = std::stoi(value);
} }
else if (var == "background.attenuateColor.b") else if (var == "background.attenuate_color.b")
{ {
param.background.attenuateColor.b = std::stoi(value); param.background.attenuate_color.b = std::stoi(value);
} }
else if (var == "background.attenuateAlpha") else if (var == "background.attenuate_alpha")
{ {
param.background.attenuateAlpha = std::stoi(value); param.background.attenuate_alpha = std::stoi(value);
} }
// BALLOON // BALLOON
else if (var == "balloon1.vel") else if (var == "balloon_1.vel")
{ {
param.balloon1.vel = std::stof(value); param.balloon_1.vel = std::stof(value);
} }
else if (var == "balloon1.grav") else if (var == "balloon_1.grav")
{ {
param.balloon1.grav = std::stof(value); param.balloon_1.grav = std::stof(value);
} }
else if (var == "balloon2.vel") else if (var == "balloon_2.vel")
{ {
param.balloon2.vel = std::stof(value); param.balloon_2.vel = std::stof(value);
} }
else if (var == "balloon2.grav") else if (var == "balloon_2.grav")
{ {
param.balloon2.grav = std::stof(value); param.balloon_2.grav = std::stof(value);
} }
else if (var == "balloon3.vel") else if (var == "balloon_3.vel")
{ {
param.balloon3.vel = std::stof(value); param.balloon_3.vel = std::stof(value);
} }
else if (var == "balloon3.grav") else if (var == "balloon_3.grav")
{ {
param.balloon3.grav = std::stof(value); param.balloon_3.grav = std::stof(value);
} }
else if (var == "balloon4.vel") else if (var == "balloon_4.vel")
{ {
param.balloon4.vel = std::stof(value); param.balloon_4.vel = std::stof(value);
} }
else if (var == "balloon4.grav") else if (var == "balloon_4.grav")
{ {
param.balloon4.grav = std::stof(value); param.balloon_4.grav = std::stof(value);
} }
// RESTO // RESTO
@@ -341,19 +341,19 @@ bool setParams(std::string var, std::string value)
void precalculateZones() void precalculateZones()
{ {
// playArea // playArea
param.game.playArea.centerX = param.game.playArea.rect.w / 2; param.game.play_area.center_x = param.game.play_area.rect.w / 2;
param.game.playArea.firstQuarterX = param.game.playArea.rect.w / 4; param.game.play_area.first_quarter_x = param.game.play_area.rect.w / 4;
param.game.playArea.thirdQuarterX = param.game.playArea.rect.w / 4 * 3; param.game.play_area.third_quarter_x = param.game.play_area.rect.w / 4 * 3;
param.game.playArea.centerY = param.game.playArea.rect.h / 2; param.game.play_area.center_y = param.game.play_area.rect.h / 2;
param.game.playArea.firstQuarterY = param.game.playArea.rect.h / 4; param.game.play_area.first_quarter_y = param.game.play_area.rect.h / 4;
param.game.playArea.thirdQuarterY = param.game.playArea.rect.h / 4 * 3; param.game.play_area.third_quarter_y = param.game.play_area.rect.h / 4 * 3;
// gameArea // gameArea
param.game.gameArea.rect = {0, 0, param.game.width, param.game.height}; param.game.game_area.rect = {0, 0, param.game.width, param.game.height};
param.game.gameArea.centerX = param.game.gameArea.rect.w / 2; param.game.game_area.center_x = param.game.game_area.rect.w / 2;
param.game.gameArea.firstQuarterX = param.game.gameArea.rect.w / 4; param.game.game_area.first_quarter_x = param.game.game_area.rect.w / 4;
param.game.gameArea.thirdQuarterX = param.game.gameArea.rect.w / 4 * 3; param.game.game_area.third_quarter_x = param.game.game_area.rect.w / 4 * 3;
param.game.gameArea.centerY = param.game.gameArea.rect.h / 2; param.game.game_area.center_y = param.game.game_area.rect.h / 2;
param.game.gameArea.firstQuarterY = param.game.gameArea.rect.h / 4; param.game.game_area.first_quarter_y = param.game.game_area.rect.h / 4;
param.game.gameArea.thirdQuarterY = param.game.gameArea.rect.h / 4 * 3; param.game.game_area.third_quarter_y = param.game.game_area.rect.h / 4 * 3;
} }

View File

@@ -1,9 +1,9 @@
#pragma once #pragma once
#include <string> // for string #include <string> // for string
struct param_t; struct Param;
extern param_t param; extern Param param;
// Establece valores para los parametros a partir de un fichero de texto // Establece valores para los parametros a partir de un fichero de texto
void loadParamsFromFile(std::string filePath); void loadParamsFromFile(std::string file_path);

View File

@@ -168,7 +168,7 @@ void Player::move()
posX += velX; posX += velX;
// Si el jugador abandona el area de juego por los laterales // Si el jugador abandona el area de juego por los laterales
if ((posX < param.game.playArea.rect.x - 5) || (posX + width > playArea->w + 5)) if ((posX < param.game.play_area.rect.x - 5) || (posX + width > playArea->w + 5))
{ {
// Restaura su posición // Restaura su posición
posX -= velX; posX -= velX;
@@ -185,7 +185,7 @@ void Player::move()
playerSprite->update(); playerSprite->update();
// Si el cadaver abandona el area de juego por los laterales // Si el cadaver abandona el area de juego por los laterales
if ((playerSprite->getPosX() < param.game.playArea.rect.x) || (playerSprite->getPosX() + width > playArea->w)) if ((playerSprite->getPosX() < param.game.play_area.rect.x) || (playerSprite->getPosX() + width > playArea->w))
{ {
// Restaura su posición // Restaura su posición
const float vx = playerSprite->getVelX(); const float vx = playerSprite->getVelX();
@@ -196,7 +196,7 @@ void Player::move()
} }
// Si el cadaver abandona el area de juego por abajo // Si el cadaver abandona el area de juego por abajo
if (playerSprite->getPosY() > param.game.playArea.rect.h) if (playerSprite->getPosY() > param.game.play_area.rect.h)
{ {
setStatusPlaying(PlayerStatus::DIED); setStatusPlaying(PlayerStatus::DIED);
} }
@@ -666,7 +666,7 @@ int Player::getCoffees() const
} }
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &Player::getCollider() Circle &Player::getCollider()
{ {
return collider; return collider;
} }

View File

@@ -7,8 +7,8 @@
#include <vector> // for vector #include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for AnimatedSprite
#include "enter_name.h" // for EnterName #include "enter_name.h" // for EnterName
#include "utils.h" // for circle_t #include "utils.h" // for Circle
#include "texture.h" // lines 12-12 #include "texture.h" // lines 12-12
enum class ScoreboardMode; enum class ScoreboardMode;
// Estados del jugador // Estados del jugador
@@ -71,7 +71,7 @@ private:
int powerUpCounter; // Temporizador para el modo PowerUp int powerUpCounter; // Temporizador para el modo PowerUp
int powerUpDespX; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador int powerUpDespX; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
bool input; // Indica si puede recibir ordenes de entrada bool input; // Indica si puede recibir ordenes de entrada
circle_t collider; // Circulo de colisión del jugador Circle collider; // Circulo de colisión del jugador
int continueCounter; // Contador para poder continuar int continueCounter; // Contador para poder continuar
Uint32 continueTicks; // Variable para poder cambiar el contador de continue en función del tiempo Uint32 continueTicks; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreBoardPanel; // Panel del marcador asociado al jugador int scoreBoardPanel; // Panel del marcador asociado al jugador
@@ -256,7 +256,7 @@ public:
int getCoffees() const; int getCoffees() const;
// Obtiene el circulo de colisión // Obtiene el circulo de colisión
circle_t &getCollider(); Circle &getCollider();
// Obtiene el valor de la variable // Obtiene el valor de la variable
int getContinueCounter() const; int getContinueCounter() const;

View File

@@ -190,7 +190,7 @@ void Scoreboard::setHiScoreName(std::string name)
} }
// Establece el valor de la variable // Establece el valor de la variable
void Scoreboard::setColor(color_t color) void Scoreboard::setColor(Color color)
{ {
this->color = color; this->color = color;
fillBackgroundTexture(); fillBackgroundTexture();

View File

@@ -6,10 +6,10 @@
#include <memory> // for unique_ptr #include <memory> // for unique_ptr
#include <string> // for string, basic_string #include <string> // for string, basic_string
#include <vector> // for vector #include <vector> // for vector
#include "utils.h" // for color_t #include "utils.h" // for Color
#include "sprite.h" // lines 11-11 #include "sprite.h" // lines 11-11
#include "text.h" // lines 12-12 #include "text.h" // lines 12-12
#include "texture.h" // lines 13-13 #include "texture.h" // lines 13-13
// Defines // Defines
constexpr int SCOREBOARD_LEFT_PANEL = 0; constexpr int SCOREBOARD_LEFT_PANEL = 0;
@@ -66,7 +66,7 @@ private:
int hiScore; // Máxima puntuación int hiScore; // Máxima puntuación
float power; // Poder actual de la fase float power; // Poder actual de la fase
std::string hiScoreName; // Nombre del jugador con la máxima puntuación std::string hiScoreName; // Nombre del jugador con la máxima puntuación
color_t color; // Color del marcador Color color; // Color del marcador
SDL_Rect rect; // Posición y dimensiones del marcador SDL_Rect rect; // Posición y dimensiones del marcador
panel_t panel[SCOREBOARD_MAX_PANELS]; // Lista con todos los paneles del marcador panel_t panel[SCOREBOARD_MAX_PANELS]; // Lista con todos los paneles del marcador
Uint32 ticks; // Variable donde almacenar el valor de SDL_GetTiks() Uint32 ticks; // Variable donde almacenar el valor de SDL_GetTiks()
@@ -155,7 +155,7 @@ public:
void setHiScoreName(std::string name); void setHiScoreName(std::string name);
// Establece el valor de la variable // Establece el valor de la variable
void setColor(color_t color); void setColor(Color color);
// Establece el valor de la variable // Establece el valor de la variable
void setPos(SDL_Rect rect); void setPos(SDL_Rect rect);

View File

@@ -104,7 +104,7 @@ Screen::~Screen()
} }
// Limpia la pantalla // Limpia la pantalla
void Screen::clean(color_t color) void Screen::clean(Color color)
{ {
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF); SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, 0xFF);
SDL_RenderClear(renderer); SDL_RenderClear(renderer);
@@ -272,7 +272,7 @@ void Screen::incWindowSize()
} }
// Cambia el color del borde // Cambia el color del borde
void Screen::setBorderColor(color_t color) void Screen::setBorderColor(Color color)
{ {
borderColor = color; borderColor = color;
} }
@@ -405,7 +405,7 @@ void Screen::updateShake()
} }
// Pone la pantalla de color // Pone la pantalla de color
void Screen::flash(color_t color, int lenght) void Screen::flash(Color color, int lenght)
{ {
flashEffect.enabled = true; flashEffect.enabled = true;
flashEffect.counter = 0; flashEffect.counter = 0;

View File

@@ -6,7 +6,7 @@
#include <SDL2/SDL_stdinc.h> // for Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <SDL2/SDL_video.h> // for SDL_Window #include <SDL2/SDL_video.h> // for SDL_Window
#include <string> // for basic_string, string #include <string> // for basic_string, string
#include "utils.h" // for color_t #include "utils.h" // for Color
#include <memory> #include <memory>
class Asset; class Asset;
class Input; class Input;
@@ -42,7 +42,7 @@ private:
// Variables // Variables
SDL_Rect srcrect; // Coordenadas de donde va a pillar la textura del juego para dibujarla SDL_Rect srcrect; // Coordenadas de donde va a pillar la textura del juego para dibujarla
SDL_Rect dstrect; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana SDL_Rect dstrect; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
color_t borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla Color borderColor; // Color del borde añadido a la textura de juego para rellenar la pantalla
bool attenuateEffect; // Indica si la pantalla ha de estar atenuada bool attenuateEffect; // Indica si la pantalla ha de estar atenuada
Uint32 fpsTicks; // Ticks para contar los frames por segundo Uint32 fpsTicks; // Ticks para contar los frames por segundo
int fpsCounter; // Contador de frames por segundo int fpsCounter; // Contador de frames por segundo
@@ -52,10 +52,10 @@ private:
struct effect_t struct effect_t
{ {
bool enabled; // Indica si el efecto está activo bool enabled; // Indica si el efecto está activo
int counter; // Contador para el efecto int counter; // Contador para el efecto
int lenght; // Duración del efecto int lenght; // Duración del efecto
color_t color; // Color del efecto Color color; // Color del efecto
}; };
// Variables - Efectos // Variables - Efectos
@@ -113,7 +113,7 @@ public:
void checkInput(); void checkInput();
// Limpia la pantalla // Limpia la pantalla
void clean(color_t color = {0x00, 0x00, 0x00}); void clean(Color color = {0x00, 0x00, 0x00});
// Prepara para empezar a dibujar en la textura de juego // Prepara para empezar a dibujar en la textura de juego
void start(); void start();
@@ -137,7 +137,7 @@ public:
void incWindowSize(); void incWindowSize();
// Cambia el color del borde // Cambia el color del borde
void setBorderColor(color_t color); void setBorderColor(Color color);
// Cambia el tipo de mezcla // Cambia el tipo de mezcla
void setBlendMode(SDL_BlendMode blendMode); void setBlendMode(SDL_BlendMode blendMode);
@@ -146,7 +146,7 @@ public:
void shake(); void shake();
// Pone la pantalla de color // Pone la pantalla de color
void flash(color_t color, int lenght); void flash(Color color, int lenght);
// Activa/desactiva los shaders // Activa/desactiva los shaders
void switchShaders(); void switchShaders();

View File

@@ -3,7 +3,7 @@
#include <iostream> // for cout #include <iostream> // for cout
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for color_t #include "utils.h" // for Color
// Llena una estructuta textFile_t desde un fichero // Llena una estructuta textFile_t desde un fichero
textFile_t LoadTextFile(std::string file) textFile_t LoadTextFile(std::string file)
@@ -167,7 +167,7 @@ void Text::write(int x, int y, std::string text, int kerning, int lenght)
} }
// Escribe el texto con colores // Escribe el texto con colores
void Text::writeColored(int x, int y, std::string text, color_t color, int kerning, int lenght) void Text::writeColored(int x, int y, std::string text, Color color, int kerning, int lenght)
{ {
sprite->getTexture()->setColor(color.r, color.g, color.b); sprite->getTexture()->setColor(color.r, color.g, color.b);
write(x, y, text, kerning, lenght); write(x, y, text, kerning, lenght);
@@ -175,7 +175,7 @@ void Text::writeColored(int x, int y, std::string text, color_t color, int kerni
} }
// 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, std::string text, Color 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);
@@ -191,7 +191,7 @@ void Text::writeCentered(int x, int y, std::string text, int kerning, int 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, std::string text, int kerning, Color textColor, Uint8 shadowDistance, Color 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);

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_stdinc.h> // for Uint8 #include <SDL2/SDL_stdinc.h> // for Uint8
#include <string> // for string #include <string> // for string
#include <memory> #include <memory>
#include "utils.h" #include "utils.h"
#include "sprite.h" #include "sprite.h"
@@ -55,16 +55,16 @@ public:
void write(int x, int y, std::string text, int kerning = 1, int lenght = -1); void write(int x, int y, 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, std::string text, Color color, int kerning = 1, int lenght = -1);
// Escribe el texto con sombra // Escribe el texto con sombra
void writeShadowed(int x, int y, std::string text, color_t color, Uint8 shadowDistance = 1, int kerning = 1, int lenght = -1); void writeShadowed(int x, int y, std::string text, Color 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, 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 = {255, 255, 255}, Uint8 shadowDistance = 1, color_t shadowColor = {0, 0, 0}, int lenght = -1); void writeDX(Uint8 flags, int x, int y, std::string text, int kerning = 1, Color textColor = {255, 255, 255}, Uint8 shadowDistance = 1, Color shadowColor = {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(std::string text, int kerning = 1);

View File

@@ -36,11 +36,11 @@ Title::Title(JA_Music_t *music)
text2 = std::make_unique<Text>(asset->get("8bithud.png"), asset->get("8bithud.txt"), renderer); text2 = std::make_unique<Text>(asset->get("8bithud.png"), asset->get("8bithud.txt"), renderer);
miniLogoTexture = std::make_shared<Texture>(renderer, asset->get("logo_jailgames_mini.png")); miniLogoTexture = std::make_shared<Texture>(renderer, asset->get("logo_jailgames_mini.png"));
miniLogoSprite = std::make_unique<Sprite>(param.game.gameArea.centerX - miniLogoTexture->getWidth() / 2, 0, miniLogoTexture->getWidth(), miniLogoTexture->getHeight(), miniLogoTexture); miniLogoSprite = std::make_unique<Sprite>(param.game.game_area.centerX - miniLogoTexture->getWidth() / 2, 0, miniLogoTexture->getWidth(), miniLogoTexture->getHeight(), miniLogoTexture);
tiledbg = std::make_unique<Tiledbg>(asset->get("title_bg_tile.png"), (SDL_Rect){0, 0, param.game.width, param.game.height}, TILED_MODE_RANDOM); tiledbg = std::make_unique<Tiledbg>(asset->get("title_bg_tile.png"), (SDL_Rect){0, 0, param.game.width, param.game.height}, TILED_MODE_RANDOM);
gameLogo = std::make_unique<GameLogo>(param.game.gameArea.centerX, param.title.titleCCPosition); gameLogo = std::make_unique<GameLogo>(param.game.game_area.centerX, param.title.titleCCPosition);
gameLogo->enable(); gameLogo->enable();
defineButtons = std::make_unique<DefineButtons>(std::move(text2)); defineButtons = std::make_unique<DefineButtons>(std::move(text2));
@@ -148,12 +148,12 @@ void Title::render()
if (section::options == section::OPTIONS_TITLE_2) if (section::options == section::OPTIONS_TITLE_2)
{ {
constexpr color_t shadow = {0x14, 0x87, 0xc4}; constexpr Color shadow = {0x14, 0x87, 0xc4};
// 'PRESS TO PLAY' // 'PRESS TO PLAY'
if (counter % 50 > 14 && !defineButtons->isEnabled()) if (counter % 50 > 14 && !defineButtons->isEnabled())
{ {
text1->writeDX(TXT_CENTER | TXT_SHADOW, param.game.gameArea.centerX, param.title.pressStartPosition, lang::getText(23), 1, noColor, 1, shadow); text1->writeDX(TXT_CENTER | TXT_SHADOW, param.game.game_area.centerX, param.title.pressStartPosition, lang::getText(23), 1, noColor, 1, shadow);
} }
// Mini logo // Mini logo
@@ -163,7 +163,7 @@ void Title::render()
miniLogoSprite->render(); miniLogoSprite->render();
// Texto con el copyright // Texto con el copyright
text1->writeDX(TXT_CENTER | TXT_SHADOW, param.game.gameArea.centerX, pos2, TEXT_COPYRIGHT, 1, noColor, 1, shadow); text1->writeDX(TXT_CENTER | TXT_SHADOW, param.game.game_area.centerX, pos2, TEXT_COPYRIGHT, 1, noColor, 1, shadow);
} }
// Define Buttons // Define Buttons

View File

@@ -8,7 +8,7 @@
#include "game_logo.h" #include "game_logo.h"
#include "text.h" #include "text.h"
#include "tiled_bg.h" #include "tiled_bg.h"
#include "utils.h" // for section_t #include "utils.h" // for Section
#include "sprite.h" #include "sprite.h"
#include "texture.h" #include "texture.h"
@@ -62,13 +62,13 @@ private:
JA_Music_t *music; // Musica para el titulo JA_Music_t *music; // Musica para el titulo
// Variable // Variable
int counter; // Temporizador para la pantalla de titulo int counter; // Temporizador para la pantalla de titulo
Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa Uint32 ticks; // Contador de ticks para ajustar la velocidad del programa
bool demo; // Indica si el modo demo estará activo bool demo; // Indica si el modo demo estará activo
section_t nextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo Section nextSection; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa Uint32 ticksSpeed; // Velocidad a la que se repiten los bucles del programa
int postFade; // Opción a realizar cuando termina el fundido int postFade; // Opción a realizar cuando termina el fundido
int numControllers; // Número de mandos conectados int numControllers; // Número de mandos conectados
// Inicializa los valores de las variables // Inicializa los valores de las variables
void init(); void init();

View File

@@ -4,39 +4,39 @@
#include <cctype> // for isspace #include <cctype> // for isspace
#include <iterator> // for distance #include <iterator> // for distance
#include <cmath> #include <cmath>
struct JA_Music_t; // lines 3-3 struct JA_Music_t; // lines 3-3
struct JA_Sound_t; // lines 4-4 struct JA_Sound_t; // lines 4-4
// Colores // Colores
const color_t bgColor = {0x27, 0x27, 0x36}; const Color bg_color = {0x27, 0x27, 0x36};
const color_t noColor = {0xFF, 0xFF, 0xFF}; const Color no_color = {0xFF, 0xFF, 0xFF};
const color_t shdwTxtColor = {0x43, 0x43, 0x4F}; const Color shdw_txt_color = {0x43, 0x43, 0x4F};
const color_t separatorColor = {0x0D, 0x1A, 0x2B}; const Color separator_color = {0x0D, 0x1A, 0x2B};
const color_t scoreboardColor = {0x2E, 0x3F, 0x47}; const Color scoreboard_color = {0x2E, 0x3F, 0x47};
const color_t difficultyEasyColor = {0x4B, 0x69, 0x2F}; const Color difficulty_easy_color = {0x4B, 0x69, 0x2F};
const color_t difficultyNormalColor = {0xFF, 0x7A, 0x00}; const Color difficulty_normal_color = {0xFF, 0x7A, 0x00};
const color_t difficultyHardColor = {0x76, 0x42, 0x8A}; const Color difficulty_hard_color = {0x76, 0x42, 0x8A};
const color_t flashColor = {0xFF, 0xFF, 0xFF}; const Color flash_color = {0xFF, 0xFF, 0xFF};
const color_t fadeColor = {0x27, 0x27, 0x36}; const Color fade_color = {0x27, 0x27, 0x36};
const color_t orangeColor = {0xFF, 0x7A, 0x00}; const Color orange_color = {0xFF, 0x7A, 0x00};
// 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)
{ {
const int deltaX = x2 - x1; const int delta_x = x2 - x1;
const int deltaY = y2 - y1; const int delta_y = y2 - y1;
return deltaX * deltaX + deltaY * deltaY; return delta_x * delta_x + delta_y * delta_y;
} }
// Detector de colisiones entre dos circulos // Detector de colisiones entre dos circulos
bool checkCollision(circle_t &a, circle_t &b) bool checkCollision(Circle &a, Circle &b)
{ {
// Calcula el radio total al cuadrado // Calcula el radio total al cuadrado
int totalRadiusSquared = a.r + b.r; int total_radius_squared = a.r + b.r;
totalRadiusSquared = totalRadiusSquared * totalRadiusSquared; total_radius_squared = total_radius_squared * total_radius_squared;
// Si la distancia entre el centro de los circulos es inferior a la suma de sus radios // Si la distancia entre el centro de los circulos es inferior a la suma de sus radios
if (distanceSquared(a.x, a.y, b.x, b.y) < (totalRadiusSquared)) if (distanceSquared(a.x, a.y, b.x, b.y) < (total_radius_squared))
{ {
// Los circulos han colisionado // Los circulos han colisionado
return true; return true;
@@ -47,7 +47,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(Circle &a, SDL_Rect &b)
{ {
// Closest point on collision box // Closest point on collision box
int cX, cY; int cX, cY;
@@ -80,10 +80,10 @@ bool checkCollision(circle_t &a, SDL_Rect &b)
cY = a.y; cY = a.y;
} }
// If the closest point is inside the circle_t // If the closest point is inside the Circle
if (distanceSquared(a.x, a.y, cX, cY) < a.r * a.r) if (distanceSquared(a.x, a.y, cX, cY) < a.r * a.r)
{ {
// This box and the circle_t have collided // This box and the Circle have collided
return true; return true;
} }
@@ -197,7 +197,7 @@ std::string toLower(std::string str)
} }
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<sound_file_t> sounds, std::string name) JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name)
{ {
for (auto s : sounds) for (auto s : sounds)
{ {
@@ -211,7 +211,7 @@ JA_Sound_t *getSound(std::vector<sound_file_t> sounds, std::string name)
} }
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<music_file_t> music, std::string name) JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name)
{ {
for (auto m : music) for (auto m : music)
{ {
@@ -225,7 +225,7 @@ JA_Music_t *getMusic(std::vector<music_file_t> music, std::string name)
} }
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
hiScoreEntry_t sortHiScoreTable(hiScoreEntry_t entry1, hiScoreEntry_t entry2) HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2)
{ {
if (entry1.score > entry2.score) if (entry1.score > entry2.score)
{ {
@@ -275,9 +275,9 @@ void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_
} }
// Aclara el color // Aclara el color
color_t lightenColor(color_t color, int amount) Color lightenColor(Color color, int amount)
{ {
color_t newColor; Color newColor;
newColor.r = std::min(255, (int)color.r + amount); newColor.r = std::min(255, (int)color.r + amount);
newColor.g = std::min(255, (int)color.g + amount); newColor.g = std::min(255, (int)color.g + amount);
newColor.b = std::min(255, (int)color.b + amount); newColor.b = std::min(255, (int)color.b + amount);
@@ -285,9 +285,9 @@ color_t lightenColor(color_t color, int amount)
} }
// Oscurece el color // Oscurece el color
color_t DarkenColor(color_t color, int amount) Color DarkenColor(Color color, int amount)
{ {
color_t newColor; Color newColor;
newColor.r = std::max(0, (int)color.r - amount); newColor.r = std::max(0, (int)color.r - amount);
newColor.g = std::max(0, (int)color.g - amount); newColor.g = std::max(0, (int)color.g - amount);
newColor.b = std::max(0, (int)color.b - amount); newColor.b = std::max(0, (int)color.b - amount);
@@ -319,6 +319,7 @@ double easeOutQuint(double t)
} }
// Función de suavizado // Función de suavizado
double easeInOutSine(double t) { double easeInOutSine(double t)
{
return -0.5 * (std::cos(M_PI * t) - 1); return -0.5 * (std::cos(M_PI * t) - 1);
} }

View File

@@ -25,128 +25,104 @@ enum class GameDifficulty
#define BLOCK 8 #define BLOCK 8
// Estructura para definir un circulo // Estructura para definir un circulo
struct circle_t struct Circle
{ {
int x, y, r; int x, y, r;
}; };
// Estructura para definir una linea horizontal
struct h_line_t
{
int x1, x2, y;
};
// Estructura para definir una linea vertical
struct v_line_t
{
int x, y1, y2;
};
// Estructura para definir una linea diagonal
struct d_line_t
{
int x1, y1, x2, y2;
};
// Estructura para definir una linea
struct line_t
{
int x1, y1, x2, y2;
};
// Estructura para definir un color // Estructura para definir un color
struct color_t struct Color
{ {
Uint8 r, g, b; Uint8 r, g, b;
}; };
// Posiciones de las notificaciones // Posiciones de las notificaciones
enum not_pos_e enum class NotifyPosition
{ {
pos_top, TOP,
pos_bottom, BOTTOM,
pos_left, LEFT,
pos_middle, MIDDLE,
pos_right RIGHT,
}; };
// Estructura para saber la seccion y subseccion del programa // Estructura para saber la seccion y subseccion del programa
struct section_t struct Section
{ {
Uint8 name; Uint8 name;
Uint8 options; Uint8 options;
}; };
// Estructura para las entradas de la tabla de recirds // Estructura para las entradas de la tabla de recirds
struct hiScoreEntry_t struct HiScoreEntry
{ {
std::string name; // Nombre std::string name; // Nombre
int score; // Puntuación int score; // Puntuación
}; };
// Estructura para mapear el teclado usado en la demo // Estructura para mapear el teclado usado en la demo
struct demoKeys_t struct DemoKeys
{ {
Uint8 left; Uint8 left;
Uint8 right; Uint8 right;
Uint8 noInput; Uint8 no_input;
Uint8 fire; Uint8 fire;
Uint8 fireLeft; Uint8 fire_left;
Uint8 fireRight; Uint8 fire_right;
}; };
// Estructura para las opciones de la ventana // Estructura para las opciones de la ventana
struct op_window_t struct OptionsWindow
{ {
int size; // Contiene el valor por el que se multiplica el tamaño de la ventana int size; // Contiene el valor por el que se multiplica el tamaño de la ventana
}; };
// Estructura con opciones para el video // Estructura con opciones para el video
struct op_video_t struct OptionsVideo
{ {
op_window_t window; // Opciones para la ventana del programa OptionsWindow window; // Opciones para la ventana del programa
ScreenVideoMode mode; // Contiene el valor del modo de pantalla completa ScreenVideoMode mode; // Contiene el valor del modo de pantalla completa
ScreenFilter filter; // Filtro usado para el escalado de la imagen ScreenFilter filter; // Filtro usado para el escalado de la imagen
bool vSync; // Indica si se quiere usar vsync o no bool v_sync; // Indica si se quiere usar vsync o no
bool shaders; // Indica si se van a usar shaders para los filtros de video bool shaders; // Indica si se van a usar shaders para los filtros de video
}; };
// Estructura para las opciones de musica // Estructura para las opciones de musica
struct op_music_t struct OptionsMusic
{ {
bool enabled; // Indica si la musica suena o no bool enabled; // Indica si la musica suena o no
int volume; // Volumen al que suena la música int volume; // Volumen al que suena la música
}; };
// Estructura para las opciones de sonido // Estructura para las opciones de sonido
struct op_sound_t struct OptionsSound
{ {
bool enabled; // Indica si los sonidos suenan o no bool enabled; // Indica si los sonidos suenan o no
int volume; // Volumen al que suenan los sonidos int volume; // Volumen al que suenan los sonidos
}; };
// Estructura para las opciones de audio // Estructura para las opciones de audio
struct op_audio_t struct OptionsAudio
{ {
op_music_t music; // Opciones para la música OptionsMusic music; // Opciones para la música
op_sound_t sound; // Opciones para los efectos de sonido OptionsSound sound; // Opciones para los efectos de sonido
}; };
// Estructura para las opciones del juego // Estructura para las opciones del juego
struct op_game_t struct OptionsGame
{ {
GameDifficulty difficulty; // Dificultad del juego GameDifficulty difficulty; // Dificultad del juego
Uint8 language; // Idioma usado en el juego Uint8 language; // Idioma usado en el juego
bool autofire; // Indica si el jugador ha de pulsar repetidamente para disparar o basta con mantener pulsado bool autofire; // Indica si el jugador ha de pulsar repetidamente para disparar o basta con mantener pulsado
std::vector<hiScoreEntry_t> hiScoreTable; // Tabla con las mejores puntuaciones std::vector<HiScoreEntry> hi_score_table; // Tabla con las mejores puntuaciones
}; };
// Estructura para los controles del juego // Estructura para los controles del juego
struct op_controller_t struct OptionsController
{ {
int index; // Indice en el vector de mandos int index; // Indice en el vector de mandos
int playerId; // Jugador asociado al mando int player_id; // Jugador asociado al mando
Uint8 deviceType; // Indica si se utilizará teclado o mando o ambos Uint8 device_type; // Indica si se utilizará teclado o mando o ambos
std::string name; // Nombre del dispositivo std::string name; // Nombre del dispositivo
bool plugged; // Indica si el mando se encuentra conectado bool plugged; // Indica si el mando se encuentra conectado
std::vector<inputs_e> inputs; // Listado de inputs std::vector<inputs_e> inputs; // Listado de inputs
@@ -154,100 +130,100 @@ struct op_controller_t
}; };
// Estructura para las opciones de las notificaciones // Estructura para las opciones de las notificaciones
struct op_notification_t struct OptionsNotification
{ {
not_pos_e posH; // Ubicación de las notificaciones en pantalla NotifyPosition pos_h; // Ubicación de las notificaciones en pantalla
not_pos_e posV; // Ubicación de las notificaciones en pantalla NotifyPosition pos_v; // Ubicación de las notificaciones en pantalla
bool sound; // Indica si las notificaciones suenan bool sound; // Indica si las notificaciones suenan
color_t color; // Color de las notificaciones Color color; // Color de las notificaciones
}; };
// Estructura con todas las opciones de configuración del programa // Estructura con todas las opciones de configuración del programa
struct options_t struct Options
{ {
op_game_t game; // Opciones para el propio juego OptionsGame game; // Opciones para el propio juego
op_video_t video; // Opciones relativas a la clase screen OptionsVideo video; // Opciones relativas a la clase screen
op_audio_t audio; // Opciones para el audio OptionsAudio audio; // Opciones para el audio
op_notification_t notification; // Opciones para las notificaciones OptionsNotification notification; // Opciones para las notificaciones
std::vector<op_controller_t> controller; // Opciones con las asignaciones del mando para cada jugador std::vector<OptionsController> controller; // Opciones con las asignaciones del mando para cada jugador
}; };
// Posiciones dentro de un rectangulo // Posiciones dentro de un rectangulo
struct zone_t struct Zone
{ {
SDL_Rect rect; // Rectangulo que define la zona SDL_Rect rect; // Rectangulo que define la zona
int centerX; // Anclaje al 50% del eje X int center_x; // Anclaje al 50% del eje X
int firstQuarterX; // Anclaje al 25% del eje X int first_quarter_x; // Anclaje al 25% del eje X
int thirdQuarterX; // Anclaje al 75% del eje X int third_quarter_x; // Anclaje al 75% del eje X
int centerY; // Anclaje al 50% del eje Y int center_y; // Anclaje al 50% del eje Y
int firstQuarterY; // Anclaje al 25% del eje Y int first_quarter_y; // Anclaje al 25% del eje Y
int thirdQuarterY; // Anclaje al 75% del eje X int third_quarter_y; // Anclaje al 75% del eje X
}; };
// param.game // param.game
struct paramGame_t struct ParamGame
{ {
int width; // Ancho de la resolucion nativa del juego int width; // Ancho de la resolucion nativa del juego
int height; // Alto de la resolucion nativa del juego int height; // Alto de la resolucion nativa del juego
int itemSize; // Tamaño de los items del juego int item_size; // Tamaño de los items del juego
zone_t playArea; // Rectangulo con la posición de la zona de juego Zone play_area; // Rectangulo con la posición de la zona de juego
zone_t gameArea; // Rectangulo con las dimensiones del juego Zone game_area; // Rectangulo con las dimensiones del juego
}; };
// param.fade // param.fade
struct paramFade_t struct ParamFade
{ {
int numSquaresWidth; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE int num_squares_width; // Cantidad total de cuadraditos en horizontal para el FadeType::RANDOM_SQUARE
int numSquaresHeight; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE int num_squares_height; // Cantidad total de cuadraditos en vertical para el FadeType::RANDOM_SQUARE
int randomSquaresDelay; // Duración entre cada pintado de cuadrados int random_squares_delay; // Duración entre cada pintado de cuadrados
int randomSquaresMult; // Cantidad de cuadrados que se pintaran cada vez int random_squares_mult; // Cantidad de cuadrados que se pintaran cada vez
int postDuration; // Duración final del fade int post_duration; // Duración final del fade
int venetianSize; // Altura de los rectangulos para FadeType::VENETIAN int venetian_size; // Altura de los rectangulos para FadeType::VENETIAN
}; };
// param.title // param.title
struct paramTitle_t struct ParamTitle
{ {
int pressStartPosition; // Posición del texto para empezar a jugar int press_start_position; // Posición del texto para empezar a jugar
int titleDuration; // Tiempo de inactividad del titulo int title_duration; // Tiempo de inactividad del titulo
int arcadeEditionPosition; // Posición del bitmap int arcade_edition_position; // Posición del bitmap
int titleCCPosition; // Posición del bitmap int title_c_c_position; // Posición del bitmap
}; };
// param.background // param.background
struct paramBackground_t struct ParamBackground
{ {
color_t attenuateColor; Color attenuate_color;
int attenuateAlpha; int attenuate_alpha;
}; };
// Estructura para guardar los parametros de un globo // Estructura para guardar los parametros de un globo
struct paramBalloon_t struct ParamBalloon
{ {
float grav; // Aceleración en el eje Y. Modifica la velocidad float grav; // Aceleración en el eje Y. Modifica la velocidad
float vel; // Velocidad inicial que tienen al rebotar contra el suelo float vel; // Velocidad inicial que tienen al rebotar contra el suelo
}; };
// Estructura para almacenar todos los parámetros del juego // Estructura para almacenar todos los parámetros del juego
struct param_t struct Param
{ {
paramGame_t game; // Parametros relacionados con el juego ParamGame game; // Parametros relacionados con el juego
paramFade_t fade; // Parametros para ajustar el fade ParamFade fade; // Parametros para ajustar el fade
SDL_Rect scoreboard; // Posición y tamaño del marcador SDL_Rect scoreboard; // Posición y tamaño del marcador
paramTitle_t title; // Parametros con ajustes para la sección Title ParamTitle title; // Parametros con ajustes para la sección Title
paramBackground_t background; // Parametros que afectan a la clase Background ParamBackground background; // Parametros que afectan a la clase Background
paramBalloon_t balloon1, balloon2, balloon3, balloon4; // Parametros de velocidad y gravedad de cada tipo de globo ParamBalloon balloon_1, balloon_2, balloon_3, balloon_4; // Parametros de velocidad y gravedad de cada tipo de globo
}; };
// Estructura para almacenar ficheros de sonido y su nombre // Estructura para almacenar ficheros de sonido y su nombre
struct sound_file_t struct SoundFile
{ {
std::string name; // Nombre del sonido std::string name; // Nombre del sonido
JA_Sound_t *file; // Fichero con el sonido JA_Sound_t *file; // Fichero con el sonido
}; };
// Estructura para almacenar ficheros musicales y su nombre // Estructura para almacenar ficheros musicales y su nombre
struct music_file_t struct MusicFile
{ {
std::string name; // Nombre de la musica std::string name; // Nombre de la musica
JA_Music_t *file; // Fichero con la música JA_Music_t *file; // Fichero con la música
@@ -257,10 +233,10 @@ struct music_file_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(Circle &a, Circle &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(Circle &a, 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(SDL_Rect &a, SDL_Rect &b);
@@ -281,22 +257,22 @@ std::string boolToOnOff(bool value);
std::string toLower(std::string str); std::string toLower(std::string str);
// Obtiene el fichero de sonido a partir de un nombre // Obtiene el fichero de sonido a partir de un nombre
JA_Sound_t *getSound(std::vector<sound_file_t> sounds, std::string name); JA_Sound_t *getSound(std::vector<SoundFile> sounds, std::string name);
// Obtiene el fichero de música a partir de un nombre // Obtiene el fichero de música a partir de un nombre
JA_Music_t *getMusic(std::vector<music_file_t> music, std::string name); JA_Music_t *getMusic(std::vector<MusicFile> music, std::string name);
// Ordena las entradas de la tabla de records // Ordena las entradas de la tabla de records
hiScoreEntry_t sortHiScoreTable(hiScoreEntry_t entry1, hiScoreEntry_t entry2); HiScoreEntry sortHiScoreTable(HiScoreEntry entry1, HiScoreEntry entry2);
// Dibuja un circulo // Dibuja un circulo
void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius); void DrawCircle(SDL_Renderer *renderer, int32_t centerX, int32_t centerY, int32_t radius);
// Aclara el color // Aclara el color
color_t lightenColor(color_t color, int amount); Color lightenColor(Color color, int amount);
// Oscurece el color // Oscurece el color
color_t DarkenColor(color_t color, int amount); Color DarkenColor(Color color, int amount);
// Quita los espacioes en un string // Quita los espacioes en un string
std::string trim(const std::string &str); std::string trim(const std::string &str);
@@ -308,14 +284,14 @@ double easeOutQuint(double t);
double easeInOutSine(double t); double easeInOutSine(double t);
// Colores // Colores
extern const color_t bgColor; extern const Color bg_color;
extern const color_t noColor; extern const Color no_color;
extern const color_t shdwTxtColor; extern const Color shdw_txt_color;
extern const color_t separatorColor; extern const Color separator_color;
extern const color_t scoreboardColor; extern const Color scoreboard_color;
extern const color_t difficultyEasyColor; extern const Color difficulty_easy_color;
extern const color_t difficultyNormalColor; extern const Color difficulty_normal_color;
extern const color_t difficultyHardColor; extern const Color difficulty_hard_color;
extern const color_t flashColor; extern const Color flash_color;
extern const color_t fadeColor; extern const Color fade_color;
extern const color_t orangeColor; extern const Color orange_color;