Compare commits

14 Commits

Author SHA1 Message Date
59de566c5b commit de acabar la jornada laboral 2024-10-17 13:57:41 +02:00
db884cb422 Commit de vesprà tirada a la brossa 2024-10-16 22:35:19 +02:00
5585f996cb A vore si el helper ja funciona com toca 2024-10-16 13:29:16 +02:00
24556eeaa8 Implementat contador per a posar el nom al acabar la partida 2024-10-16 09:18:22 +02:00
dbffda491f Retocat l'aspecte visual de les notificacions 2024-10-15 22:56:24 +02:00
53f5f3f8b0 Ja comprova la notificació d'eixir per diferenciarla de la resta
En ARCADE la notificació diferencia si vas a eixir o a apagar el sistema
2024-10-15 20:40:45 +02:00
e0faa0890e Afegides noves cadenes de text 2024-10-15 20:12:16 +02:00
de6508c37c Don Melitonitzada la classe Notifier e independitzada de la classe Screen
Ara es poden afegir codis a les notificacions per identificarles
2024-10-15 20:09:09 +02:00
e99c2c5265 fix: faltava el nom de la classe en shutdownSystem() 2024-10-15 18:58:10 +02:00
942924c65c Afegit codi per apagar el sistema al eixir del joc 2024-10-15 18:24:19 +02:00
089da99b5b Afegida la funció getNewPosition a la classe Screen per a respectar la posició de la finestra al canviarla de tamany 2024-10-15 18:12:16 +02:00
3fdd60c9e2 Treballant en els game_texts 2024-10-15 14:02:37 +02:00
3b9885ab03 Commit de Boromir 2024-10-14 22:33:45 +02:00
39a8c992e1 Ja duplica la ultima lletra al posar el nom 2024-10-14 17:12:07 +02:00
62 changed files with 1395 additions and 1614 deletions

View File

@@ -1,11 +1,12 @@
## GAME ## GAME
game.item_size 20 game.item_size 20 # Tamaño de los items del juego
game.width 320 game.width 320 # Ancho de la resolucion nativa del juego
game.height 240 game.height 240 # Alto de la resolucion nativa del juego
game.play_area.rect.x 0 game.play_area.rect.x 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.y 0 game.play_area.rect.y 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.w 320 game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
game.play_area.rect.h 200 game.play_area.rect.h 200 # Rectangulo con la posición de la zona de juego
game.enter_name_seconds 30 # Duración en segundos para introducir el nombre al finalizar la partida
## FADE ## FADE
fade.num_squares_width 160 fade.num_squares_width 160

View File

@@ -1,11 +1,12 @@
## GAME ## GAME
game.item_size 20 game.item_size 20 # Tamaño de los items del juego
game.width 320 game.width 320 # Ancho de la resolucion nativa del juego
game.height 256 game.height 256 # Alto de la resolucion nativa del juego
game.play_area.rect.x 0 game.play_area.rect.x 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.y 0 game.play_area.rect.y 0 # Rectangulo con la posición de la zona de juego
game.play_area.rect.w 320 game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
game.play_area.rect.h 216 game.play_area.rect.h 216 # Rectangulo con la posición de la zona de juego
game.enter_name_seconds 30 # Duración en segundos para introducir el nombre al finalizar la partida
## FADE ## FADE
fade.num_squares_width 160 fade.num_squares_width 160

Binary file not shown.

Before

Width:  |  Height:  |  Size: 935 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 337 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 376 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 364 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 487 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 580 B

View File

@@ -281,7 +281,7 @@ MODE FORA DE LINEA
TAULER DE PUNTS TAULER DE PUNTS
## 94 - NOTIFICACIONES ## 94 - NOTIFICACIONES
Torna a polsar per eixir ... Torna a polsar per eixir
## 95 - DEFINE BUTTONS ## 95 - DEFINE BUTTONS
Disparar cap a l'esquerra Disparar cap a l'esquerra
@@ -345,3 +345,6 @@ Per favor
## 115 - MARCADOR ## 115 - MARCADOR
espere espere
## 116 - NOTIFICACIONES
Torna a polsar per apagar el sistema

View File

@@ -345,3 +345,6 @@ Please
## 115 - MARCADOR ## 115 - MARCADOR
wait wait
## 116 - NOTIFICACIONES
Press again to shutdown system

View File

@@ -345,3 +345,6 @@ Por favor
## 115 - MARCADOR ## 115 - MARCADOR
espere espere
## 94 - NOTIFICACIONES
Pulsa otra vez para apagar el sistema

View File

@@ -7,19 +7,16 @@
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Carga la animación desde un fichero // Carga la animación desde un fichero
AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string file_path) std::vector<Animation> loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string file_path)
{ {
// Inicializa variables // Inicializa variables
AnimatedFile af; std::vector<Animation> animations;
af.texture = texture;
auto frames_per_row = 0; auto frames_per_row = 0;
auto frame_width = 0; auto frame_width = 0;
auto frame_height = 0; auto frame_height = 0;
auto max_tiles = 0; auto max_tiles = 0;
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
std::ifstream file(file_path); std::ifstream file(file_path);
std::string line; std::string line;
@@ -27,22 +24,20 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
#ifdef VERBOSE
std::cout << "Animation loaded: " << file_name << std::endl; std::cout << "Animation loaded: " << file_name << std::endl;
#endif
while (std::getline(file, line)) while (std::getline(file, line))
{ {
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") if (line == "[animation]")
{ {
Animation buffer; Animation animation;
buffer.counter = 0; animation.counter = 0;
buffer.current_frame = 0; animation.current_frame = 0;
buffer.completed = false; animation.completed = false;
buffer.name.clear(); animation.name.clear();
buffer.speed = 5; animation.speed = 5;
buffer.loop = 0; animation.loop = 0;
buffer.frames.clear(); animation.frames.clear();
do do
{ {
@@ -56,17 +51,17 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
{ {
if (line.substr(0, pos) == "name") if (line.substr(0, pos) == "name")
{ {
buffer.name = line.substr(pos + 1, line.length()); animation.name = line.substr(pos + 1, line.length());
} }
else if (line.substr(0, pos) == "speed") else if (line.substr(0, pos) == "speed")
{ {
buffer.speed = std::stoi(line.substr(pos + 1, line.length())); animation.speed = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "loop") else if (line.substr(0, pos) == "loop")
{ {
buffer.loop = std::stoi(line.substr(pos + 1, line.length())); animation.loop = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frames") else if (line.substr(0, pos) == "frames")
@@ -81,21 +76,19 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
const auto num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp); const auto num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width; rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height; rect.y = (num_tile / frames_per_row) * frame_height;
buffer.frames.push_back(rect); animation.frames.push_back(rect);
} }
} }
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: file " << file_name.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
} }
} }
} while (line != "[/animation]"); } while (line != "[/animation]");
// Añade la animación al vector de animaciones // Añade la animación al vector de animaciones
af.animations.push_back(buffer); animations.push_back(animation);
} }
// 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
@@ -124,9 +117,7 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: file " << file_name.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
} }
// Normaliza valores // Normaliza valores
@@ -151,42 +142,38 @@ AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string
// El fichero no se puede abrir // El fichero no se puede abrir
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl;
#endif
} }
return af; return animations;
} }
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file, std::vector<std::string> *buffer) AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path)
: MovingSprite(texture), : MovingSprite(texture),
current_animation_(0) current_animation_(0)
{ {
// Carga las animaciones // Carga las animaciones
if (!file.empty()) if (!file_path.empty())
{ {
AnimatedFile as = loadAnimationFromFile(texture, file); animations_ = loadAnimationFromFile(texture, file_path);
// Copia los datos de las animaciones
std::copy(as.animations.begin(), as.animations.end(), std::back_inserter(animations_));
} }
}
else if (buffer) AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::vector<std::string> *animations)
: MovingSprite(texture),
current_animation_(0)
{
if (animations)
{ {
loadFromVector(buffer); loadFromVector(animations);
} }
} }
// Constructor // Constructor
AnimatedSprite::AnimatedSprite(const AnimatedFile *animation) AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture)
: MovingSprite(animation->texture), : MovingSprite(texture),
current_animation_(0) current_animation_(0) {}
{
// Copia los datos de las animaciones
std::copy(animation->animations.begin(), animation->animations.end(), std::back_inserter(animations_));
}
// Destructor // Destructor
AnimatedSprite::~AnimatedSprite() AnimatedSprite::~AnimatedSprite()
@@ -207,9 +194,7 @@ int AnimatedSprite::getIndex(const std::string &name)
return index; return index;
} }
} }
#ifdef VERBOSE
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl; std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
#endif
return -1; return -1;
} }
@@ -356,14 +341,14 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación // Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]") if (line == "[animation]")
{ {
Animation buffer; Animation animation;
buffer.counter = 0; animation.counter = 0;
buffer.current_frame = 0; animation.current_frame = 0;
buffer.completed = false; animation.completed = false;
buffer.name.clear(); animation.name.clear();
buffer.speed = 5; animation.speed = 5;
buffer.loop = 0; animation.loop = 0;
buffer.frames.clear(); animation.frames.clear();
do do
{ {
@@ -379,17 +364,17 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{ {
if (line.substr(0, pos) == "name") if (line.substr(0, pos) == "name")
{ {
buffer.name = line.substr(pos + 1, line.length()); animation.name = line.substr(pos + 1, line.length());
} }
else if (line.substr(0, pos) == "speed") else if (line.substr(0, pos) == "speed")
{ {
buffer.speed = std::stoi(line.substr(pos + 1, line.length())); animation.speed = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "loop") else if (line.substr(0, pos) == "loop")
{ {
buffer.loop = std::stoi(line.substr(pos + 1, line.length())); animation.loop = std::stoi(line.substr(pos + 1, line.length()));
} }
else if (line.substr(0, pos) == "frames") else if (line.substr(0, pos) == "frames")
@@ -404,22 +389,20 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
const int num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp); const int num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width; rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height; rect.y = (num_tile / frames_per_row) * frame_height;
buffer.frames.push_back(rect); animation.frames.push_back(rect);
} }
} }
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl; std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
#endif
success = false; success = false;
} }
} }
} while (line != "[/animation]"); } while (line != "[/animation]");
// Añade la animación al vector de animaciones // Añade la animación al vector de animaciones
animations_.push_back(buffer); animations_.push_back(animation);
} }
// 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
@@ -448,9 +431,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl; std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
#endif
success = false; success = false;
} }
@@ -474,7 +455,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
} }
// Pone un valor por defecto // Pone un valor por defecto
setPos((SDL_Rect){0, 0, frame_width, frame_height}); setPosition((SDL_Rect){0, 0, frame_width, frame_height});
return success; return success;
} }

View File

@@ -19,14 +19,8 @@ struct Animation
int counter; // Contador para las animaciones int counter; // Contador para las animaciones
}; };
struct AnimatedFile
{
std::vector<Animation> animations; // Vector con las diferentes animaciones
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
AnimatedFile loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath); std::vector<Animation> loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath);
class AnimatedSprite : public MovingSprite class AnimatedSprite : public MovingSprite
{ {
@@ -35,16 +29,20 @@ protected:
std::vector<Animation> animations_; // Vector con las diferentes animaciones std::vector<Animation> animations_; // Vector con las diferentes animaciones
int current_animation_; // Animacion activa int current_animation_; // Animacion activa
// Calcula el frame correspondiente a la animación actual
void animate();
public: public:
// Constructor // Constructor
explicit AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, const std::string &file = std::string(), std::vector<std::string> *buffer = nullptr); AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path);
explicit AnimatedSprite(const AnimatedFile *animation); AnimatedSprite(std::shared_ptr<Texture> texture, std::vector<std::string> *animations);
explicit AnimatedSprite(std::shared_ptr<Texture> texture);
// Destructor // Destructor
virtual ~AnimatedSprite(); virtual ~AnimatedSprite();
// Calcula el frame correspondiente a la animación actual // Actualiza las variables del objeto
void animate(); void update() override;
// Obtiene el número de frames de la animación actual // Obtiene el número de frames de la animación actual
int getNumFrames(); int getNumFrames();
@@ -84,9 +82,6 @@ public:
void setCurrentAnimation(const std::string &name = "default"); void setCurrentAnimation(const std::string &name = "default");
void setCurrentAnimation(int index = 0); void setCurrentAnimation(int index = 0);
// Actualiza las variables del objeto
void update() override;
// OLD - Establece el rectangulo para un frame de una animación // OLD - Establece el rectangulo para un frame de una animación
void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h); void setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h);

View File

@@ -59,9 +59,7 @@ std::string Asset::get(const std::string &text) const
} }
} }
#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 "";
} }
@@ -70,12 +68,10 @@ bool Asset::check() const
{ {
bool success = true; bool success = true;
#ifdef VERBOSE
std::cout << "\n** Checking files" << std::endl; std::cout << "\n** Checking files" << std::endl;
std::cout << "Executable path is: " << executable_path_ << std::endl; std::cout << "Executable path is: " << executable_path_ << std::endl;
std::cout << "Sample filepath: " << file_list_.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 < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type) for (int type = 0; type < static_cast<int>(AssetType::MAX_ASSET_TYPE); ++type)
@@ -94,9 +90,7 @@ bool Asset::check() const
// Si hay ficheros de ese tipo, comprueba si existen // Si hay ficheros de ese tipo, comprueba si existen
if (any) if (any)
{ {
#ifdef VERBOSE
std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl; std::cout << "\n>> " << getTypeName(static_cast<AssetType>(type)).c_str() << " FILES" << std::endl;
#endif
for (const auto &f : file_list_) for (const auto &f : file_list_)
{ {
@@ -108,10 +102,8 @@ bool Asset::check() const
} }
} }
// Resultado // Resultado
#ifdef VERBOSE
std::cout << (success ? "\n** All files OK.\n" : "\n** A file is missing. Exiting.\n") << std::endl; std::cout << (success ? "\n** All files OK.\n" : "\n** A file is missing. Exiting.\n") << std::endl;
#endif
return success; return success;
} }
@@ -130,7 +122,6 @@ bool Asset::checkFile(const std::string &path) const
SDL_RWclose(file); SDL_RWclose(file);
} }
#ifdef VERBOSE
const std::string file_name = path.substr(path.find_last_of("\\/") + 1); const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
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: ";
@@ -138,7 +129,6 @@ bool Asset::checkFile(const std::string &path) const
std::cout.fill('.'); std::cout.fill('.');
std::cout << file_name; std::cout << file_name;
std::cout << (success ? " [OK]" : " [ERROR]") << std::endl; std::cout << (success ? " [OK]" : " [ERROR]") << std::endl;
#endif
return success; return success;
} }

View File

@@ -1,12 +1,12 @@
#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 clamp, max #include <algorithm> // for clamp, max
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "moving_sprite.h" // for MovingSprite #include "moving_sprite.h" // for MovingSprite
#include "param.h" // for param #include "param.h" // for param
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Constructor // Constructor
Background::Background(SDL_Renderer *renderer) Background::Background(SDL_Renderer *renderer)
@@ -19,55 +19,71 @@ Background::Background(SDL_Renderer *renderer)
{ {
// Inicializa variables // Inicializa variables
gradient_number_ = 0;
alpha_ = 0;
clouds_speed_ = 0;
transition_ = 0;
counter_ = 0;
rect_ = {0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2};
src_rect_ = {0, 0, 320, 240};
dst_rect_ = {0, 0, 320, 240};
base_ = rect_.h;
color_ = {param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b};
alpha_color_text_ = alpha_color_text_temp_ = param.background.attenuate_alpha;
gradient_rect_[0] = {0, 0, rect_.w, rect_.h};
gradient_rect_[1] = {rect_.w, 0, rect_.w, rect_.h};
gradient_rect_[2] = {0, rect_.h, rect_.w, rect_.h};
gradient_rect_[3] = {rect_.w, rect_.h, rect_.w, rect_.h};
const int top_clouds_texture_height = top_clouds_texture_->getHeight() / 4;
const int bottom_clouds_texture_height = bottom_clouds_texture_->getHeight() / 4;
for (int i = 0; i < 4; ++i)
{ {
top_clouds_rect_[i] = {0, i * top_clouds_texture_height, top_clouds_texture_->getWidth(), top_clouds_texture_height}; gradient_number_ = 0;
bottom_clouds_rect_[i] = {0, i * bottom_clouds_texture_height, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_height}; alpha_ = 0;
clouds_speed_ = 0;
transition_ = 0;
counter_ = 0;
rect_ = {0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2};
src_rect_ = {0, 0, 320, 240};
dst_rect_ = {0, 0, 320, 240};
base_ = rect_.h;
color_ = {param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b};
alpha_color_text_ = alpha_color_text_temp_ = param.background.attenuate_alpha;
gradient_rect_[0] = {0, 0, rect_.w, rect_.h};
gradient_rect_[1] = {rect_.w, 0, rect_.w, rect_.h};
gradient_rect_[2] = {0, rect_.h, rect_.w, rect_.h};
gradient_rect_[3] = {rect_.w, rect_.h, rect_.w, rect_.h};
const int top_clouds_texture_height = top_clouds_texture_->getHeight() / 4;
const int bottom_clouds_texture_height = bottom_clouds_texture_->getHeight() / 4;
for (int i = 0; i < 4; ++i)
{
top_clouds_rect_[i] = {0, i * top_clouds_texture_height, top_clouds_texture_->getWidth(), top_clouds_texture_height};
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 top_clouds_y = base_ - 165; {
const int bottom_clouds_y = base_ - 101; const int top_clouds_y = base_ - 165;
constexpr float top_clouds_speed = 0.1f; const int bottom_clouds_y = base_ - 101;
constexpr float bottom_clouds_speed = 0.05f;
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_);
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_);
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_); top_clouds_sprite_a_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_Rect){0, top_clouds_y, rect_.w, top_clouds_texture_->getHeight()});
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_); top_clouds_sprite_b_ = std::make_unique<MovingSprite>(top_clouds_texture_, (SDL_Rect){rect_.w, top_clouds_y, rect_.w, top_clouds_texture_->getHeight()});
buildings_sprite_ = std::make_unique<Sprite>(0, 0, buildings_texture_->getWidth(), buildings_texture_->getHeight(), buildings_texture_); bottom_clouds_sprite_a_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_Rect){0, bottom_clouds_y, rect_.w, bottom_clouds_texture_->getHeight()});
gradient_sprite_ = std::make_unique<Sprite>(0, 0, rect_.w, rect_.h, gradients_texture_); bottom_clouds_sprite_b_ = std::make_unique<MovingSprite>(bottom_clouds_texture_, (SDL_Rect){rect_.w, bottom_clouds_y, rect_.w, bottom_clouds_texture_->getHeight()});
grass_sprite_ = std::make_unique<Sprite>(0, 0, grass_texture_->getWidth(), grass_texture_->getHeight() / 2, grass_texture_);
buildings_sprite_ = std::make_unique<Sprite>(buildings_texture_, 0, 0, buildings_texture_->getWidth(), buildings_texture_->getHeight());
gradient_sprite_ = std::make_unique<Sprite>(gradients_texture_, 0, 0, rect_.w, rect_.h);
grass_sprite_ = std::make_unique<Sprite>(grass_texture_, 0, 0, grass_texture_->getWidth(), grass_texture_->getHeight() / 2);
}
// Inicializa objetos // Inicializa objetos
top_clouds_sprite_a_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight()); {
top_clouds_sprite_b_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight()); constexpr float top_clouds_speed = 0.1f;
bottom_clouds_sprite_a_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight()); constexpr float bottom_clouds_speed = 0.05f;
bottom_clouds_sprite_b_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
buildings_sprite_->setPosY(base_ - buildings_sprite_->getHeight()); top_clouds_sprite_a_->setVelX(-top_clouds_speed);
grass_sprite_->setPosY(base_ - grass_sprite_->getHeight()); top_clouds_sprite_a_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
top_clouds_sprite_b_->setVelX(-top_clouds_speed);
top_clouds_sprite_b_->setSpriteClip(0, 0, top_clouds_texture_->getWidth(), top_clouds_texture_->getHeight());
bottom_clouds_sprite_a_->setVelX(-bottom_clouds_speed);
bottom_clouds_sprite_a_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
bottom_clouds_sprite_b_->setVelX(-bottom_clouds_speed);
bottom_clouds_sprite_b_->setSpriteClip(0, 0, bottom_clouds_texture_->getWidth(), bottom_clouds_texture_->getHeight());
buildings_sprite_->setY(base_ - buildings_sprite_->getHeight());
grass_sprite_->setY(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);
@@ -297,10 +313,10 @@ void Background::updateClouds()
bottom_clouds_sprite_b_->setVelX(clouds_speed_ / 2); bottom_clouds_sprite_b_->setVelX(clouds_speed_ / 2);
// Mueve las nubes // Mueve las nubes
top_clouds_sprite_a_->move(); top_clouds_sprite_a_->update();
top_clouds_sprite_b_->move(); top_clouds_sprite_b_->update();
bottom_clouds_sprite_a_->move(); bottom_clouds_sprite_a_->update();
bottom_clouds_sprite_b_->move(); bottom_clouds_sprite_b_->update();
// Calcula el offset de las nubes // Calcula el offset de las nubes
if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth()) if (top_clouds_sprite_a_->getPosX() < -top_clouds_sprite_a_->getWidth())

View File

@@ -1,9 +1,9 @@
#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 <memory> // for unique_ptr, shared_ptr #include <memory> // for unique_ptr, shared_ptr
#include "utils.h" // for Color #include "utils.h" // for Color
class MovingSprite; class MovingSprite;
class Sprite; class Sprite;
class Texture; class Texture;

View File

@@ -1,6 +1,6 @@
#include "balloon.h" #include "balloon.h"
#include <cmath> // for abs #include <cmath> // for abs
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "moving_sprite.h" // for MovingSprite #include "moving_sprite.h" // for MovingSprite
#include "param.h" // for param #include "param.h" // for param
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
@@ -8,7 +8,7 @@
// Constructor // Constructor
Balloon::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) Balloon::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)
: sprite_(std::make_unique<AnimatedSprite>(texture, "", animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
pos_x_(x), pos_x_(x),
pos_y_(y), pos_y_(y),
vel_x_(vel_x), vel_x_(vel_x),
@@ -217,7 +217,7 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16
menace_ = 0; menace_ = 0;
// Añade rotación al sprite_ // Añade rotación al sprite_
sprite_->setRotate(false); sprite_->disableRotate();
sprite_->setRotateSpeed(0); sprite_->setRotateSpeed(0);
vel_x_ > 0.0f ? sprite_->setRotateAmount(2.0) : sprite_->setRotateAmount(-2.0); vel_x_ > 0.0f ? sprite_->setRotateAmount(2.0) : sprite_->setRotateAmount(-2.0);
@@ -306,7 +306,7 @@ void Balloon::render()
if (kind_ == POWER_BALL && !isBeingCreated()) if (kind_ == POWER_BALL && !isBeingCreated())
{ {
auto sp = std::make_unique<Sprite>(sprite_->getPos(), sprite_->getTexture()); auto sp = std::make_unique<Sprite>(sprite_->getTexture(), sprite_->getPosition());
sp->setSpriteClip(BALLOON_WIDTH_4, 0, BALLOON_WIDTH_4, BALLOON_WIDTH_4); sp->setSpriteClip(BALLOON_WIDTH_4, 0, BALLOON_WIDTH_4, BALLOON_WIDTH_4);
sp->render(); sp->render();
} }
@@ -454,7 +454,7 @@ void Balloon::update()
{ {
if (enabled_) if (enabled_)
{ {
sprite_->MovingSprite::update(); sprite_->update();
move(); move();
updateAnimation(); updateAnimation();
updateColliders(); updateColliders();
@@ -510,7 +510,7 @@ void Balloon::updateState()
setInvulnerable(false); setInvulnerable(false);
if (kind_ == POWER_BALL) if (kind_ == POWER_BALL)
{ {
sprite_->setRotate(true); sprite_->enableRotate();
} }
} }
} }
@@ -520,7 +520,7 @@ void Balloon::updateState()
// Si es una powerball deja de rodar // Si es una powerball deja de rodar
if (kind_ == POWER_BALL) if (kind_ == POWER_BALL)
{ {
sprite_->setRotate(false); sprite_->disableRotate();
} }
// Reduce el contador // Reduce el contador
@@ -536,7 +536,7 @@ void Balloon::updateState()
// Si es una powerball vuelve a rodar // Si es una powerball vuelve a rodar
if (kind_ == POWER_BALL) if (kind_ == POWER_BALL)
{ {
sprite_->setRotate(true); sprite_->enableRotate();
} }
} }
} }
@@ -569,7 +569,7 @@ void Balloon::updateAnimation()
sprite_->setCurrentAnimation(normal_animation); sprite_->setCurrentAnimation(normal_animation);
} }
sprite_->animate(); sprite_->update();
} }
// Comprueba si el globo está habilitado // Comprueba si el globo está habilitado

View File

@@ -4,7 +4,7 @@
#include <memory> // for shared_ptr, unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "utils.h" // for Circle #include "utils.h" // for Circle
class Texture; class Texture;

View File

@@ -12,7 +12,7 @@ constexpr int BULLET_VELX_RIGHT = 2;
// Constructor // Constructor
Bullet::Bullet(int x, int y, BulletType kind, bool powered_up, int owner, SDL_Rect *play_area, std::shared_ptr<Texture> texture) Bullet::Bullet(int x, int y, BulletType kind, bool powered_up, int owner, SDL_Rect *play_area, std::shared_ptr<Texture> texture)
: sprite_(std::make_unique<Sprite>(SDL_Rect{x, y, BULLET_WIDTH, BULLET_HEIGHT}, texture)), : sprite_(std::make_unique<Sprite>(texture, SDL_Rect{x, y, BULLET_WIDTH, BULLET_HEIGHT})),
pos_x_(x), pos_x_(x),
pos_y_(y), pos_y_(y),
width_(BULLET_WIDTH), width_(BULLET_WIDTH),
@@ -57,8 +57,8 @@ BulletMoveStatus Bullet::move()
return BulletMoveStatus::OUT; return BulletMoveStatus::OUT;
} }
sprite_->setPosX(pos_x_); sprite_->setX(pos_x_);
sprite_->setPosY(pos_y_); sprite_->setY(pos_y_);
shiftColliders(); shiftColliders();
return BulletMoveStatus::OK; return BulletMoveStatus::OK;

View File

@@ -8,6 +8,7 @@
#include <SDL2/SDL_scancode.h> // for SDL_SCANCODE_0, SDL_SCANCODE_DOWN #include <SDL2/SDL_scancode.h> // for SDL_SCANCODE_0, SDL_SCANCODE_DOWN
#include <SDL2/SDL_stdinc.h> // for SDL_bool, Uint32 #include <SDL2/SDL_stdinc.h> // for SDL_bool, Uint32
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <cstdlib> // for system
#include <errno.h> // for errno, EEXIST, EACCES, ENAMETOO... #include <errno.h> // for errno, EEXIST, EACCES, ENAMETOO...
#include <stdio.h> // for printf, perror #include <stdio.h> // for printf, perror
#include <string.h> // for strcmp #include <string.h> // for strcmp
@@ -29,6 +30,7 @@
#include "lang.h" // for Code, loadFromFile #include "lang.h" // for Code, loadFromFile
#include "logo.h" // for Logo #include "logo.h" // for Logo
#include "manage_hiscore_table.h" // for ManageHiScoreTable #include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "notifier.h" // for Notifier
#include "on_screen_help.h" // for OnScreenHelp #include "on_screen_help.h" // for OnScreenHelp
#include "options.h" // for options, loadOptionsFile, saveO... #include "options.h" // for options, loadOptionsFile, saveO...
#include "param.h" // for param, loadParamsFromFile #include "param.h" // for param, loadParamsFromFile
@@ -53,6 +55,12 @@ Director::Director(int argc, const char *argv[])
section::name = section::Name::LOGO; section::name = section::Name::LOGO;
#endif #endif
#ifndef VERBOSE
// Deshabilita todos los std::cout
std::ostream null_stream(nullptr);
std::streambuf *orig_buf = std::cout.rdbuf(null_stream.rdbuf());
#endif
// Comprueba los parametros del programa // Comprueba los parametros del programa
checkProgramArguments(argc, argv); checkProgramArguments(argc, argv);
@@ -101,6 +109,8 @@ Director::Director(int argc, const char *argv[])
Screen::init(window_, renderer_); Screen::init(window_, renderer_);
Notifier::init(renderer_, std::string(), Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"));
OnScreenHelp::init(); OnScreenHelp::init();
// Carga los sonidos del juego // Carga los sonidos del juego
@@ -119,6 +129,7 @@ Director::~Director()
Asset::destroy(); Asset::destroy();
Input::destroy(); Input::destroy();
Screen::destroy(); Screen::destroy();
Notifier::destroy();
OnScreenHelp::destroy(); OnScreenHelp::destroy();
sounds_.clear(); sounds_.clear();
@@ -243,9 +254,7 @@ bool Director::initSDL()
// Inicializa SDL // Inicializa SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{ {
#ifdef VERBOSE
std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "SDL could not initialize!\nSDL Error: " << SDL_GetError() << std::endl;
#endif
success = false; success = false;
} }
else else
@@ -253,7 +262,6 @@ bool Director::initSDL()
// Inicia el generador de numeros aleatorios // Inicia el generador de numeros aleatorios
std::srand(static_cast<unsigned int>(SDL_GetTicks())); std::srand(static_cast<unsigned int>(SDL_GetTicks()));
#ifdef VERBOSE
// Muestra información de la pantalla // Muestra información de la pantalla
/*std::cout << "\nDisplay modes list:" << std::endl; /*std::cout << "\nDisplay modes list:" << std::endl;
for (int i = 0; i < SDL_GetNumDisplayModes(0); ++i) for (int i = 0; i < SDL_GetNumDisplayModes(0); ++i)
@@ -267,30 +275,23 @@ bool Director::initSDL()
SDL_GetCurrentDisplayMode(0, &DM); SDL_GetCurrentDisplayMode(0, &DM);
std::cout << "\nCurrent display mode: " + std::to_string(DM.w) + "x" + std::to_string(DM.h) + " @ " + std::to_string(DM.refresh_rate) + "Hz" << std::endl; std::cout << "\nCurrent display mode: " + std::to_string(DM.w) + "x" + std::to_string(DM.h) + " @ " + std::to_string(DM.refresh_rate) + "Hz" << std::endl;
std::cout << "Window resolution : " + std::to_string(param.game.width) + "x" + std::to_string(param.game.height) + " x" + std::to_string(options.video.window.size) << std::endl; std::cout << "Window resolution : " + std::to_string(param.game.width) + "x" + std::to_string(param.game.height) + " x" + std::to_string(options.video.window.size) << std::endl;
#endif
// Establece el filtro de la textura // Establece el filtro de la textura
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(static_cast<int>(options.video.filter)).c_str())) if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, std::to_string(static_cast<int>(options.video.filter)).c_str()))
{ {
#ifdef VERBOSE
std::cout << "Warning: texture filtering not enabled!\n"; std::cout << "Warning: texture filtering not enabled!\n";
#endif
} }
#ifndef NO_SHADERS #ifndef NO_SHADERS
if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl")) if (!SDL_SetHint(SDL_HINT_RENDER_DRIVER, "opengl"))
{ {
#ifdef VERBOSE
std::cout << "Warning: opengl not enabled!\n"; std::cout << "Warning: opengl not enabled!\n";
#endif // VERBOSE
} }
#endif // NO_SHADERS #endif // NO_SHADERS
// Crea la ventana // Crea la ventana
window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, param.game.width * options.video.window.size, param.game.height * options.video.window.size, SDL_WINDOW_HIDDEN); window_ = SDL_CreateWindow(WINDOW_CAPTION, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, param.game.width * options.video.window.size, param.game.height * options.video.window.size, SDL_WINDOW_HIDDEN);
if (!window_) if (!window_)
{ {
#ifdef VERBOSE
std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Window could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
#endif
success = false; success = false;
} }
else else
@@ -309,9 +310,7 @@ bool Director::initSDL()
if (!renderer_) if (!renderer_)
{ {
#ifdef VERBOSE
std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl; std::cout << "Renderer could not be created!\nSDL Error: " << SDL_GetError() << std::endl;
#endif
success = false; success = false;
} }
else else
@@ -329,9 +328,7 @@ bool Director::initSDL()
} }
} }
#ifdef VERBOSE
std::cout << std::endl; std::cout << std::endl;
#endif
return success; return success;
} }
@@ -411,7 +408,12 @@ bool Director::setFileList()
Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/game/game_grass.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_power_meter.png", AssetType::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", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/game/game_sky_colors.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game/game_text.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_1000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_2500_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_5000_points.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_powerup.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/game_text/game_text_one_hit.png", AssetType::BITMAP);
Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP); Asset::get()->add(prefix + "/data/gfx/intro/intro.png", AssetType::BITMAP);
@@ -692,6 +694,12 @@ int Director::run()
} }
} }
#ifdef ARCADE
// Comprueba si ha de apagar el sistema
if (section::options == section::Options::QUIT_SHUTDOWN)
shutdownSystem();
#endif
const int return_code = section::options == section::Options::QUIT_NORMAL ? 0 : 1; const int return_code = section::options == section::Options::QUIT_NORMAL ? 0 : 1;
return return_code; return return_code;
} }
@@ -719,3 +727,21 @@ std::string Director::getLangFile(lang::Code code)
return Asset::get()->get("en_UK.txt"); return Asset::get()->get("en_UK.txt");
} }
// Apaga el sistema
void Director::shutdownSystem()
{
#ifdef _WIN32
// Apaga el sistema en Windows
system("shutdown /s /t 0");
#elif __APPLE__
// Apaga el sistema en macOS
system("sudo shutdown -h now");
#elif __linux__
// Apaga el sistema en Linux
system("shutdown -h now");
#else
// Sistema operativo no compatible
#error "Sistema operativo no soportado"
#endif
}

View File

@@ -76,6 +76,9 @@ private:
// Obtiene una fichero a partir de un lang::Code // Obtiene una fichero a partir de un lang::Code
std::string getLangFile(lang::Code code); std::string getLangFile(lang::Code code);
// Apaga el sistema
void shutdownSystem();
public: public:
// Constructor // Constructor
Director(int argc, const char *argv[]); Director(int argc, const char *argv[]);

View File

@@ -15,7 +15,7 @@ void EnterName::init()
// Inicia la lista de caracteres permitidos // Inicia la lista de caracteres permitidos
character_list_ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+-*/=?¿<>!\"#$%&/()"; character_list_ = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-+-*/=?¿<>!\"#$%&/()";
pos_ = 0; position_ = 0;
num_characters_ = (int)character_list_.size(); num_characters_ = (int)character_list_.size();
// Pone la lista de indices para que refleje el nombre // Pone la lista de indices para que refleje el nombre
@@ -26,26 +26,27 @@ void EnterName::init()
} }
// Incrementa la posición // Incrementa la posición
void EnterName::incPos() void EnterName::incPosition()
{ {
pos_++; position_++;
pos_ = std::min(pos_, NAME_LENGHT - 1); position_ = std::min(position_, NAME_LENGHT - 1);
checkIfPositionHasBeenUsed();
} }
// Decrementa la posición // Decrementa la posición
void EnterName::decPos() void EnterName::decPosition()
{ {
pos_--; position_--;
pos_ = std::max(pos_, 0); position_ = std::max(position_, 0);
} }
// Incrementa el índice // Incrementa el índice
void EnterName::incIndex() void EnterName::incIndex()
{ {
++character_index_[pos_]; ++character_index_[position_];
if (character_index_[pos_] >= num_characters_) if (character_index_[position_] >= num_characters_)
{ {
character_index_[pos_] = 0; character_index_[position_] = 0;
} }
updateName(); updateName();
} }
@@ -53,15 +54,15 @@ void EnterName::incIndex()
// Decrementa el índice // Decrementa el índice
void EnterName::decIndex() void EnterName::decIndex()
{ {
--character_index_[pos_]; --character_index_[position_];
if (character_index_[pos_] < 0) if (character_index_[position_] < 0)
{ {
character_index_[pos_] = num_characters_ - 1; character_index_[position_] = num_characters_ - 1;
} }
updateName(); updateName();
} }
// Actualiza la variable // Actualiza el nombre a partir de la lista de índices
void EnterName::updateName() void EnterName::updateName()
{ {
name_.clear(); name_.clear();
@@ -74,16 +75,18 @@ void EnterName::updateName()
// Actualiza la variable // Actualiza la variable
void EnterName::updateCharacterIndex() void EnterName::updateCharacterIndex()
{ {
// Rellena de espacios // Rellena de espacios y marca como no usados
for (int i = 0; i < NAME_LENGHT; ++i) for (int i = 0; i < NAME_LENGHT; ++i)
{ {
character_index_[i] = 0; character_index_[i] = 0;
position_has_been_used_[i] = false;
} }
// Coloca los índices en funcion de los caracteres que forman el nombre // Coloca los índices en funcion de los caracteres que forman el nombre
for (int i = 0; i < (int)name_.size(); ++i) for (int i = 0; i < (int)name_.size(); ++i)
{ {
character_index_[i] = findIndex(name_.at(i)); character_index_[i] = findIndex(name_.at(i));
position_has_been_used_[i] = true;
} }
} }
@@ -107,7 +110,21 @@ std::string EnterName::getName() const
} }
// Obtiene la posición que se está editando // Obtiene la posición que se está editando
int EnterName::getPos() const int EnterName::getPosition() const
{ {
return pos_; return position_;
}
// Comprueba la posición y copia el caracter si es necesario
void EnterName::checkIfPositionHasBeenUsed()
{
auto used = position_has_been_used_[position_];
if (!used && position_ > 0)
{
character_index_[position_] = character_index_[position_ - 1];
}
position_has_been_used_[position_] = true;
updateName();
} }

View File

@@ -16,13 +16,14 @@ constexpr int NAME_LENGHT = 8;
class EnterName class EnterName
{ {
private: private:
std::string character_list_; // Lista de todos los caracteres permitidos std::string character_list_; // Lista de todos los caracteres permitidos
std::string name_; // Nombre introducido std::string name_; // Nombre introducido
int pos_; // Posición a editar del nombre int position_; // Posición a editar del nombre
int num_characters_; // Cantidad de caracteres de la lista de caracteres int num_characters_; // Cantidad de caracteres de la lista de caracteres
int character_index_[NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre int character_index_[NAME_LENGHT]; // Indice de la lista para cada uno de los caracteres que forman el nombre
bool position_has_been_used_[NAME_LENGHT]; // Indica si en esa posición se ha puesto ya alguna letra. Se utiliza para replicar la letra anterior la primera vez
// Actualiza la variable // Actualiza el nombre a partir de la lista de índices
void updateName(); void updateName();
// Actualiza la variable // Actualiza la variable
@@ -31,6 +32,9 @@ private:
// Encuentra el indice de un caracter en "characterList" // Encuentra el indice de un caracter en "characterList"
int findIndex(char character); int findIndex(char character);
// Comprueba la posición y copia el caracter si es necesario
void checkIfPositionHasBeenUsed();
public: public:
// Constructor // Constructor
EnterName(); EnterName();
@@ -42,10 +46,10 @@ public:
void init(); void init();
// Incrementa la posición // Incrementa la posición
void incPos(); void incPosition();
// Decrementa la posición // Decrementa la posición
void decPos(); void decPosition();
// Incrementa el índice // Incrementa el índice
void incIndex(); void incIndex();
@@ -57,5 +61,5 @@ public:
std::string getName() const; std::string getName() const;
// Obtiene la posición que se está editando // Obtiene la posición que se está editando
int getPos() const; int getPosition() const;
}; };

View File

@@ -1,6 +1,6 @@
#include "explosions.h" #include "explosions.h"
#include <utility> // for move #include <utility> // for move
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
class Texture; // lines 3-3 class Texture; // lines 3-3
// Constructor // Constructor
@@ -51,7 +51,7 @@ void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, std::vec
void Explosions::add(int x, int y, int size) void Explosions::add(int x, int y, int size)
{ {
const int index = getIndexBySize(size); const int index = getIndexBySize(size);
auto sprite = std::make_unique<AnimatedSprite>(textures_[index].texture, "", textures_[index].animation); auto sprite = std::make_unique<AnimatedSprite>(textures_[index].texture, textures_[index].animation);
sprite->setPos(x, y); sprite->setPos(x, y);
explosions_.push_back(std::move(sprite)); explosions_.push_back(std::move(sprite));
} }

View File

@@ -1,8 +1,8 @@
#pragma once #pragma once
#include <memory> // for shared_ptr, unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
class AnimatedSprite; class AnimatedSprite;
class Texture; class Texture;

View File

@@ -21,17 +21,18 @@
#include "fade.h" // for Fade, FadeType #include "fade.h" // for Fade, FadeType
#include "global_inputs.h" // for check #include "global_inputs.h" // for check
#include "input.h" // for InputType, Input, INPUT_DO_NOT_ALL... #include "input.h" // for InputType, Input, INPUT_DO_NOT_ALL...
#include "item.h" // for Item, ITEM_COFFEE_MACHINE, ITEM_CLOCK #include "item.h" // for Item, ItemType::COFFEE_MACHINE, ItemType::CLOCK
#include "jail_audio.h" // for JA_PlaySound, JA_DeleteSound, JA_L... #include "jail_audio.h" // for JA_PlaySound, JA_DeleteSound, JA_L...
#include "lang.h" // for getText #include "lang.h" // for getText
#include "manage_hiscore_table.h" // for ManageHiScoreTable #include "manage_hiscore_table.h" // for ManageHiScoreTable
#include "notifier.h" // for Notifier
#include "options.h" // for options #include "options.h" // for options
#include "param.h" // for param #include "param.h" // for param
#include "player.h" // for Player, PlayerStatus #include "player.h" // for Player, PlayerStatus
#include "scoreboard.h" // for Scoreboard, ScoreboardMode, SCOREB... #include "scoreboard.h" // for Scoreboard, ScoreboardMode, SCOREB...
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for Name, name, Options, options #include "section.h" // for Name, name, Options, options
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SpriteSmart
#include "text.h" // for Text, TEXT_CENTER #include "text.h" // for Text, TEXT_CENTER
#include "texture.h" // for Texture #include "texture.h" // for Texture
struct JA_Music_t; // lines 35-35 struct JA_Music_t; // lines 35-35
@@ -39,7 +40,8 @@ struct JA_Sound_t; // lines 36-36
// Constructor // Constructor
Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music) Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music)
: music_(music), current_stage_(current_stage) : music_(music),
current_stage_(current_stage)
{ {
// Copia los punteros // Copia los punteros
asset_ = Asset::get(); asset_ = Asset::get();
@@ -75,10 +77,6 @@ Game::Game(int player_id, int current_stage, bool demo, JA_Music_t *music)
background_->setPos(param.game.play_area.rect); background_->setPos(param.game.play_area.rect);
p1000_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
p2500_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
p5000_sprite_ = std::make_shared<SmartSprite>(game_text_texture_);
explosions_->addTexture(1, explosions_textures_[0], explosions_animations_[0]); explosions_->addTexture(1, explosions_textures_[0], explosions_animations_[0]);
explosions_->addTexture(2, explosions_textures_[1], explosions_animations_[1]); explosions_->addTexture(2, explosions_textures_[1], explosions_animations_[1]);
explosions_->addTexture(3, explosions_textures_[2], explosions_animations_[2]); explosions_->addTexture(3, explosions_textures_[2], explosions_animations_[2]);
@@ -295,62 +293,14 @@ void Game::init(int player_id)
// Con los globos creados, calcula el nivel de amenaza // Con los globos creados, calcula el nivel de amenaza
evaluateAndSetMenace(); evaluateAndSetMenace();
// Inicializa el bitmap de 1000 puntos // Inicializa los sprites con los textos que aparecen al coger items
constexpr auto height = 15; smart_sprites_.clear();
constexpr auto sprite1_width = 35;
constexpr auto sprite2_width = 38;
constexpr auto sprite3_width = 39;
p1000_sprite_->setPosX(0);
p1000_sprite_->setPosY(0);
p1000_sprite_->setWidth(sprite1_width);
p1000_sprite_->setHeight(height);
p1000_sprite_->setVelX(0.0f);
p1000_sprite_->setVelY(-0.5f);
p1000_sprite_->setAccelX(0.0f);
p1000_sprite_->setAccelY(-0.1f);
p1000_sprite_->setSpriteClip(0, 0, sprite1_width, height);
p1000_sprite_->setEnabled(false);
p1000_sprite_->setFinishedCounter(0);
p1000_sprite_->setDestX(0);
p1000_sprite_->setDestY(0);
// Inicializa el bitmap de 2500 puntos
p2500_sprite_->setPosX(0);
p2500_sprite_->setPosY(0);
p2500_sprite_->setWidth(sprite2_width);
p2500_sprite_->setHeight(height);
p2500_sprite_->setVelX(0.0f);
p2500_sprite_->setVelY(-0.5f);
p2500_sprite_->setAccelX(0.0f);
p2500_sprite_->setAccelY(-0.1f);
p2500_sprite_->setSpriteClip(sprite1_width, 0, sprite2_width, height);
p2500_sprite_->setEnabled(false);
p2500_sprite_->setFinishedCounter(0);
p2500_sprite_->setDestX(0);
p2500_sprite_->setDestY(0);
// Inicializa el bitmap de 5000 puntos
p5000_sprite_->setPosX(0);
p5000_sprite_->setPosY(0);
p5000_sprite_->setWidth(sprite3_width);
p5000_sprite_->setHeight(height);
p5000_sprite_->setVelX(0.0f);
p5000_sprite_->setVelY(-0.5f);
p5000_sprite_->setAccelX(0.0f);
p5000_sprite_->setAccelY(-0.1f);
p5000_sprite_->setSpriteClip(sprite1_width + sprite2_width, 0, sprite3_width, height);
p5000_sprite_->setEnabled(false);
p5000_sprite_->setFinishedCounter(0);
p5000_sprite_->setDestX(0);
p5000_sprite_->setDestY(0);
} }
// Carga los recursos necesarios para la sección 'Game' // Carga los recursos necesarios para la sección 'Game'
void Game::loadMedia() void Game::loadMedia()
{ {
#ifdef VERBOSE
std::cout << "\n** LOADING RESOURCES FOR GAME SECTION" << std::endl; std::cout << "\n** LOADING RESOURCES FOR GAME SECTION" << std::endl;
#endif
// Limpia // Limpia
{ {
@@ -362,93 +312,73 @@ void Game::loadMedia()
item_textures_.clear(); item_textures_.clear();
balloon_textures_.clear(); balloon_textures_.clear();
explosions_textures_.clear(); explosions_textures_.clear();
game_text_textures_.clear();
} }
// Texturas // Texturas
{ {
bullet_texture_ = std::make_shared<Texture>(renderer_, asset_->get("bullet.png")); bullet_texture_ = std::make_shared<Texture>(renderer_, asset_->get("bullet.png"));
game_text_texture_ = std::make_shared<Texture>(renderer_, asset_->get("game_text.png")); }
// Texturas - Game_text
{
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_1000_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_2500_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_5000_points.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_powerup.png")));
game_text_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("game_text_one_hit.png")));
} }
// Texturas - Globos // Texturas - Globos
{ {
auto balloon1_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon1.png")); balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon1.png")));
balloon_textures_.push_back(balloon1_texture); balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon2.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon3.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("balloon4.png")));
balloon_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("powerball.png")));
}
auto balloon2_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon2.png")); // Texturas - Explosiones
balloon_textures_.push_back(balloon2_texture); {
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion1.png")));
auto balloon3_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon3.png")); explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion2.png")));
balloon_textures_.push_back(balloon3_texture); explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion3.png")));
explosions_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("explosion4.png")));
auto balloon4_texture = std::make_shared<Texture>(renderer_, asset_->get("balloon4.png"));
balloon_textures_.push_back(balloon4_texture);
auto balloon5_texture = std::make_shared<Texture>(renderer_, asset_->get("powerball.png"));
balloon_textures_.push_back(balloon5_texture);
// Texturas - Explosiones
auto explosion1_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion1.png"));
explosions_textures_.push_back(explosion1_texture);
auto explosion2_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion2.png"));
explosions_textures_.push_back(explosion2_texture);
auto explosion3_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion3.png"));
explosions_textures_.push_back(explosion3_texture);
auto explosion4_texture = std::make_shared<Texture>(renderer_, asset_->get("explosion4.png"));
explosions_textures_.push_back(explosion4_texture);
} }
// Texturas - Items // Texturas - Items
{ {
auto item1 = std::make_shared<Texture>(renderer_, asset_->get("item_points1_disk.png")); item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points1_disk.png")));
item_textures_.push_back(item1); item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points2_gavina.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_points3_pacmar.png")));
auto item2 = std::make_shared<Texture>(renderer_, asset_->get("item_points2_gavina.png")); item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_clock.png")));
item_textures_.push_back(item2); item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_coffee.png")));
item_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("item_coffee_machine.png")));
auto item3 = std::make_shared<Texture>(renderer_, asset_->get("item_points3_pacmar.png"));
item_textures_.push_back(item3);
auto item4 = std::make_shared<Texture>(renderer_, asset_->get("item_clock.png"));
item_textures_.push_back(item4);
auto item5 = std::make_shared<Texture>(renderer_, asset_->get("item_coffee.png"));
item_textures_.push_back(item5);
auto item6 = std::make_shared<Texture>(renderer_, asset_->get("item_coffee_machine.png"));
item_textures_.push_back(item6);
} }
// Texturas - Player1 // Texturas - Player1
{ {
auto player1_texture = std::make_shared<Texture>(renderer_, asset_->get("player1.gif")); player1_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player1.gif")));
player1_texture->addPalette(asset_->get("player1_pal1.gif")); player1_textures_.back()->addPalette(asset_->get("player1_pal1.gif"));
player1_texture->addPalette(asset_->get("player1_pal2.gif")); player1_textures_.back()->addPalette(asset_->get("player1_pal2.gif"));
player1_texture->addPalette(asset_->get("player1_pal3.gif")); player1_textures_.back()->addPalette(asset_->get("player1_pal3.gif"));
player1_textures_.push_back(player1_texture);
auto player1_power_texture = std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")); player1_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")));
player1_power_texture->addPalette(asset_->get("player_power_pal.gif")); player1_textures_.back()->addPalette(asset_->get("player_power_pal.gif"));
player1_textures_.push_back(player1_power_texture);
player_textures_.push_back(player1_textures_); player_textures_.push_back(player1_textures_);
} }
// Texturas - Player2 // Texturas - Player2
{ {
auto player2_texture = std::make_shared<Texture>(renderer_, asset_->get("player2.gif")); player2_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player2.gif")));
player2_texture->addPalette(asset_->get("player2_pal1.gif")); player2_textures_.back()->addPalette(asset_->get("player2_pal1.gif"));
player2_texture->addPalette(asset_->get("player2_pal2.gif")); player2_textures_.back()->addPalette(asset_->get("player2_pal2.gif"));
player2_texture->addPalette(asset_->get("player2_pal3.gif")); player2_textures_.back()->addPalette(asset_->get("player2_pal3.gif"));
player2_textures_.push_back(player2_texture);
auto player2_power_texture = std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")); player2_textures_.emplace_back(std::make_shared<Texture>(renderer_, asset_->get("player_power.gif")));
player2_power_texture->addPalette(asset_->get("player_power_pal.gif")); player2_textures_.back()->addPalette(asset_->get("player_power_pal.gif"));
player2_power_texture->setPalette(1); player2_textures_.back()->setPalette(1);
player2_textures_.push_back(player2_power_texture);
player_textures_.push_back(player2_textures_); player_textures_.push_back(player2_textures_);
} }
@@ -560,10 +490,8 @@ void Game::loadMedia()
coffee_machine_sound_ = JA_LoadSound(asset_->get("title.wav").c_str()); coffee_machine_sound_ = JA_LoadSound(asset_->get("title.wav").c_str());
} }
#ifdef VERBOSE
std::cout << "** RESOURCES FOR GAME SECTION LOADED\n" std::cout << "** RESOURCES FOR GAME SECTION LOADED\n"
<< std::endl; << std::endl;
#endif
} }
// Libera los recursos previamente cargados // Libera los recursos previamente cargados
@@ -605,15 +533,11 @@ bool Game::loadDemoFile(const std::string &file_path, DemoKeys (*data_file)[TOTA
{ {
// Indicador de éxito en la carga // Indicador de éxito en la carga
auto success = true; auto success = true;
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
auto file = SDL_RWFromFile(file_path.c_str(), "r+b"); auto file = SDL_RWFromFile(file_path.c_str(), "r+b");
if (!file) if (!file)
{ // El fichero no existe { // El fichero no existe
#ifdef VERBOSE
std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl;
#endif
// Creamos el fichero para escritura // Creamos el fichero para escritura
file = SDL_RWFromFile(file_path.c_str(), "w+b"); file = SDL_RWFromFile(file_path.c_str(), "w+b");
@@ -621,9 +545,7 @@ bool Game::loadDemoFile(const std::string &file_path, DemoKeys (*data_file)[TOTA
// Si ha creado el fichero // Si ha creado el fichero
if (file) if (file)
{ {
#ifdef VERBOSE
std::cout << "New file (" << file_name.c_str() << ") created!" << std::endl; std::cout << "New file (" << file_name.c_str() << ") created!" << std::endl;
#endif
// 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)
@@ -644,9 +566,7 @@ bool Game::loadDemoFile(const std::string &file_path, DemoKeys (*data_file)[TOTA
} }
else else
{ // Si no puede crear el fichero { // Si no puede crear el fichero
#ifdef VERBOSE
std::cout << "Error: Unable to create file " << file_name.c_str() << std::endl; std::cout << "Error: Unable to create file " << file_name.c_str() << std::endl;
#endif
success = false; success = false;
} }
} }
@@ -654,9 +574,7 @@ bool Game::loadDemoFile(const std::string &file_path, DemoKeys (*data_file)[TOTA
else else
{ {
// Mensaje de proceder a la carga de los datos // Mensaje de proceder a la carga de los datos
#ifdef VERBOSE
std::cout << "Reading file: " << file_name.c_str() << std::endl; std::cout << "Reading file: " << file_name.c_str() << std::endl;
#endif
// 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)
@@ -678,9 +596,7 @@ bool Game::loadDemoFile(const std::string &file_path, DemoKeys (*data_file)[TOTA
bool Game::saveDemoFile(const std::string &file_path) bool Game::saveDemoFile(const std::string &file_path)
{ {
auto success = true; auto success = true;
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif // VERBOSE
auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); auto file = SDL_RWFromFile(file_path.c_str(), "w+b");
if (file) if (file)
@@ -691,18 +607,14 @@ bool Game::saveDemoFile(const std::string &file_path)
SDL_RWwrite(file, &demo.dataFile[0][i], sizeof(DemoKeys), 1); SDL_RWwrite(file, &demo.dataFile[0][i], sizeof(DemoKeys), 1);
} }
#ifdef VERBOSE
std::cout << "Writing file " << file_name.c_str() << std::endl; std::cout << "Writing file " << file_name.c_str() << std::endl;
#endif // VERBOSE
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_RWclose(file);
} }
else else
{ {
#ifdef VERBOSE
std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl; std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl;
#endif // VERBOSE
} }
return success; return success;
@@ -1192,50 +1104,55 @@ void Game::checkPlayerItemCollision(std::shared_ptr<Player> &player)
{ {
if (checkCollision(player->getCollider(), item->getCollider())) if (checkCollision(player->getCollider(), item->getCollider()))
{ {
switch (item->getClass()) switch (item->getType())
{ {
case ITEM_POINTS_1_DISK: case ItemType::DISK:
{ {
player->addScore(1000); player->addScore(1000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p1000_sprite_->getWidth() / 2), player->getPosY(), p1000_sprite_); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[0]->getWidth() / 2), player->getPosY(), game_text_textures_[0]);
break; break;
} }
case ITEM_POINTS_2_GAVINA: case ItemType::GAVINA:
{ {
player->addScore(2500); player->addScore(2500);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p2500_sprite_->getWidth() / 2), player->getPosY(), p2500_sprite_); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[1]->getWidth() / 2), player->getPosY(), game_text_textures_[1]);
break; break;
} }
case ITEM_POINTS_3_PACMAR: case ItemType::PACMAR:
{ {
player->addScore(5000); player->addScore(5000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p5000_sprite_->getWidth() / 2), player->getPosY(), p5000_sprite_); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[2]->getWidth() / 2), player->getPosY(), game_text_textures_[2]);
break; break;
} }
case ITEM_CLOCK: case ItemType::CLOCK:
{ {
enableTimeStopItem(); enableTimeStopItem();
break; break;
} }
case ITEM_COFFEE: case ItemType::COFFEE:
{ {
if (player->getCoffees() == 2) if (player->getCoffees() == 2)
{ {
player->addScore(5000); player->addScore(5000);
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (p5000_sprite_->getWidth() / 2), player->getPosY(), p5000_sprite_); createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[2]->getWidth() / 2), player->getPosY(), game_text_textures_[2]);
}
else
{
player->giveExtraHit();
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[4]->getWidth() / 2), player->getPosY(), game_text_textures_[4]);
} }
player->giveExtraHit();
break; break;
} }
case ITEM_COFFEE_MACHINE: case ItemType::COFFEE_MACHINE:
{ {
player->setPowerUp(); player->setPowerUp();
coffee_machine_enabled_ = false; coffee_machine_enabled_ = false;
createItemScoreSprite(item->getPosX() + (item->getWidth() / 2) - (game_text_textures_[3]->getWidth() / 2), player->getPosY(), game_text_textures_[3]);
break; break;
} }
@@ -1274,9 +1191,9 @@ void Game::checkBulletBalloonCollision()
// Suelta el item si se da el caso // Suelta el item si se da el caso
const auto droppeditem = dropItem(); const auto droppeditem = dropItem();
if (droppeditem != ITEM_NULL && !demo_.recording) if (droppeditem != ItemType::NONE && !demo_.recording)
{ {
if (droppeditem != ITEM_COFFEE_MACHINE) if (droppeditem != ItemType::COFFEE_MACHINE)
{ {
createItem(droppeditem, balloon->getPosX(), balloon->getPosY()); createItem(droppeditem, balloon->getPosX(), balloon->getPosY());
JA_PlaySound(item_drop_sound_); JA_PlaySound(item_drop_sound_);
@@ -1380,7 +1297,7 @@ void Game::renderItems()
} }
// Devuelve un item al azar y luego segun sus probabilidades // Devuelve un item al azar y luego segun sus probabilidades
int Game::dropItem() ItemType Game::dropItem()
{ {
const auto lucky_number = rand() % 100; const auto lucky_number = rand() % 100;
const auto item = rand() % 6; const auto item = rand() % 6;
@@ -1390,28 +1307,28 @@ int Game::dropItem()
case 0: case 0:
if (lucky_number < helper_.item_disk_odds) if (lucky_number < helper_.item_disk_odds)
{ {
return ITEM_POINTS_1_DISK; return ItemType::DISK;
} }
break; break;
case 1: case 1:
if (lucky_number < helper_.item_gavina_odds) if (lucky_number < helper_.item_gavina_odds)
{ {
return ITEM_POINTS_2_GAVINA; return ItemType::GAVINA;
} }
break; break;
case 2: case 2:
if (lucky_number < helper_.item_pacmar_odds) if (lucky_number < helper_.item_pacmar_odds)
{ {
return ITEM_POINTS_3_PACMAR; return ItemType::GAVINA;
} }
break; break;
case 3: case 3:
if (lucky_number < helper_.item_clock_odds) if (lucky_number < helper_.item_clock_odds)
{ {
return ITEM_CLOCK; return ItemType::CLOCK;
} }
break; break;
@@ -1419,7 +1336,7 @@ int Game::dropItem()
if (lucky_number < helper_.item_coffee_odds) if (lucky_number < helper_.item_coffee_odds)
{ {
helper_.item_coffee_odds = ITEM_COFFEE_ODDS; helper_.item_coffee_odds = ITEM_COFFEE_ODDS;
return ITEM_COFFEE; return ItemType::COFFEE;
} }
else else
{ {
@@ -1436,7 +1353,7 @@ int Game::dropItem()
helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS; helper_.item_coffee_machine_odds = ITEM_COFFEE_MACHINE_ODDS;
if (!coffee_machine_enabled_ && helper_.need_coffee_machine) if (!coffee_machine_enabled_ && helper_.need_coffee_machine)
{ {
return ITEM_COFFEE_MACHINE; return ItemType::COFFEE_MACHINE;
} }
} }
else else
@@ -1452,14 +1369,13 @@ int Game::dropItem()
break; break;
} }
return ITEM_NULL; return ItemType::NONE;
} }
// Crea un objeto item // Crea un objeto item
void Game::createItem(int kind, float x, float y) void Game::createItem(ItemType type, float x, float y)
{ {
auto item = std::make_unique<Item>(kind, x, y, &(param.game.play_area.rect), item_textures_[kind - 1], item_animations_[kind - 1]); items_.emplace_back(std::make_unique<Item>(type, x, y, &(param.game.play_area.rect), item_textures_[static_cast<int>(type) - 1], item_animations_[static_cast<int>(type) - 1]));
items_.push_back(std::move(item));
} }
// Vacia el vector de items // Vacia el vector de items
@@ -1477,24 +1393,26 @@ void Game::freeItems()
} }
} }
// Crea un objeto SmartSprite para mostrar la puntuación al coger un objeto // Crea un objeto SpriteSmart para mostrar la puntuación al coger un objeto
void Game::createItemScoreSprite(int x, int y, std::shared_ptr<SmartSprite> sprite) void Game::createItemScoreSprite(int x, int y, std::shared_ptr<Texture> texture)
{ {
auto ss = new SmartSprite(nullptr); smart_sprites_.emplace_back(std::make_unique<SmartSprite>(texture));
smart_sprites_.push_back(ss);
// Crea una copia del objeto // Inicializa
*ss = *sprite; smart_sprites_.back()->setPos({0, 0, texture->getWidth(), texture->getHeight()});
ss->setPosX(x); smart_sprites_.back()->setSpriteClip(smart_sprites_.back()->getPosition());
ss->setPosY(y); smart_sprites_.back()->setPosX(x);
ss->setDestX(x); smart_sprites_.back()->setPosY(y);
ss->setDestY(y - 25); smart_sprites_.back()->setDestX(x);
ss->setEnabled(true); smart_sprites_.back()->setDestY(y - 25);
ss->setFinishedCounter(100); smart_sprites_.back()->setVelY(-0.5f);
smart_sprites_.back()->setAccelY(-0.1f);
smart_sprites_.back()->setEnabled(true);
smart_sprites_.back()->setFinishedCounter(100);
} }
// Vacia el vector de smartsprites // Vacia el vector de smartsprites
void Game::freeSmartSprites() void Game::freeSpriteSmarts()
{ {
if (!smart_sprites_.empty()) if (!smart_sprites_.empty())
{ {
@@ -1508,43 +1426,42 @@ void Game::freeSmartSprites()
} }
} }
// Crea un SmartSprite para arrojar el item café al recibir un impacto // Crea un SpriteSmart para arrojar el item café al recibir un impacto
void Game::throwCoffee(int x, int y) void Game::throwCoffee(int x, int y)
{ {
auto ss = new SmartSprite(item_textures_[4]); smart_sprites_.emplace_back(std::make_unique<SmartSprite>(item_textures_[4]));
smart_sprites_.push_back(ss);
ss->setPosX(x - 8); smart_sprites_.back()->setPosX(x - 8);
ss->setPosY(y - 8); smart_sprites_.back()->setPosY(y - 8);
ss->setWidth(param.game.item_size); smart_sprites_.back()->setWidth(param.game.item_size);
ss->setHeight(param.game.item_size); smart_sprites_.back()->setHeight(param.game.item_size);
ss->setVelX(-1.0f + ((rand() % 5) * 0.5f)); smart_sprites_.back()->setVelX(-1.0f + ((rand() % 5) * 0.5f));
ss->setVelY(-4.0f); smart_sprites_.back()->setVelY(-4.0f);
ss->setAccelX(0.0f); smart_sprites_.back()->setAccelX(0.0f);
ss->setAccelY(0.2f); smart_sprites_.back()->setAccelY(0.2f);
ss->setDestX(x + (ss->getVelX() * 50)); smart_sprites_.back()->setDestX(x + (smart_sprites_.back()->getVelX() * 50));
ss->setDestY(param.game.height + 1); smart_sprites_.back()->setDestY(param.game.height + 1);
ss->setEnabled(true); smart_sprites_.back()->setEnabled(true);
ss->setFinishedCounter(1); smart_sprites_.back()->setFinishedCounter(1);
ss->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size); smart_sprites_.back()->setSpriteClip(0, param.game.item_size, param.game.item_size, param.game.item_size);
ss->setRotate(true); smart_sprites_.back()->enableRotate();
ss->setRotateSpeed(10); smart_sprites_.back()->setRotateSpeed(10);
ss->setRotateAmount(90.0); smart_sprites_.back()->setRotateAmount(90.0);
} }
// Actualiza los SmartSprites // Actualiza los SpriteSmarts
void Game::updateSmartSprites() void Game::updateSpriteSmarts()
{ {
for (auto ss : smart_sprites_) for (auto &ss : smart_sprites_)
{ {
ss->update(); ss->update();
} }
} }
// Pinta los SmartSprites activos // Pinta los SpriteSmarts activos
void Game::renderSmartSprites() void Game::renderSpriteSmarts()
{ {
for (auto ss : smart_sprites_) for (auto &ss : smart_sprites_)
{ {
ss->render(); ss->render();
} }
@@ -1742,8 +1659,8 @@ void Game::update()
// Actualiza el estado de muerte // Actualiza el estado de muerte
updateGameOver(); updateGameOver();
// Actualiza los SmartSprites // Actualiza los SpriteSmarts
updateSmartSprites(); updateSpriteSmarts();
// Actualiza los contadores de estado y efectos // Actualiza los contadores de estado y efectos
updateTimeStoppedCounter(); updateTimeStoppedCounter();
@@ -1771,7 +1688,7 @@ void Game::update()
freeBullets(); freeBullets();
freeBalloons(); freeBalloons();
freeItems(); freeItems();
freeSmartSprites(); freeSpriteSmarts();
} }
// Comprueba si la música ha de estar sonando // Comprueba si la música ha de estar sonando
@@ -1820,7 +1737,7 @@ void Game::fillCanvas()
// Dibuja los objetos // Dibuja los objetos
background_->render(); background_->render();
renderItems(); renderItems();
renderSmartSprites(); renderSpriteSmarts();
explosions_->render(); explosions_->render();
renderBalloons(); renderBalloons();
renderBullets(); renderBullets();
@@ -2337,10 +2254,15 @@ void Game::updateHelper()
// Solo ofrece ayuda cuando la amenaza es elevada // Solo ofrece ayuda cuando la amenaza es elevada
if (menace_current_ > 15) if (menace_current_ > 15)
{ {
helper_.need_coffee = true;
helper_.need_coffee_machine = true;
for (const auto &player : players_) for (const auto &player : players_)
{ {
helper_.need_coffee = (player->getCoffees() == 0); if (player->isPlaying())
helper_.need_coffee_machine = (!player->isPowerUp()); {
helper_.need_coffee &= (player->getCoffees() == 0);
helper_.need_coffee_machine &= (!player->isPowerUp());
}
} }
} }
else else
@@ -2462,7 +2384,7 @@ void Game::checkEvents()
case SDLK_3: case SDLK_3:
{ {
auto_pop_balloons_ = !auto_pop_balloons_; auto_pop_balloons_ = !auto_pop_balloons_;
screen_->showNotification("auto_pop_balloons_ " + boolToString(auto_pop_balloons_)); Notifier::get()->showText("auto_pop_balloons_ " + boolToString(auto_pop_balloons_));
break; break;
} }
@@ -2497,9 +2419,7 @@ void Game::loadAnimations(std::string filePath, std::vector<std::string> *buffer
if (file) if (file)
{ {
#ifdef VERBOSE
std::cout << "Animation loaded: " << filePath.substr(filePath.find_last_of("\\/") + 1).c_str() << std::endl; std::cout << "Animation loaded: " << filePath.substr(filePath.find_last_of("\\/") + 1).c_str() << std::endl;
#endif
while (std::getline(file, line)) while (std::getline(file, line))
{ {
buffer->push_back(line); buffer->push_back(line);
@@ -2541,8 +2461,12 @@ void Game::reloadTextures()
texture->reLoad(); texture->reLoad();
} }
for (auto &texture : game_text_textures_)
{
texture->reLoad();
}
bullet_texture_->reLoad(); bullet_texture_->reLoad();
game_text_texture_->reLoad();
background_->reloadTextures(); background_->reloadTextures();
} }

View File

@@ -24,6 +24,7 @@ class Texture;
enum class BulletType; // lines 26-26 enum class BulletType; // lines 26-26
struct JA_Music_t; // lines 27-27 struct JA_Music_t; // lines 27-27
struct JA_Sound_t; // lines 28-28 struct JA_Sound_t; // lines 28-28
enum class ItemType;
// Modo demo // Modo demo
constexpr bool GAME_MODE_DEMO_OFF = false; constexpr bool GAME_MODE_DEMO_OFF = false;
@@ -118,11 +119,11 @@ private:
SDL_Texture *canvas_; // Textura para dibujar la zona de juego SDL_Texture *canvas_; // Textura para dibujar la zona de juego
std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores std::vector<std::shared_ptr<Player>> players_; // Vector con los jugadores
std::vector<std::shared_ptr<Balloon>> balloons_; // Vector con los globos std::vector<std::shared_ptr<Balloon>> balloons_; // Vector con los globos
std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas std::vector<std::unique_ptr<Bullet>> bullets_; // Vector con las balas
std::vector<std::unique_ptr<Item>> items_; // Vector con los items std::vector<std::unique_ptr<Item>> items_; // Vector con los items
std::vector<SmartSprite *> smart_sprites_; // Vector con los smartsprites std::vector<std::unique_ptr<SmartSprite>> smart_sprites_; // Vector con los smartsprites
std::shared_ptr<Texture> bullet_texture_; // Textura para las balas std::shared_ptr<Texture> bullet_texture_; // Textura para las balas
std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items std::vector<std::shared_ptr<Texture>> item_textures_; // Vector con las texturas de los items
@@ -132,7 +133,8 @@ private:
std::vector<std::shared_ptr<Texture>> player2_textures_; // Vector con las texturas del jugador std::vector<std::shared_ptr<Texture>> player2_textures_; // Vector con las texturas del jugador
std::vector<std::vector<std::shared_ptr<Texture>>> player_textures_; // Vector con todas las texturas de los jugadores; std::vector<std::vector<std::shared_ptr<Texture>>> player_textures_; // Vector con todas las texturas de los jugadores;
std::shared_ptr<Texture> game_text_texture_; // Textura para los sprites con textos std::vector<std::shared_ptr<Texture>> game_text_textures_; // Vector con las texturas para los sprites con textos
// std::vector<std::shared_ptr<SpriteSmart>> game_text_sprites_; // Sprite con el textos que aparecen al coger items
std::vector<std::vector<std::string> *> item_animations_; // Vector con las animaciones de los items std::vector<std::vector<std::string> *> item_animations_; // Vector con las animaciones de los items
std::vector<std::vector<std::string> *> player_animations_; // Vector con las animaciones del jugador std::vector<std::vector<std::string> *> player_animations_; // Vector con las animaciones del jugador
@@ -146,10 +148,6 @@ private:
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
std::shared_ptr<SmartSprite> p1000_sprite_; // Sprite con el texto 1.000
std::shared_ptr<SmartSprite> p2500_sprite_; // Sprite con el texto 2.500
std::shared_ptr<SmartSprite> p5000_sprite_; // Sprite con el texto 5.000
JA_Sound_t *balloon_sound_; // Sonido para la explosión del globo JA_Sound_t *balloon_sound_; // Sonido para la explosión del globo
JA_Sound_t *bullet_sound_; // Sonido para los disparos JA_Sound_t *bullet_sound_; // Sonido para los disparos
JA_Sound_t *player_collision_sound_; // Sonido para la colisión del jugador con un enemigo JA_Sound_t *player_collision_sound_; // Sonido para la colisión del jugador con un enemigo
@@ -315,28 +313,28 @@ private:
void renderItems(); void renderItems();
// Devuelve un item en función del azar // Devuelve un item en función del azar
int dropItem(); ItemType dropItem();
// Crea un objeto item // Crea un objeto item
void createItem(int kind, float x, float y); void createItem(ItemType type, float x, float y);
// Vacia el vector de items // Vacia el vector de items
void freeItems(); void freeItems();
// Crea un objeto SmartSprite // Crea un objeto SpriteSmart
void createItemScoreSprite(int x, int y, std::shared_ptr<SmartSprite> sprite); void createItemScoreSprite(int x, int y, std::shared_ptr<Texture> texture);
// Vacia el vector de smartsprites // Vacia el vector de smartsprites
void freeSmartSprites(); void freeSpriteSmarts();
// Crea un SmartSprite para arrojar el item café al recibir un impacto // Crea un SpriteSmart para arrojar el item café al recibir un impacto
void throwCoffee(int x, int y); void throwCoffee(int x, int y);
// Actualiza los SmartSprites // Actualiza los SpriteSmarts
void updateSmartSprites(); void updateSpriteSmarts();
// Pinta los SmartSprites activos // Pinta los SpriteSmarts activos
void renderSmartSprites(); void renderSpriteSmarts();
// Acciones a realizar cuando el jugador muere // Acciones a realizar cuando el jugador muere
void killPlayer(std::shared_ptr<Player> &player); void killPlayer(std::shared_ptr<Player> &player);

View File

@@ -1,12 +1,12 @@
#include "game_logo.h" #include "game_logo.h"
#include <SDL2/SDL_render.h> // for SDL_FLIP_HORIZONTAL #include <SDL2/SDL_render.h> // for SDL_FLIP_HORIZONTAL
#include <algorithm> // for max #include <algorithm> // for max
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_PlaySound #include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_PlaySound
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SpriteSmart
#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, ParamGame, ParamTitle #include "utils.h" // for Param, ParamGame, ParamTitle
@@ -24,7 +24,7 @@ GameLogo::GameLogo(int x, int y)
coffee_sprite_(std::make_unique<SmartSprite>(coffee_texture_)), coffee_sprite_(std::make_unique<SmartSprite>(coffee_texture_)),
crisis_sprite_(std::make_unique<SmartSprite>(crisis_texture_)), crisis_sprite_(std::make_unique<SmartSprite>(crisis_texture_)),
arcade_edition_sprite_(std::make_unique<Sprite>((param.game.width - arcade_edition_texture_->getWidth()) / 2, param.title.arcade_edition_position, arcade_edition_texture_->getWidth(), arcade_edition_texture_->getHeight(), arcade_edition_texture_)), arcade_edition_sprite_(std::make_unique<Sprite>(arcade_edition_texture_, (param.game.width - arcade_edition_texture_->getWidth()) / 2, param.title.arcade_edition_position, arcade_edition_texture_->getWidth(), arcade_edition_texture_->getHeight())),
crash_sound_(JA_LoadSound(Asset::get()->get("title.wav").c_str())), crash_sound_(JA_LoadSound(Asset::get()->get("title.wav").c_str())),

View File

@@ -3,6 +3,7 @@
#include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT #include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT
#include "jail_audio.h" // for JA_EnableMusic, JA_EnableSound #include "jail_audio.h" // for JA_EnableMusic, JA_EnableSound
#include "lang.h" // for getText #include "lang.h" // for getText
#include "notifier.h" // for Notifier
#include "options.h" // for options #include "options.h" // for options
#include "on_screen_help.h" #include "on_screen_help.h"
#include "screen.h" // for Screen #include "screen.h" // for Screen
@@ -28,14 +29,21 @@ namespace globalInputs
// Termina // Termina
void quit(section::Options code) void quit(section::Options code)
{ {
if (Screen::get()->notificationsAreActive()) const std::string exit_code = "QUIT";
auto code_found = stringInVector(Notifier::get()->getCodes(), exit_code);
if (code_found)
{ {
section::name = section::Name::QUIT; section::name = section::Name::QUIT;
section::options = code; section::options = code;
} }
else else
{ {
Screen::get()->showNotification(lang::getText(94)); #ifdef ARCADE
const int index = code == section::Options::QUIT_NORMAL ? 94 : 116;
Notifier::get()->showText(lang::getText(index), std::string(), -1, exit_code);
#else
Notifier::get()->showText(lang::getText(94), std::string(), -1, exit_code);
#endif
} }
} }
@@ -43,7 +51,7 @@ namespace globalInputs
void reset() void reset()
{ {
section::name = section::Name::INIT; section::name = section::Name::INIT;
Screen::get()->showNotification("Reset"); Notifier::get()->showText("Reset");
} }
// Activa o desactiva el audio // Activa o desactiva el audio
@@ -52,7 +60,7 @@ namespace globalInputs
options.audio.sound.enabled = options.audio.music.enabled = !options.audio.music.enabled; options.audio.sound.enabled = options.audio.music.enabled = !options.audio.music.enabled;
JA_EnableMusic(options.audio.music.enabled); JA_EnableMusic(options.audio.music.enabled);
JA_EnableSound(options.audio.sound.enabled); JA_EnableSound(options.audio.sound.enabled);
Screen::get()->showNotification("Audio " + boolToOnOff(options.audio.music.enabled)); Notifier::get()->showText("Audio " + boolToOnOff(options.audio.music.enabled));
} }
// Comprueba los inputs que se pueden introducir en cualquier sección del juego // Comprueba los inputs que se pueden introducir en cualquier sección del juego

View File

@@ -396,11 +396,9 @@ bool Input::discoverGameControllers()
if (SDL_GameControllerAddMappingsFromFile(game_controller_db_path_.c_str()) < 0) if (SDL_GameControllerAddMappingsFromFile(game_controller_db_path_.c_str()) < 0)
{ {
#ifdef VERBOSE
{ {
std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl; std::cout << "Error, could not load " << game_controller_db_path_.c_str() << " file: " << SDL_GetError() << std::endl;
} }
#endif
} }
num_joysticks_ = SDL_NumJoysticks(); num_joysticks_ = SDL_NumJoysticks();
@@ -418,12 +416,10 @@ bool Input::discoverGameControllers()
} }
} }
#ifdef VERBOSE
{ {
std::cout << "\nChecking for game controllers...\n"; std::cout << "\nChecking for game controllers...\n";
std::cout << num_joysticks_ << " joysticks found, " << num_gamepads_ << " are gamepads\n"; std::cout << num_joysticks_ << " joysticks found, " << num_gamepads_ << " are gamepads\n";
} }
#endif
if (num_gamepads_ > 0) if (num_gamepads_ > 0)
{ {
@@ -437,20 +433,16 @@ bool Input::discoverGameControllers()
{ {
connected_controllers_.push_back(pad); connected_controllers_.push_back(pad);
const std::string name = SDL_GameControllerNameForIndex(i); const std::string name = SDL_GameControllerNameForIndex(i);
#ifdef VERBOSE
{ {
std::cout << name << std::endl; std::cout << name << std::endl;
} }
#endif
controller_names_.push_back(name); controller_names_.push_back(name);
} }
else else
{ {
#ifdef VERBOSE
{ {
std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl; std::cout << "SDL_GetError() = " << SDL_GetError() << std::endl;
} }
#endif
} }
} }

View File

@@ -98,8 +98,8 @@ void Instructions::iniSprites()
// Inicializa los sprites // Inicializa los sprites
for (int i = 0; i < (int)item_textures_.size(); ++i) for (int i = 0; i < (int)item_textures_.size(); ++i)
{ {
auto sprite = std::make_unique<Sprite>(0, 0, param.game.item_size, param.game.item_size, item_textures_[i]); auto sprite = std::make_unique<Sprite>(item_textures_[i], 0, 0, param.game.item_size, param.game.item_size);
sprite->setPos((SDL_Point){sprite_pos_.x, sprite_pos_.y + ((param.game.item_size + item_space_) * i)}); sprite->setPosition((SDL_Point){sprite_pos_.x, sprite_pos_.y + ((param.game.item_size + item_space_) * i)});
sprites_.push_back(std::move(sprite)); sprites_.push_back(std::move(sprite));
} }
} }

View File

@@ -1,22 +1,22 @@
#include "intro.h" #include "intro.h"
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL... #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include <utility> // for move #include <utility> // for move
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "global_inputs.h" // for check #include "global_inputs.h" // for check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_StopMusic, JA_PlayMusic #include "jail_audio.h" // for JA_StopMusic, JA_PlayMusic
#include "lang.h" // for getText #include "lang.h" // for getText
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for Name, name, Options, options #include "section.h" // for Name, name, Options, options
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SpriteSmart
#include "text.h" // for Text #include "text.h" // for Text
#include "texture.h" // for Texture #include "texture.h" // for Texture
#include "utils.h" // for Param, ParamGame, Zone, BLOCK, Color #include "utils.h" // for Param, ParamGame, Zone, BLOCK, Color
#include "writer.h" // for Writer #include "writer.h" // for Writer
struct JA_Music_t; // lines 19-19 struct JA_Music_t; // lines 19-19
// Constructor // Constructor
Intro::Intro(JA_Music_t *music) Intro::Intro(JA_Music_t *music)

View File

@@ -1,13 +1,13 @@
#pragma once #pragma once
#include <SDL2/SDL_stdinc.h> // for Uint32, Uint8 #include <SDL2/SDL_stdinc.h> // for Uint32, Uint8
#include <memory> // for unique_ptr, shared_ptr #include <memory> // for unique_ptr, shared_ptr
#include <vector> // for vector #include <vector> // for vector
#include "smart_sprite.h" // for SmartSprite #include "smart_sprite.h" // for SpriteSmart
#include "writer.h" // for Writer #include "writer.h" // for Writer
class Text; class Text;
class Texture; class Texture;
struct JA_Music_t; // lines 11-11 struct JA_Music_t; // lines 11-11
/* /*
Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia Esta clase gestiona un estado del programa. Se encarga de mostrar la secuencia

View File

@@ -1,20 +1,20 @@
#include "item.h" #include "item.h"
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "param.h" // for param #include "param.h" // for param
class Texture; class Texture;
// Constructor // Constructor
Item::Item(int kind, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation) Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
: sprite_(std::make_unique<AnimatedSprite>(texture, "", animation)), : sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
accel_x_(0.0f), accel_x_(0.0f),
floor_collision_(false), floor_collision_(false),
kind_(kind), type_(type),
enabled_(true), enabled_(true),
play_area_(play_area), play_area_(play_area),
time_to_live_(600) time_to_live_(600)
{ {
if (kind == ITEM_COFFEE_MACHINE) if (type == ItemType::COFFEE_MACHINE)
{ {
width_ = 28; width_ = 28;
height_ = 37; height_ = 37;
@@ -104,7 +104,7 @@ 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 ((pos_y_ < param.game.play_area.rect.y) && !(kind_ == ITEM_COFFEE_MACHINE)) if ((pos_y_ < param.game.play_area.rect.y) && !(type_ == ItemType::COFFEE_MACHINE))
{ {
// Corrige // Corrige
pos_y_ = param.game.play_area.rect.y; pos_y_ = param.game.play_area.rect.y;
@@ -122,7 +122,7 @@ void Item::move()
accel_x_ = 0; accel_x_ = 0;
accel_y_ = 0; accel_y_ = 0;
pos_y_ = play_area_->h - height_; pos_y_ = play_area_->h - height_;
if (kind_ == ITEM_COFFEE_MACHINE) if (type_ == ItemType::COFFEE_MACHINE)
{ {
floor_collision_ = true; floor_collision_ = true;
} }
@@ -144,7 +144,7 @@ void Item::disable()
void Item::update() void Item::update()
{ {
move(); move();
sprite_->animate(); sprite_->update();
updateTimeToLive(); updateTimeToLive();
checkTimeToLive(); checkTimeToLive();
} }
@@ -190,9 +190,9 @@ int Item::getHeight()
} }
// Obtiene del valor de la variable // Obtiene del valor de la variable
int Item::getClass() ItemType Item::getType()
{ {
return kind_; return type_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable

View File

@@ -1,22 +1,25 @@
#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 <memory> // for shared_ptr, unique_ptr #include <memory> // for shared_ptr, unique_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "utils.h" // for Circle #include "utils.h" // for Circle
class Texture; class Texture;
// Tipos de objetos // Tipos de objetos
constexpr int ITEM_POINTS_1_DISK = 1; enum class ItemType : int
constexpr int ITEM_POINTS_2_GAVINA = 2; {
constexpr int ITEM_POINTS_3_PACMAR = 3; DISK = 1,
constexpr int ITEM_CLOCK = 4; GAVINA = 2,
constexpr int ITEM_COFFEE = 5; PACMAR = 3,
constexpr int ITEM_COFFEE_MACHINE = 6; CLOCK = 4,
constexpr int ITEM_NULL = 7; COFFEE = 5,
COFFEE_MACHINE = 6,
NONE = 7,
};
// Clase Item // Clase Item
class Item class Item
@@ -35,7 +38,7 @@ private:
float accel_x_; // Aceleración en el eje X float accel_x_; // Aceleración en el eje X
float accel_y_; // Aceleración en el eje Y float accel_y_; // Aceleración en el eje Y
bool floor_collision_; // Indica si el objeto colisiona con el suelo bool floor_collision_; // Indica si el objeto colisiona con el suelo
int kind_; // Especifica el tipo de objeto que es ItemType type_; // Especifica el tipo de objeto que es
bool enabled_; // Especifica si el objeto está habilitado bool enabled_; // Especifica si el objeto está habilitado
Circle collider_; // Circulo de colisión del objeto Circle collider_; // Circulo de colisión del objeto
SDL_Rect *play_area_; // Rectangulo con la zona de juego SDL_Rect *play_area_; // Rectangulo con la zona de juego
@@ -55,7 +58,7 @@ private:
public: public:
// Constructor // Constructor
Item(int kind, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation); Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Destructor // Destructor
~Item() = default; ~Item() = default;
@@ -85,7 +88,7 @@ public:
int getHeight(); int getHeight();
// Obtiene del valor de la variable // Obtiene del valor de la variable
int getClass(); ItemType getType();
// Obtiene el valor de la variable // Obtiene el valor de la variable
bool isEnabled(); bool isEnabled();

View File

@@ -1,166 +0,0 @@
#ifdef JA_USESDLMIXER
#include "jail_audio.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
struct JA_Sound_t {}; // Dummy structs
struct JA_Music_t {};
int JA_freq {48000};
SDL_AudioFormat JA_format {AUDIO_S16};
Uint8 JA_channels {2};
int JA_musicVolume = 128;
int JA_soundVolume = 64;
bool JA_musicEnabled = true;
bool JA_soundEnabled = true;
void JA_Init(const int freq, const SDL_AudioFormat format, const int channels) {
JA_freq = freq;
JA_format = format;
JA_channels = channels;
Mix_OpenAudio(JA_freq, JA_format, JA_channels, 1024);
}
void JA_Quit() {
Mix_CloseAudio();
}
JA_Music_t *JA_LoadMusic(const char* filename) {
return (JA_Music_t*)Mix_LoadMUS(filename);
}
void JA_PlayMusic(JA_Music_t *music, const int loop)
{
if (!JA_musicEnabled) return;
Mix_PlayMusic((Mix_Music*)music, loop);
Mix_VolumeMusic(JA_musicVolume);
}
void JA_PauseMusic()
{
if (!JA_musicEnabled) return;
Mix_PauseMusic();
}
void JA_ResumeMusic()
{
if (!JA_musicEnabled) return;
Mix_ResumeMusic();
}
void JA_StopMusic()
{
if (!JA_musicEnabled) return;
Mix_HaltMusic();
}
JA_Music_state JA_GetMusicState()
{
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
if (Mix_PausedMusic()) {
return JA_MUSIC_PAUSED;
} else if (Mix_PlayingMusic()) {
return JA_MUSIC_PLAYING;
} else {
return JA_MUSIC_STOPPED;
}
}
void JA_DeleteMusic(JA_Music_t *music)
{
Mix_FreeMusic((Mix_Music*)music);
}
int JA_SetMusicVolume(int volume)
{
JA_musicVolume = volume;
Mix_VolumeMusic(JA_musicVolume);
return JA_musicVolume;
}
void JA_EnableMusic(const bool value)
{
if (Mix_PlayingMusic()) Mix_HaltMusic();
JA_musicEnabled = value;
}
JA_Sound_t *JA_NewSound(Uint8* buffer, Uint32 length)
{
return NULL;
}
JA_Sound_t *JA_LoadSound(const char* filename) {
JA_Sound_t *sound = (JA_Sound_t*)Mix_LoadWAV(filename);
return sound;
}
int JA_PlaySound(JA_Sound_t *sound, const int loop) {
if (!JA_soundEnabled) return -1;
const int channel = Mix_PlayChannel(-1, (Mix_Chunk*)sound, loop);
Mix_Volume(-1, JA_soundVolume);
return channel;
}
void JA_DeleteSound(JA_Sound_t *sound)
{
Mix_FreeChunk((Mix_Chunk*)sound);
}
void JA_PauseChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_Pause(channel);
}
void JA_ResumeChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_Resume(channel);
}
void JA_StopChannel(const int channel)
{
if (!JA_soundEnabled) return;
Mix_HaltChannel(channel);
}
JA_Channel_state JA_GetChannelState(const int channel)
{
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
if (Mix_Paused(channel)) {
return JA_CHANNEL_PAUSED;
} else if (Mix_Playing(channel)) {
return JA_CHANNEL_PLAYING;
} else {
return JA_CHANNEL_FREE;
}
}
int JA_SetSoundVolume(int volume)
{
JA_musicVolume = volume;
Mix_Volume(-1, JA_musicVolume);
return JA_musicVolume;
}
void JA_EnableSound(const bool value)
{
Mix_HaltChannel(-1);
JA_soundEnabled = value;
}
int JA_SetVolume(int volume)
{
JA_SetSoundVolume(volume);
return JA_SetMusicVolume(volume);
}
#endif

View File

@@ -1,18 +1,18 @@
#include "logo.h" #include "logo.h"
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL... #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_QUIT, SDL...
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED #include <SDL2/SDL_video.h> // for SDL_WINDOWEVENT_SIZE_CHANGED
#include <utility> // for move #include <utility> // for move
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "global_inputs.h" // for check #include "global_inputs.h" // for check
#include "input.h" // for Input #include "input.h" // for Input
#include "jail_audio.h" // for JA_StopMusic #include "jail_audio.h" // for JA_StopMusic
#include "param.h" // for param #include "param.h" // for param
#include "screen.h" // for Screen #include "screen.h" // for Screen
#include "section.h" // for Name, name, Options, options #include "section.h" // for Name, name, Options, options
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Constructor // Constructor
Logo::Logo() Logo::Logo()
@@ -23,7 +23,7 @@ Logo::Logo()
// Reserva memoria para los punteros // Reserva memoria para los punteros
jail_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_jailgames.png")); jail_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_jailgames.png"));
since_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_since_1998.png")); since_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_since_1998.png"));
since_sprite_ = std::make_unique<Sprite>((param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight(), since_texture_); since_sprite_ = std::make_unique<Sprite>(since_texture_, (param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight());
// Inicializa variables // Inicializa variables
counter_ = 0; counter_ = 0;
@@ -31,18 +31,18 @@ Logo::Logo()
ticks_ = 0; ticks_ = 0;
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2; dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 2;
dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2; dest_.y = param.game.game_area.center_y - jail_texture_->getHeight() / 2;
since_sprite_->setPosY(dest_.y + jail_texture_->getHeight() + 5); since_sprite_->setY(dest_.y + jail_texture_->getHeight() + 5);
since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight()); since_sprite_->setSpriteClip(0, 0, since_texture_->getWidth(), since_texture_->getHeight());
since_texture_->setColor(0x00, 0x00, 0x00); // Esto en linux no hace nada ?? since_texture_->setColor(0x00, 0x00, 0x00); // Esto en linux no hace nada ??
// Crea los sprites de cada linea // Crea los sprites de cada linea
for (int i = 0; i < jail_texture_->getHeight(); ++i) for (int i = 0; i < jail_texture_->getHeight(); ++i)
{ {
auto temp = std::make_unique<Sprite>(0, i, jail_texture_->getWidth(), 1, jail_texture_); auto temp = std::make_unique<Sprite>(jail_texture_, 0, i, jail_texture_->getWidth(), 1);
temp->setSpriteClip(0, i, jail_texture_->getWidth(), 1); temp->setSpriteClip(0, i, jail_texture_->getWidth(), 1);
const int posX = (i % 2 == 0) ? param.game.width + (i * 3) : -jail_texture_->getWidth() - (i * 3); const int posX = (i % 2 == 0) ? param.game.width + (i * 3) : -jail_texture_->getWidth() - (i * 3);
temp->setPosX(posX); temp->setX(posX);
temp->setPosY(dest_.y + i); temp->setY(dest_.y + i);
jail_sprite_.push_back(std::move(temp)); jail_sprite_.push_back(std::move(temp));
} }
@@ -115,22 +115,22 @@ void Logo::updateJAILGAMES()
{ {
for (int i = 0; i < (int)jail_sprite_.size(); ++i) for (int i = 0; i < (int)jail_sprite_.size(); ++i)
{ {
if (jail_sprite_[i]->getIntPosX() != dest_.x) if (jail_sprite_[i]->getX() != dest_.x)
{ {
if (i % 2 == 0) if (i % 2 == 0)
{ {
jail_sprite_[i]->incPosX(-SPEED); jail_sprite_[i]->incX(-SPEED);
if (jail_sprite_[i]->getIntPosX() < dest_.x) if (jail_sprite_[i]->getX() < dest_.x)
{ {
jail_sprite_[i]->setPosX(dest_.x); jail_sprite_[i]->setX(dest_.x);
} }
} }
else else
{ {
jail_sprite_[i]->incPosX(SPEED); jail_sprite_[i]->incX(SPEED);
if (jail_sprite_[i]->getIntPosX() > dest_.x) if (jail_sprite_[i]->getX() > dest_.x)
{ {
jail_sprite_[i]->setPosX(dest_.x); jail_sprite_[i]->setX(dest_.x);
} }
} }
} }

View File

@@ -66,10 +66,8 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
if (file) if (file)
{ {
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::cout << "Reading file: " << file_name.c_str() << std::endl; std::cout << "Reading file: " << file_name.c_str() << std::endl;
#endif
for (int i = 0; i < (int)table_->size(); ++i) for (int i = 0; i < (int)table_->size(); ++i)
{ {
int nameSize = 0; int nameSize = 0;
@@ -115,9 +113,7 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
// Guarda la tabla en un fichero // Guarda la tabla en un fichero
bool ManageHiScoreTable::saveToFile(const std::string &file_path) bool ManageHiScoreTable::saveToFile(const std::string &file_path)
{ {
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
auto success = true; auto success = true;
auto file = SDL_RWFromFile(file_path.c_str(), "w+b"); auto file = SDL_RWFromFile(file_path.c_str(), "w+b");
@@ -132,17 +128,13 @@ bool ManageHiScoreTable::saveToFile(const std::string &file_path)
SDL_RWwrite(file, table_->at(i).name.c_str(), nameSize, 1); SDL_RWwrite(file, table_->at(i).name.c_str(), nameSize, 1);
} }
#ifdef VERBOSE
std::cout << "Writing file: " << file_name.c_str() << std::endl; std::cout << "Writing file: " << file_name.c_str() << std::endl;
#endif
// Cierra el fichero // Cierra el fichero
SDL_RWclose(file); SDL_RWclose(file);
} }
else else
{ {
#ifdef VERBOSE
std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl; std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl;
#endif
} }
return success; return success;
} }

View File

@@ -2,34 +2,30 @@
#include "texture.h" // for Texture #include "texture.h" // for Texture
// Constructor // Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float vx, float vy, float ax, float ay, std::shared_ptr<Texture> texture) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip)
: Sprite((int)x, (int)y, w, h, texture), : Sprite(texture, pos),
x_(x), x_(pos.x),
y_(y), y_(pos.y),
vx_(vx), rotate_(rotate),
vy_(vy), zoom_w_(zoom_w),
ax_(ax), zoom_h_(zoom_h),
ay_(ay), flip_(flip) {}
zoom_w_(1),
zoom_h_(1),
counter_(0),
flip_(SDL_FLIP_NONE)
{
// Establece los valores de rotacion
rotate_.enabled = false;
rotate_.speed = 0;
rotate_.angle = 0.0f;
rotate_.amount = 0.0f;
rotate_.center = nullptr;
sprite_clip_ = (SDL_Rect){0, 0, w, h}; MovingSprite::MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos)
}; : Sprite(texture, pos),
x_(pos.x),
y_(pos.y),
rotate_({false, 0, 0, 0.0f, 0.0f, nullptr}),
zoom_w_(1.0f),
zoom_h_(1.0f),
flip_(SDL_FLIP_NONE) {}
MovingSprite::MovingSprite(std::shared_ptr<Texture> texture) MovingSprite::MovingSprite(std::shared_ptr<Texture> texture)
: Sprite(texture) : Sprite(texture),
{ rotate_({false, 0, 0, 0.0f, 0.0f, nullptr}),
clear(); zoom_w_(1.0f),
}; zoom_h_(1.0f),
flip_(SDL_FLIP_NONE) {}
// Reinicia todas las variables // Reinicia todas las variables
void MovingSprite::clear() void MovingSprite::clear()
@@ -43,16 +39,15 @@ void MovingSprite::clear()
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
zoom_w_ = 1.0f; // Zoom aplicado a la anchura
zoom_h_ = 1.0f; // Zoom aplicado a la altura
rotate_.enabled = false; // Indica si ha de rotar rotate_.enabled = false; // Indica si ha de rotar
rotate_.counter = 0; // Contador
rotate_.speed = 0; // Velocidad de giro rotate_.speed = 0; // Velocidad de giro
rotate_.angle = 0.0f; // Angulo para dibujarlo rotate_.angle = 0.0f; // Angulo para dibujarlo
rotate_.amount = 0.0f; // Cantidad de grados a girar en cada iteración rotate_.amount = 0.0f; // Cantidad de grados a girar en cada iteración
rotate_.center = nullptr; // Centro de rotación rotate_.center = nullptr; // Centro de rotación
counter_ = 0; // Contador interno zoom_w_ = 1.0f; // Zoom aplicado a la anchura
zoom_h_ = 1.0f; // Zoom aplicado a la altura
flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite flip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
@@ -68,12 +63,139 @@ void MovingSprite::move()
vx_ += ax_; vx_ += ax_;
vy_ += ay_; vy_ += ay_;
syncPos();
}
// Actualiza las variables internas del objeto
void MovingSprite::update()
{
move();
rotate();
} }
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void MovingSprite::render() void MovingSprite::render()
{ {
texture_->render((int)x_, (int)y_, &sprite_clip_, zoom_w_, zoom_h_, (double)rotate_.angle, rotate_.center, flip_); texture_->render(pos_.x, pos_.y, &sprite_clip_, zoom_w_, zoom_h_, rotate_.angle, rotate_.center, flip_);
}
// Obtiene el valor de la variable
float MovingSprite::getZoomW() const
{
return zoom_w_;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomH() const
{
return zoom_h_;
}
// Obtiene el valor de la variable
double MovingSprite::getAngle() const
{
return rotate_.angle;
}
// Establece el valor de la variable
void MovingSprite::setZoomW(float value)
{
zoom_w_ = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoom_h_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
rotate_.angle = value;
}
// Incrementa el valor del ángulo
void MovingSprite::updateAngle()
{
rotate_.angle += rotate_.amount;
}
// Obtiene el valor de la variable
bool MovingSprite::isRotating() const
{
return rotate_.enabled;
}
// Obtiene el valor de la variable
int MovingSprite::getRotateSpeed() const
{
return rotate_.speed;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (rotate_.enabled)
{
++rotate_.counter;
if (rotate_.counter % rotate_.speed == 0)
{
updateAngle();
rotate_.counter = 0;
}
}
}
// Establece el valor de la variable
void MovingSprite::enableRotate()
{
rotate_.enabled = true;
rotate_.counter = 0;
}
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
rotate_.enabled = false;
rotate_.counter = 0;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
rotate_.speed = std::max(1, value);
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotate_.amount = value;
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotate_.amount *= -1;
}
// Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip)
{
flip_ = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return flip_;
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -112,24 +234,6 @@ float MovingSprite::getAccelY() const
return ay_; return ay_;
} }
// Obtiene el valor de la variable
float MovingSprite::getZoomW() const
{
return zoom_w_;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomH() const
{
return zoom_h_;
}
// Obtiene el valor de la variable
float MovingSprite::getAngle() const
{
return rotate_.angle;
}
// Establece la posición y_ el tamaño del objeto // Establece la posición y_ el tamaño del objeto
void MovingSprite::setPos(SDL_Rect rect) void MovingSprite::setPos(SDL_Rect rect)
{ {
@@ -145,8 +249,7 @@ void MovingSprite::setPos(float x, float y)
x_ = x; x_ = x;
y_ = y; y_ = y;
pos_.x = (int)x; syncPos();
pos_.y = (int)y;
} }
// Establece el valor de la variable // Establece el valor de la variable
@@ -187,119 +290,9 @@ void MovingSprite::setAccelY(float value)
ay_ = value; ay_ = value;
} }
// Establece el valor de la variable // Sincroniza la posición
void MovingSprite::setZoomW(float value) void MovingSprite::syncPos()
{ {
zoom_w_ = value; pos_.x = (int)x_;
} pos_.y = (int)y_;
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoom_h_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
rotate_.angle = value;
}
// Incrementa el valor de la variable
void MovingSprite::incAngle(double value)
{
rotate_.angle += value;
}
// Decrementa el valor de la variable
void MovingSprite::decAngle(double value)
{
rotate_.angle -= value;
}
// Obtiene el valor de la variable
bool MovingSprite::getRotate() const
{
return rotate_.enabled;
}
// Obtiene el valor de la variable
Uint16 MovingSprite::getRotateSpeed() const
{
return rotate_.speed;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (rotate_.enabled)
{
if (counter_ % rotate_.speed == 0)
{
incAngle(rotate_.amount);
}
}
}
// Establece el valor de la variable
void MovingSprite::setRotate(bool value)
{
rotate_.enabled = value;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
rotate_.speed = (value < 1) ? 1 : value;
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotate_.amount = value;
}
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
rotate_.enabled = false;
rotate_.angle = 0.0f;
}
// Actualiza las variables internas del objeto
void MovingSprite::update()
{
move();
rotate();
++counter_ %= 60000;
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotate_.amount *= -1;
}
// Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip)
{
flip_ = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
flip_ = (flip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return flip_;
}
// Devuelve el rectangulo donde está el sprite
SDL_Rect MovingSprite::getPos() const
{
return (SDL_Rect){(int)x_, (int)y_, pos_.w, pos_.h};
} }

View File

@@ -1,25 +1,27 @@
#pragma once #pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point #include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_RendererFlip #include <SDL2/SDL_render.h> // for SDL_RendererFlip
#include <SDL2/SDL_stdinc.h> // for Uint16 #include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory> // for shared_ptr #include <memory> // for shared_ptr
#include "sprite.h" // for Sprite #include "sprite.h" // for Sprite
class Texture; class Texture;
// Clase MovingSprite. Añade posicion y velocidad en punto flotante // Clase MovingSprite. Añade movimiento y efectos de rotación, zoom y flip al sprite
class MovingSprite : public Sprite class MovingSprite : public Sprite
{ {
protected: public:
struct Rotate struct Rotate
{ {
bool enabled; // Indica si ha de rotar bool enabled; // Indica si ha de rotar
int counter; // Contador
int speed; // Velocidad de giro int speed; // Velocidad de giro
float angle; // Angulo para dibujarlo double angle; // Angulo para dibujarlo
float amount; // Cantidad de grados a girar en cada iteración float amount; // Cantidad de grados a girar en cada iteración
SDL_Point *center; // Centro de rotación SDL_Point *center; // Centro de rotación
}; };
protected:
float x_; // Posición en el eje X float x_; // Posición en el eje X
float y_; // Posición en el eje Y float y_; // Posición en el eje Y
@@ -29,20 +31,13 @@ protected:
float ax_; // Aceleración en el eje X. Variación de la velocidad float ax_; // Aceleración en el eje X. Variación de la velocidad
float ay_; // Aceleración en el eje Y. Variación de la velocidad float ay_; // Aceleración en el eje Y. Variación de la velocidad
float zoom_w_; // Zoom aplicado a la anchura
float zoom_h_; // Zoom aplicado a la altura
int counter_; // Contador interno
Rotate rotate_; // Variables usada para controlar la rotación del sprite Rotate rotate_; // Variables usada para controlar la rotación del sprite
float zoom_w_; // Zoom aplicado a la anchura
float zoom_h_; // Zoom aplicado a la altura
SDL_RendererFlip flip_; // Indica como se voltea el sprite SDL_RendererFlip flip_; // Indica como se voltea el sprite
public: // Incrementa el valor del ángulo
// Constructor void updateAngle();
explicit MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr);
explicit MovingSprite(std::shared_ptr<Texture> texture = nullptr);
// Destructor
virtual ~MovingSprite() = default;
// Mueve el sprite // Mueve el sprite
void move(); void move();
@@ -50,6 +45,18 @@ public:
// Rota el sprite // Rota el sprite
void rotate(); void rotate();
// Sincroniza la posición
void syncPos();
public:
// Constructor
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos, MovingSprite::Rotate rotate, float zoom_w, float zoom_h, SDL_RendererFlip flip);
MovingSprite(std::shared_ptr<Texture> texture, SDL_Rect pos);
explicit MovingSprite(std::shared_ptr<Texture> texture);
// Destructor
~MovingSprite() = default;
// Actualiza las variables internas del objeto // Actualiza las variables internas del objeto
virtual void update(); virtual void update();
@@ -59,45 +66,28 @@ public:
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void render() override; void render() override;
// Obten el valor de la variable // Obtiene la variable
float getPosX() const; float getPosX() const;
float getPosY() const; float getPosY() const;
// Obten el valor de la variable
float getVelX() const; float getVelX() const;
float getVelY() const; float getVelY() const;
// Obten el valor de la variable
float getAccelX() const; float getAccelX() const;
float getAccelY() const; float getAccelY() const;
// Establece la variable
void setVelX(float value);
void setVelY(float value);
void setAccelX(float value);
void setAccelY(float value);
// Obten el valor de la variable // Obten el valor de la variable
float getZoomW() const; float getZoomW() const;
float getZoomH() const; float getZoomH() const;
// Obten el valor de la variable // Obten el valor de la variable
float getAngle() const; bool isRotating() const;
bool getRotate() const; double getAngle() const;
Uint16 getRotateSpeed() const; int getRotateSpeed() const;
// Establece la posición del objeto
void setPos(SDL_Rect rect) override;
void setPos(float x, float y);
// Devuelve el rectangulo donde está el sprite
SDL_Rect getPos() const override;
// Establece el valor de la variable
void setPosX(float value);
void setPosY(float value);
// Establece el valor de la variable
void setVelX(float value);
void setVelY(float value);
// Establece el valor de la variable
void setAccelX(float value);
void setAccelY(float value);
// Establece el valor de la variable // Establece el valor de la variable
void setZoomW(float value); void setZoomW(float value);
@@ -105,17 +95,15 @@ public:
// Establece el valor de la variable // Establece el valor de la variable
void setAngle(double vaue); void setAngle(double vaue);
void incAngle(double value);
void decAngle(double value); // Activa o desactiva el efecto derotación
void enableRotate();
void disableRotate();
// Establece el valor de la variable // Establece el valor de la variable
void setRotate(bool value);
void setRotateSpeed(int value); void setRotateSpeed(int value);
void setRotateAmount(double value); void setRotateAmount(double value);
// Quita el efecto de rotación y deja el sprite en su angulo inicial.
void disableRotate();
// Cambia el sentido de la rotación // Cambia el sentido de la rotación
void switchRotate(); void switchRotate();
@@ -128,5 +116,15 @@ public:
// Obtiene el valor de la variable // Obtiene el valor de la variable
SDL_RendererFlip getFlip(); SDL_RendererFlip getFlip();
// Establece la posición y_ el tamaño del objeto
void setPos(SDL_Rect rect);
// Establece el valor de las variables
void setPos(float x, float y);
// Establece el valor de la variable
void setPosX(float value);
// Establece el valor de la variable
void setPosY(float value);
}; };

342
source/notifier.cpp Normal file
View File

@@ -0,0 +1,342 @@
#include "notifier.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <string> // for string
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla...
#include "param.h" // for param
#include "sprite.h" // for Sprite
#include "text.h" // for Text
#include "texture.h" // for Texture
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
Notifier *Notifier::notifier_ = nullptr;
// [SINGLETON] Crearemos el objeto screen con esta función estática
void Notifier::init(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file)
{
Notifier::notifier_ = new Notifier(renderer, icon_file, bitmap_file, text_file, sound_file);
}
// [SINGLETON] Destruiremos el objeto screen con esta función estática
void Notifier::destroy()
{
delete Notifier::notifier_;
}
// [SINGLETON] Con este método obtenemos el objeto screen y podemos trabajar con él
Notifier *Notifier::get()
{
return Notifier::notifier_;
}
// Constructor
Notifier::Notifier(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file)
: renderer_(renderer),
text_(std::make_unique<Text>(bitmap_file, text_file, renderer)),
bg_color_(param.notification.color),
wait_time_(150),
stack_(false),
sound_(JA_LoadSound(sound_file.c_str()))
{
// Inicializa variables
has_icons_ = !icon_file.empty();
// Crea objetos
icon_texture_ = has_icons_ ? std::make_unique<Texture>(renderer, icon_file) : nullptr;
}
// Destructor
Notifier::~Notifier()
{
// Libera la memoria de los objetos
JA_DeleteSound(sound_);
notifications_.clear();
}
// Dibuja las notificaciones por pantalla
void Notifier::render()
{
for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{
notifications_[i].sprite->render();
}
}
// Actualiza el estado de las notificaiones
void Notifier::update()
{
for (int i = 0; i < (int)notifications_.size(); ++i)
{
// Si la notificación anterior está "saliendo", no hagas nada
if (i > 0)
{
if (notifications_[i - 1].status == NotificationStatus::RISING)
{
break;
}
}
notifications_[i].counter++;
// Hace sonar la notificación en el primer frame
if (notifications_[i].counter == 1)
{
if (param.notification.sound)
{
if (notifications_[i].status == NotificationStatus::RISING)
{ // Reproduce el sonido de la notificación
JA_PlaySound(sound_);
}
}
}
// Comprueba los estados
if (notifications_[i].status == NotificationStatus::RISING)
{
const float step = ((float)notifications_[i].counter / notifications_[i].travel_dist);
const int alpha = 255 * step;
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications_[i].rect.y++;
}
else
{
notifications_[i].rect.y--;
}
notifications_[i].texture->setAlpha(alpha);
if (notifications_[i].rect.y == notifications_[i].y)
{
notifications_[i].status = NotificationStatus::STAY;
notifications_[i].texture->setAlpha(255);
notifications_[i].counter = 0;
}
}
else if (notifications_[i].status == NotificationStatus::STAY)
{
if (notifications_[i].counter == wait_time_)
{
notifications_[i].status = NotificationStatus::VANISHING;
notifications_[i].counter = 0;
}
}
else if (notifications_[i].status == NotificationStatus::VANISHING)
{
const float step = (notifications_[i].counter / (float)notifications_[i].travel_dist);
const int alpha = 255 * (1 - step);
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications_[i].rect.y--;
}
else
{
notifications_[i].rect.y++;
}
notifications_[i].texture->setAlpha(alpha);
if (notifications_[i].rect.y == notifications_[i].y - notifications_[i].travel_dist)
{
notifications_[i].status = NotificationStatus::FINISHED;
}
}
notifications_[i].sprite->setPosition(notifications_[i].rect);
}
clearFinishedNotifications();
}
// Elimina las notificaciones finalizadas
void Notifier::clearFinishedNotifications()
{
for (int i = (int)notifications_.size() - 1; i >= 0; --i)
{
if (notifications_[i].status == NotificationStatus::FINISHED)
{
notifications_.erase(notifications_.begin() + i);
}
}
}
void Notifier::showText(std::string text1, std::string text2, int icon, std::string code)
{
// Cuenta el número de textos a mostrar
const int num_texts = !text1.empty() + !text2.empty();
// Si no hay texto, acaba
if (num_texts == 0)
{
return;
}
// Si solo hay un texto, lo coloca en la primera variable
if (num_texts == 1)
{
text1 += text2;
text2.clear();
}
// Si las notificaciones no se apilan, elimina las anteriores
if (!stack_)
{
clearNotifications();
}
// Inicializa variables
constexpr auto icon_size = 16;
constexpr auto padding_out = 1;
const auto padding_in_h = text_->getCharacterSize();
const auto padding_in_v = text_->getCharacterSize() / 2;
const auto icon_space = icon >= 0 ? icon_size + padding_in_h : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2;
const auto width = text_->lenght(txt) + (padding_in_h * 2) + icon_space;
const auto height = (text_->getCharacterSize() * num_texts) + (padding_in_v * 2);
const auto shape = NotificationShape::SQUARED;
// Posición horizontal
auto desp_h = 0;
if (param.notification.pos_h == NotifyPosition::LEFT)
{
desp_h = padding_out;
}
else if (param.notification.pos_h == NotifyPosition::MIDDLE)
{
desp_h = ((param.game.width / 2) - (width / 2));
}
else
{
desp_h = param.game.width - width - padding_out;
}
// Posición vertical
const int desp_v = (param.notification.pos_v == NotifyPosition::TOP) ? padding_out : (param.game.height - height - padding_out);
// Offset
const auto travel_dist = height + padding_out;
auto offset = 0;
if (param.notification.pos_v == NotifyPosition::TOP)
{
offset = (int)notifications_.size() > 0 ? notifications_.back().y + travel_dist : desp_v;
}
else
{
offset = (int)notifications_.size() > 0 ? notifications_.back().y - travel_dist : desp_v;
}
// Crea la notificacion
Notification n;
// Inicializa variables
n.code = code;
n.y = offset;
n.travel_dist = travel_dist;
n.counter = 0;
n.status = NotificationStatus::RISING;
n.text1 = text1;
n.text2 = text2;
n.shape = shape;
auto y_pos = offset + (param.notification.pos_v == NotifyPosition::TOP ? -travel_dist : travel_dist);
n.rect = {desp_h, y_pos, width, height};
// Crea la textura
n.texture = std::make_shared<Texture>(renderer_);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura
n.texture->setAsRenderTarget(renderer_);
// Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer_, bg_color_.r, bg_color_.g, bg_color_.b, 255);
SDL_Rect rect;
if (shape == NotificationShape::ROUNDED)
{
rect = {4, 0, width - (4 * 2), height};
SDL_RenderFillRect(renderer_, &rect);
rect = {4 / 2, 1, width - 4, height - 2};
SDL_RenderFillRect(renderer_, &rect);
rect = {1, 4 / 2, width - 2, height - 4};
SDL_RenderFillRect(renderer_, &rect);
rect = {0, 4, width, height - (4 * 2)};
SDL_RenderFillRect(renderer_, &rect);
}
else if (shape == NotificationShape::SQUARED)
{
SDL_RenderClear(renderer_);
}
// Dibuja el icono de la notificación
if (has_icons_ && icon >= 0 && num_texts == 2)
{
auto sp = std::make_unique<Sprite>(icon_texture_, (SDL_Rect){0, 0, icon_size, icon_size});
sp->setPosition({padding_in_h, padding_in_v, icon_size, icon_size});
sp->setSpriteClip({icon_size * (icon % 10), icon_size * (icon / 10), icon_size, icon_size});
sp->render();
}
// Escribe el texto de la notificación
Color color = {255, 255, 255};
if (num_texts == 2)
{ // Dos lineas de texto
text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color);
text_->writeColored(padding_in_h + icon_space, padding_in_v + text_->getCharacterSize() + 1, text2, color);
}
else
{ // Una linea de texto
text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color);
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer_, nullptr);
// Crea el sprite de la notificación
n.sprite = std::make_shared<Sprite>(n.texture, n.rect);
// Deja la notificación invisible
n.texture->setAlpha(0);
// Añade la notificación a la lista
notifications_.push_back(n);
}
// Indica si hay notificaciones activas
bool Notifier::isActive()
{
if ((int)notifications_.size() > 0)
{
return true;
}
return false;
}
// Finaliza y elimnina todas las notificaciones activas
void Notifier::clearNotifications()
{
for (int i = 0; i < (int)notifications_.size(); ++i)
{
notifications_[i].status = NotificationStatus::FINISHED;
}
clearFinishedNotifications();
}
// Obtiene los códigos de las notificaciones
std::vector<std::string> Notifier::getCodes()
{
std::vector<std::string> codes;
for (int i = 0; i < (int)notifications_.size(); ++i)
{
codes.push_back(notifications_[i].code);
}
return codes;
}

121
source/notifier.h Normal file
View File

@@ -0,0 +1,121 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string, basic_string
#include <vector> // for vector
#include "utils.h" // for Color
class Sprite;
class Text;
class Texture;
struct JA_Sound_t; // lines 12-12
class Notifier
{
private:
// [SINGLETON] Objeto notifier privado para Don Melitón
static Notifier *notifier_;
enum class NotificationStatus
{
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationPosition
{
UPPER_LEFT,
UPPER_CENTER,
UPPER_RIGHT,
MIDDLE_LEFT,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
};
enum class NotificationShape
{
ROUNDED,
SQUARED,
};
struct Notification
{
std::shared_ptr<Texture> texture;
std::shared_ptr<Sprite> sprite;
std::string text1;
std::string text2;
int counter;
NotificationStatus status;
NotificationPosition position;
NotificationShape shape;
SDL_Rect rect;
int y;
int travel_dist;
std::string code; // Permite asignar un código a la notificación
};
// Objetos y punteros
SDL_Renderer *renderer_; // El renderizador de la ventana
std::shared_ptr<Texture> icon_texture_; // Textura para los iconos de las notificaciones
std::unique_ptr<Text> text_; // Objeto para dibujar texto
// Variables
Color bg_color_; // Color de fondo de las notificaciones
int wait_time_; // Tiempo que se ve la notificación
std::vector<Notification> notifications_; // La lista de notificaciones activas
bool stack_; // Indica si las notificaciones se apilan
bool has_icons_; // Indica si el notificador tiene textura para iconos
JA_Sound_t *sound_; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
// Finaliza y elimnina todas las notificaciones activas
void clearNotifications();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos notifier desde fuera
// Constructor
Notifier(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file);
// Destructor
~Notifier();
public:
// [SINGLETON] Crearemos el objeto notifier con esta función estática
static void init(SDL_Renderer *renderer, std::string icon_file, std::string bitmap_file, std::string text_file, const std::string &sound_file);
// [SINGLETON] Destruiremos el objeto notifier con esta función estática
static void destroy();
// [SINGLETON] Con este método obtenemos el objeto notifier y podemos trabajar con él
static Notifier *get();
// Dibuja las notificaciones por pantalla
void render();
// Actualiza el estado de las notificaiones
void update();
/**
* @brief Muestra una notificación de texto por pantalla.
*
* @param text1 Primer texto opcional para mostrar (valor predeterminado: cadena vacía).
* @param text2 Segundo texto opcional para mostrar (valor predeterminado: cadena vacía).
* @param icon Icono opcional para mostrar (valor predeterminado: -1).
* @param code Permite asignar un código a la notificación (valor predeterminado: cadena vacía).
*/
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, std::string code = std::string());
// Indica si hay notificaciones activas
bool isActive();
// Obtiene los códigos de las notificaciones
std::vector<std::string> getCodes();
};

View File

@@ -1,309 +0,0 @@
#include "notify.h"
#include <SDL2/SDL_blendmode.h> // for SDL_BLENDMODE_BLEND
#include <SDL2/SDL_pixels.h> // for SDL_PIXELFORMAT_RGBA8888
#include <string> // for string
#include "jail_audio.h" // for JA_DeleteSound, JA_LoadSound, JA_Pla...
#include "param.h" // for param
#include "sprite.h" // for Sprite
#include "text.h" // for Text
#include "texture.h" // for Texture
// Constructor
Notify::Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile)
: renderer(renderer),
text(std::make_unique<Text>(bitmapFile, textFile, renderer)),
bgColor(param.notification.color),
waitTime(150),
stack(false),
sound(JA_LoadSound(soundFile.c_str()))
{
// Inicializa variables
hasIcons = !iconFile.empty();
// Crea objetos
iconTexture = hasIcons ? std::make_unique<Texture>(renderer, iconFile) : nullptr;
}
// Destructor
Notify::~Notify()
{
// Libera la memoria de los objetos
JA_DeleteSound(sound);
notifications.clear();
}
// Dibuja las notificaciones por pantalla
void Notify::render()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
notifications[i].sprite->render();
}
}
// Actualiza el estado de las notificaiones
void Notify::update()
{
for (int i = 0; i < (int)notifications.size(); ++i)
{
// Si la notificación anterior está "saliendo", no hagas nada
if (i > 0)
{
if (notifications[i - 1].status == NotificationStatus::RISING)
{
break;
}
}
notifications[i].counter++;
// Hace sonar la notificación en el primer frame
if (notifications[i].counter == 1)
{
if (param.notification.sound)
{
if (notifications[i].status == NotificationStatus::RISING)
{ // Reproduce el sonido de la notificación
JA_PlaySound(sound);
}
}
}
// Comprueba los estados
if (notifications[i].status == NotificationStatus::RISING)
{
const float step = ((float)notifications[i].counter / notifications[i].travelDist);
const int alpha = 255 * step;
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications[i].rect.y++;
}
else
{
notifications[i].rect.y--;
}
notifications[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y)
{
notifications[i].status = NotificationStatus::STAY;
notifications[i].texture->setAlpha(255);
notifications[i].counter = 0;
}
}
else if (notifications[i].status == NotificationStatus::STAY)
{
if (notifications[i].counter == waitTime)
{
notifications[i].status = NotificationStatus::VANISHING;
notifications[i].counter = 0;
}
}
else if (notifications[i].status == NotificationStatus::VANISHING)
{
const float step = (notifications[i].counter / (float)notifications[i].travelDist);
const int alpha = 255 * (1 - step);
if (param.notification.pos_v == NotifyPosition::TOP)
{
notifications[i].rect.y--;
}
else
{
notifications[i].rect.y++;
}
notifications[i].texture->setAlpha(alpha);
if (notifications[i].rect.y == notifications[i].y - notifications[i].travelDist)
{
notifications[i].status = NotificationStatus::FINISHED;
}
}
notifications[i].sprite->setPos(notifications[i].rect);
}
clearFinishedNotifications();
}
// Elimina las notificaciones finalizadas
void Notify::clearFinishedNotifications()
{
for (int i = (int)notifications.size() - 1; i >= 0; --i)
{
if (notifications[i].status == NotificationStatus::FINISHED)
{
notifications.erase(notifications.begin() + i);
}
}
}
// Muestra una notificación de texto por pantalla;
void Notify::showText(std::string text1, std::string text2, int icon)
{
// Cuenta el número de textos a mostrar
const int numTexts = !text1.empty() + !text2.empty();
// Si no hay texto, acaba
if (numTexts == 0)
{
return;
}
// Si solo hay un texto, lo coloca en la primera variable
if (numTexts == 1)
{
text1 += text2;
text2.clear();
}
// Si las notificaciones no se apilan, elimina las anteriores
if (!stack)
{
clearNotifications();
}
// Inicializa variables
constexpr auto iconSize = 16;
constexpr auto paddingOut = 1;
const auto paddingIn = text->getCharacterSize() / 2;
const auto iconSpace = icon >= 0 ? iconSize + paddingIn : 0;
const std::string txt = text1.length() > text2.length() ? text1 : text2;
const auto width = text->lenght(txt) + (paddingIn * 2) + iconSpace;
const auto height = (text->getCharacterSize() * numTexts) + (paddingIn * 2);
const auto shape = NotificationShape::SQUARED;
// Posición horizontal
auto despH = 0;
if (param.notification.pos_h == NotifyPosition::LEFT)
{
despH = paddingOut;
}
else if (param.notification.pos_h == NotifyPosition::MIDDLE)
{
despH = ((param.game.width / 2) - (width / 2));
}
else
{
despH = param.game.width - width - paddingOut;
}
// Posición vertical
const int despV = (param.notification.pos_v == NotifyPosition::TOP) ? paddingOut : (param.game.height - height - paddingOut);
// Offset
const auto travelDist = height + paddingOut;
auto offset = 0;
if (param.notification.pos_v == NotifyPosition::TOP)
{
offset = (int)notifications.size() > 0 ? notifications.back().y + travelDist : despV;
}
else
{
offset = (int)notifications.size() > 0 ? notifications.back().y - travelDist : despV;
}
// Crea la notificacion
Notification n;
// Inicializa variables
n.y = offset;
n.travelDist = travelDist;
n.counter = 0;
n.status = NotificationStatus::RISING;
n.text1 = text1;
n.text2 = text2;
n.shape = shape;
auto yPos = offset + (param.notification.pos_v == NotifyPosition::TOP ? -travelDist : travelDist);
n.rect = {despH, yPos, width, height};
// Crea la textura
n.texture = std::make_shared<Texture>(renderer);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
// Prepara para dibujar en la textura
n.texture->setAsRenderTarget(renderer);
// Dibuja el fondo de la notificación
SDL_SetRenderDrawColor(renderer, bgColor.r, bgColor.g, bgColor.b, 255);
SDL_Rect rect;
if (shape == NotificationShape::ROUNDED)
{
rect = {4, 0, width - (4 * 2), height};
SDL_RenderFillRect(renderer, &rect);
rect = {4 / 2, 1, width - 4, height - 2};
SDL_RenderFillRect(renderer, &rect);
rect = {1, 4 / 2, width - 2, height - 4};
SDL_RenderFillRect(renderer, &rect);
rect = {0, 4, width, height - (4 * 2)};
SDL_RenderFillRect(renderer, &rect);
}
else if (shape == NotificationShape::SQUARED)
{
SDL_RenderClear(renderer);
}
// Dibuja el icono de la notificación
if (hasIcons && icon >= 0 && numTexts == 2)
{
auto sp = std::make_unique<Sprite>((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture);
sp->setPos({paddingIn, paddingIn, iconSize, iconSize});
sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
sp->render();
}
// Escribe el texto de la notificación
Color color = {255, 255, 255};
if (numTexts == 2)
{ // Dos lineas de texto
text->writeColored(paddingIn + iconSpace, paddingIn, text1, color);
text->writeColored(paddingIn + iconSpace, paddingIn + text->getCharacterSize() + 1, text2, color);
}
else
{ // Una linea de texto
text->writeColored(paddingIn + iconSpace, paddingIn, text1, color);
}
// Deja de dibujar en la textura
SDL_SetRenderTarget(renderer, nullptr);
// Crea el sprite de la notificación
n.sprite = std::make_shared<Sprite>(n.rect, n.texture);
// Deja la notificación invisible
n.texture->setAlpha(0);
// Añade la notificación a la lista
notifications.push_back(n);
}
// Indica si hay notificaciones activas
bool Notify::active()
{
if ((int)notifications.size() > 0)
{
return true;
}
return false;
}
// Finaliza y elimnina todas las notificaciones activas
void Notify::clearNotifications()
{
for (int i = 0; i < (int)notifications.size(); ++i)
{
notifications[i].status = NotificationStatus::FINISHED;
}
clearFinishedNotifications();
}

View File

@@ -1,96 +0,0 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer
#include <memory> // for shared_ptr, unique_ptr
#include <string> // for string, basic_string
#include <vector> // for vector
#include "utils.h" // for Color
class Sprite;
class Text;
class Texture;
struct JA_Sound_t; // lines 12-12
class Notify
{
private:
enum class NotificationStatus
{
RISING,
STAY,
VANISHING,
FINISHED,
};
enum class NotificationPosition
{
UPPER_LEFT,
UPPER_CENTER,
UPPER_RIGHT,
MIDDLE_LEFT,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT,
};
enum class NotificationShape
{
ROUNDED,
SQUARED,
};
struct Notification
{
std::shared_ptr<Texture> texture;
std::shared_ptr<Sprite> sprite;
std::string text1;
std::string text2;
int counter;
NotificationStatus status;
NotificationPosition position;
NotificationShape shape;
SDL_Rect rect;
int y;
int travelDist;
};
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
std::shared_ptr<Texture> iconTexture; // Textura para los iconos de las notificaciones
std::unique_ptr<Text> text; // Objeto para dibujar texto
// Variables
Color bgColor; // Color de fondo de las notificaciones
int waitTime; // Tiempo que se ve la notificación
std::vector<Notification> notifications; // La lista de notificaciones activas
bool stack; // Indica si las notificaciones se apilan
bool hasIcons; // Indica si el notificador tiene textura para iconos
JA_Sound_t *sound; // Sonido a reproducir cuando suena la notificación
// Elimina las notificaciones finalizadas
void clearFinishedNotifications();
// Finaliza y elimnina todas las notificaciones activas
void clearNotifications();
public:
// Constructor
Notify(SDL_Renderer *renderer, std::string iconFile, std::string bitmapFile, std::string textFile, const std::string &soundFile);
// Destructor
~Notify();
// Dibuja las notificaciones por pantalla
void render();
// Actualiza el estado de las notificaiones
void update();
// Muestra una notificación de texto por pantalla;
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1);
// Indica si hay notificaciones activas
bool active();
};

View File

@@ -101,7 +101,7 @@ void OnScreenHelp::fillTexture()
auto controllersTexture = std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("controllers.png")); auto controllersTexture = std::make_shared<Texture>(Screen::get()->getRenderer(), Asset::get()->get("controllers.png"));
// Crea el sprite para dibujar los gráficos // Crea el sprite para dibujar los gráficos
auto sprite = std::make_unique<Sprite>((SDL_Rect){0, 0, 16, 16}, controllersTexture); auto sprite = std::make_unique<Sprite>(controllersTexture, (SDL_Rect){0, 0, 16, 16});
// Borra la textura // Borra la textura
SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0); SDL_SetRenderDrawColor(Screen::get()->getRenderer(), 0, 0, 0, 0);
@@ -186,7 +186,7 @@ auto OnScreenHelp::getLargestStringSize() -> int const
void OnScreenHelp::renderButton(Sprite *sprite, Text *text, const SDL_Rect &buttonClip, const SDL_Rect &buttonPos, int textId) void OnScreenHelp::renderButton(Sprite *sprite, Text *text, const SDL_Rect &buttonClip, const SDL_Rect &buttonPos, int textId)
{ {
sprite->setSpriteClip(buttonClip); sprite->setSpriteClip(buttonClip);
sprite->setPos(buttonPos); sprite->setPosition(buttonPos);
sprite->render(); sprite->render();
text->write(buttonPos.x + DESP.x, buttonPos.y + DESP.y, lang::getText(textId)); text->write(buttonPos.x + DESP.x, buttonPos.y + DESP.y, lang::getText(textId));
} }

View File

@@ -86,18 +86,14 @@ bool loadOptionsFile(std::string file_path)
bool success = true; bool success = true;
// Variables para manejar el fichero // Variables para manejar el fichero
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
std::ifstream file(file_path); std::ifstream file(file_path);
// Si el fichero se puede abrir // Si el fichero se puede abrir
if (file.good()) if (file.good())
{ {
// Procesa el fichero linea a linea // Procesa el fichero linea a linea
#ifdef VERBOSE
std::cout << "Reading file: " << file_name << std::endl; std::cout << "Reading file: " << file_name << std::endl;
#endif
std::string line; std::string line;
while (std::getline(file, line)) while (std::getline(file, line))
{ {
@@ -109,10 +105,8 @@ bool loadOptionsFile(std::string file_path)
// Procesa las dos subcadenas // Procesa las dos subcadenas
if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length()))) if (!setOptions(line.substr(0, pos), line.substr(pos + 1, line.length())))
{ {
#ifdef VERBOSE
std::cout << "Warning: file " << file_name << std::endl; std::cout << "Warning: file " << file_name << std::endl;
std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl; std::cout << "Unknown parameter " << line.substr(0, pos).c_str() << std::endl;
#endif
success = false; success = false;
} }
} }
@@ -152,22 +146,16 @@ bool loadOptionsFile(std::string file_path)
// Guarda el fichero de configuración // Guarda el fichero de configuración
bool saveOptionsFile(std::string file_path) bool saveOptionsFile(std::string file_path)
{ {
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
#endif
std::ofstream file(file_path); std::ofstream file(file_path);
if (!file.good()) if (!file.good())
{ {
#ifdef VERBOSE
std::cout << file_name << " can't be opened" << std::endl; std::cout << file_name << " can't be opened" << std::endl;
#endif
return false; return false;
} }
#ifdef VERBOSE
std::cout << "Writing file: " << file_name << std::endl; std::cout << "Writing file: " << file_name << std::endl;
#endif
// Opciones de video // Opciones de video
const auto value_video_mode_winow = std::to_string(static_cast<int>(ScreenVideoMode::WINDOW)); const auto value_video_mode_winow = std::to_string(static_cast<int>(ScreenVideoMode::WINDOW));

View File

@@ -65,109 +65,6 @@ void initParam()
param.notification.color.b = 48; param.notification.color.b = 48;
} }
// Establece valores para los parametros a partir de un fichero de texto
/*void loadParamsFromFile(std::string file_path)
{
// Pone valores por defecto a las variables
initParam();
// Variables para manejar el fichero
std::ifstream file(file_path);
std::string line;
std::string param1;
std::string param2;
// Si el fichero se puede abrir
if (file.good())
{
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::cout << "Reading file: " << file_name << std::endl;
#endif
// Procesa cada linea del fichero
while (std::getline(file, line))
{
// Reinicia variables
param1.clear();
param2.clear();
// Elimina los comentarios al final de una linea
{
// line = line.substr(0, line.find("#"));
auto pos = line.find("#");
if (pos != std::string::npos)
{
line.resize(pos);
}
}
// Ignora los espacios en blanco
int pos = 0;
while (pos < (int)line.size() && (int)line[pos] <= 32)
{
pos++;
}
// Si no ha llegado al final de la linea, es que hay algo escrito (no es una linea vacía)
if (pos < (int)line.size())
{
// Elimina el espacio en blanco
line = line.substr(pos, std::string::npos);
// Se queda con todo lo que no sean espacios en blanco
pos = 1;
while (pos <= (int)line.size() && (int)line[pos] > 32)
{
pos++;
}
// Si llega al final de la linea, falta la segunda palabra
if (pos < (int)line.size())
{
// Se queda con la primera palabra
param1 = line.substr(0, pos);
// Y recorta la linea
line = line.substr(pos, std::string::npos);
// Ignora los espacios en blanco
pos = 0;
while (pos <= (int)line.size() && (int)line[pos] <= 32)
{
pos++;
}
// Si llega al final de la linea, falta la segunda palabra
if (pos < (int)line.size())
{
// Elimina el espacio en blanco
line = line.substr(pos, std::string::npos);
// Ignora los espacios en blanco
pos = 1;
while (pos <= (int)line.size() && (int)line[pos] > 32)
{
pos++;
}
// Se queda con la segunda palabra
param2 = line.substr(0, pos);
}
}
}
setParams(param1, param2);
}
// Cierra el fichero
file.close();
}
#ifdef VERBOSE
else
std::cout << "Failed to load file: " << file_path << std::endl;
#endif
precalculateZones();
}*/
void loadParamsFromFile(const std::string &file_path) void loadParamsFromFile(const std::string &file_path)
{ {
// Inicializa los parámetros con valores por defecto // Inicializa los parámetros con valores por defecto
@@ -177,16 +74,12 @@ void loadParamsFromFile(const std::string &file_path)
std::ifstream file(file_path); std::ifstream file(file_path);
if (!file.is_open()) if (!file.is_open())
{ {
#ifdef VERBOSE
std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl; std::cerr << "Error: No se pudo abrir el archivo " << file_path << std::endl;
#endif
throw std::runtime_error("No se pudo abrir el archivo: " + file_path); throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
} }
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
std::cout << "Reading file: " << file_name << std::endl; std::cout << "Reading file: " << file_name << std::endl;
#endif
std::string line, param1, param2; std::string line, param1, param2;
while (std::getline(file, line)) while (std::getline(file, line))
@@ -255,6 +148,11 @@ bool setParams(const std::string &var, const std::string &value)
param.game.play_area.rect.h = std::stoi(value); param.game.play_area.rect.h = std::stoi(value);
} }
else if (var == "game.enter_name_seconds")
{
param.game.enter_name_seconds = std::stoi(value);
}
// FADE // FADE
else if (var == "fade.num_squares_width") else if (var == "fade.num_squares_width")
{ {

View File

@@ -3,7 +3,7 @@
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <stdlib.h> // for rand #include <stdlib.h> // for rand
#include <algorithm> // for max, min #include <algorithm> // for max, min
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "input.h" // for inputs_e #include "input.h" // for inputs_e
#include "param.h" // for param #include "param.h" // for param
#include "texture.h" // for Texture #include "texture.h" // for Texture
@@ -12,8 +12,8 @@
// Constructor // Constructor
Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations) Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations)
: player_sprite_(std::make_unique<AnimatedSprite>(texture[0], "", animations[0])), : player_sprite_(std::make_unique<AnimatedSprite>(texture[0], animations[0])),
power_sprite_(std::make_unique<AnimatedSprite>(texture[1], "", animations[1])), power_sprite_(std::make_unique<AnimatedSprite>(texture[1], animations[1])),
enter_name_(std::make_unique<EnterName>()), enter_name_(std::make_unique<EnterName>()),
play_area_(play_area), play_area_(play_area),
id_(id), id_(id),
@@ -55,7 +55,9 @@ void Player::init()
coffees_ = 0; coffees_ = 0;
input_ = true; input_ = true;
continue_ticks_ = 0; continue_ticks_ = 0;
continue_counter_ = 20; continue_counter_ = 10;
enter_name_ticks_ = 0;
enter_name_counter_ = param.game.enter_name_seconds;
width_ = 30; width_ = 30;
height_ = 30; height_ = 30;
collider_.r = 9; collider_.r = 9;
@@ -149,11 +151,11 @@ void Player::setInputEnteringName(InputType input)
switch (input) switch (input)
{ {
case InputType::LEFT: case InputType::LEFT:
enter_name_->decPos(); enter_name_->decPosition();
break; break;
case InputType::RIGHT: case InputType::RIGHT:
enter_name_->incPos(); enter_name_->incPosition();
break; break;
case InputType::UP: case InputType::UP:
@@ -277,10 +279,10 @@ void Player::setAnimation()
} }
// Actualiza las animaciones de los sprites // Actualiza las animaciones de los sprites
player_sprite_->animate(); player_sprite_->update();
// powerSprite->setFlip(flip_walk); // powerSprite->setFlip(flip_walk);
power_sprite_->animate(); power_sprite_->update();
} }
// Obtiene el valor de la variable // Obtiene el valor de la variable
@@ -347,6 +349,7 @@ void Player::update()
updatePowerUpCounter(); updatePowerUpCounter();
updateInvulnerable(); updateInvulnerable();
updateContinueCounter(); updateContinueCounter();
updateEnterNameCounter();
updateScoreboard(); updateScoreboard();
} }
@@ -711,6 +714,20 @@ void Player::updateContinueCounter()
} }
} }
// Actualiza el contador de entrar nombre
void Player::updateEnterNameCounter()
{
if (status_playing_ == PlayerStatus::ENTERING_NAME)
{
constexpr Uint32 ticks_speed = 1000;
if (SDL_GetTicks() - enter_name_ticks_ > ticks_speed)
{
decEnterNameCounter();
}
}
}
// Le asigna un panel en el marcador al jugador // Le asigna un panel en el marcador al jugador
void Player::setScoreBoardPanel(int panel) void Player::setScoreBoardPanel(int panel)
{ {
@@ -734,6 +751,18 @@ void Player::decContinueCounter()
} }
} }
// Decrementa el contador de entrar nombre
void Player::decEnterNameCounter()
{
enter_name_ticks_ = SDL_GetTicks();
--enter_name_counter_;
if (enter_name_counter_ < 0)
{
enter_name_counter_ = param.game.enter_name_seconds;
setStatusPlaying(PlayerStatus::CONTINUE);
}
}
// Establece el nombre del jugador // Establece el nombre del jugador
void Player::setName(const std::string &name) void Player::setName(const std::string &name)
{ {
@@ -763,7 +792,7 @@ int Player::getRecordNamePos() const
{ {
if (enter_name_) if (enter_name_)
{ {
return enter_name_->getPos(); return enter_name_->getPosition();
} }
return 0; return 0;

View File

@@ -1,16 +1,17 @@
#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 Uint32 #include <SDL2/SDL_stdinc.h> // for Uint32
#include <memory> // for unique_ptr, shared_ptr #include <memory> // for unique_ptr, shared_ptr
#include <string> // for string #include <string> // for string
#include <vector> // for vector #include <vector> // for vector
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
#include "enter_name.h" // for EnterName #include "smart_sprite.h" // for SpriteAnimated
#include "utils.h" // for Circle #include "enter_name.h" // for EnterName
#include "utils.h" // for Circle
class Texture; class Texture;
enum class InputType : int; enum class InputType : int;
enum class ScoreboardMode; // lines 12-12 enum class ScoreboardMode; // lines 12-12
// Estados del jugador // Estados del jugador
enum class PlayerStatus enum class PlayerStatus
@@ -42,10 +43,10 @@ class Player
{ {
private: private:
// Objetos y punteros // Objetos y punteros
std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador std::unique_ptr<AnimatedSprite> player_sprite_; // Sprite para dibujar el jugador
std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope std::unique_ptr<AnimatedSprite> power_sprite_; // Sprite para dibujar el aura del jugador con el poder a tope
std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre std::unique_ptr<EnterName> enter_name_; // Clase utilizada para introducir el nombre
SDL_Rect *play_area_; // Rectangulo con la zona de juego SDL_Rect *play_area_; // Rectangulo con la zona de juego
// Variables // Variables
int id_; // Numero de identificación para el jugador int id_; // Numero de identificación para el jugador
@@ -77,9 +78,11 @@ private:
Uint32 continue_ticks_; // Variable para poder cambiar el contador de continue en función del tiempo Uint32 continue_ticks_; // Variable para poder cambiar el contador de continue en función del tiempo
int scoreboard_panel_; // Panel del marcador asociado al jugador int scoreboard_panel_; // Panel del marcador asociado al jugador
std::string name_; // Nombre del jugador std::string name_; // Nombre del jugador
std::string record_name_; // Nombre del jugador para l atabla de mejores puntuaciones std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
int controller_index_; // Indice del array de mandos que utilizará para moverse int controller_index_; // Indice del array de mandos que utilizará para moverse
bool demo_; // Para que el jugador sepa si está en el modo demostración bool demo_; // Para que el jugador sepa si está en el modo demostración
int enter_name_counter_; // Contador para poner nombre
Uint32 enter_name_ticks_; // Variable para poder cambiar el contador de poner nombre en función del tiempo
// Actualiza el circulo de colisión a la posición del jugador // Actualiza el circulo de colisión a la posición del jugador
void shiftColliders(); void shiftColliders();
@@ -90,6 +93,12 @@ private:
// Actualiza el contador de continue // Actualiza el contador de continue
void updateContinueCounter(); void updateContinueCounter();
// Actualiza el contador de entrar nombre
void updateEnterNameCounter();
// Decrementa el contador de entrar nombre
void decEnterNameCounter();
// Indica si el jugador se puede dibujar // Indica si el jugador se puede dibujar
bool isRenderable() const; bool isRenderable() const;

View File

@@ -66,7 +66,7 @@ Scoreboard::Scoreboard(SDL_Renderer *renderer)
// Recalcula las anclas de los elementos // Recalcula las anclas de los elementos
recalculateAnchors(); recalculateAnchors();
power_meter_sprite_->setPos({slot4_2_.x - 20, slot4_2_.y, 40, 7}); power_meter_sprite_->setPosition({slot4_2_.x - 20, slot4_2_.y, 40, 7});
// Crea la textura de fondo // Crea la textura de fondo
background_ = nullptr; background_ = nullptr;
@@ -418,8 +418,8 @@ void Scoreboard::recalculateAnchors()
// Recoloca los sprites // Recoloca los sprites
if (power_meter_sprite_) if (power_meter_sprite_)
{ {
power_meter_sprite_->setPosX(slot4_2_.x - 20); power_meter_sprite_->setX(slot4_2_.x - 20);
power_meter_sprite_->setPosY(slot4_2_.y); power_meter_sprite_->setY(slot4_2_.y);
} }
} }

View File

@@ -12,7 +12,7 @@
#include "dbgtxt.h" // for dbg_print #include "dbgtxt.h" // for dbg_print
#include "global_inputs.h" // for servicePressedCounter #include "global_inputs.h" // for servicePressedCounter
#include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT #include "input.h" // for Input, inputs_e, INPUT_DO_NOT_ALLOW_REPEAT
#include "notify.h" // for Notify #include "notifier.h" // for Notify
#include "on_screen_help.h" // for OnScreenHelp #include "on_screen_help.h" // for OnScreenHelp
#include "options.h" // for options #include "options.h" // for options
#include "param.h" // for param #include "param.h" // for param
@@ -47,7 +47,6 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
: window_(window), : window_(window),
renderer_(renderer), renderer_(renderer),
notify_(std::make_unique<Notify>(renderer_, std::string(), Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), Asset::get()->get("notify.wav"))),
game_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), game_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
shader_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)), shader_canvas_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
@@ -127,7 +126,7 @@ void Screen::blit()
displayInfo(); displayInfo();
// Muestra las notificaciones // Muestra las notificaciones
notify_->render(); Notifier::get()->render();
#ifdef NO_SHADERS #ifdef NO_SHADERS
// Vuelve a dejar el renderizador en modo normal // Vuelve a dejar el renderizador en modo normal
@@ -200,8 +199,9 @@ void Screen::setVideoMode(ScreenVideoMode videoMode)
SDL_ShowCursor(SDL_ENABLE); SDL_ShowCursor(SDL_ENABLE);
#endif #endif
// Modifica el tamaño de la ventana // Modifica el tamaño de la ventana
SDL_Point pos = getNewPosition();
SDL_SetWindowSize(window_, param.game.width * options.video.window.size, param.game.height * options.video.window.size); SDL_SetWindowSize(window_, param.game.width * options.video.window.size, param.game.height * options.video.window.size);
SDL_SetWindowPosition(window_, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_SetWindowPosition(window_, pos.x, pos.y);
break; break;
} }
@@ -280,7 +280,7 @@ void Screen::setBlendMode(SDL_BlendMode blendMode)
void Screen::update() void Screen::update()
{ {
updateShakeEffect(); updateShakeEffect();
notify_->update(); Notifier::get()->update();
updateFPS(); updateFPS();
OnScreenHelp::get()->update(); OnScreenHelp::get()->update();
} }
@@ -294,7 +294,7 @@ void Screen::checkInput()
{ {
switchVideoMode(); switchVideoMode();
const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? "Window" : "Fullscreen"; const std::string mode = options.video.mode == ScreenVideoMode::WINDOW ? "Window" : "Fullscreen";
showNotification(mode + " mode"); Notifier::get()->showText(mode + " mode");
return; return;
} }
@@ -303,7 +303,7 @@ void Screen::checkInput()
{ {
decWindowSize(); decWindowSize();
const std::string size = std::to_string(options.video.window.size); const std::string size = std::to_string(options.video.window.size);
showNotification("Window size x" + size); Notifier::get()->showText("Window size x" + size);
return; return;
} }
@@ -312,7 +312,7 @@ void Screen::checkInput()
{ {
incWindowSize(); incWindowSize();
const std::string size = std::to_string(options.video.window.size); const std::string size = std::to_string(options.video.window.size);
showNotification("Window size x" + size); Notifier::get()->showText("Window size x" + size);
return; return;
} }
#endif #endif
@@ -442,7 +442,7 @@ void Screen::switchShaders()
options.video.shaders = !options.video.shaders; options.video.shaders = !options.video.shaders;
setVideoMode(options.video.mode); setVideoMode(options.video.mode);
const std::string value = options.video.shaders ? "on" : "off"; const std::string value = options.video.shaders ? "on" : "off";
showNotification("Shaders " + value); Notifier::get()->showText("Shaders " + value);
} }
// Atenua la pantalla // Atenua la pantalla
@@ -451,12 +451,6 @@ void Screen::attenuate(bool value)
attenuate_effect_ = value; attenuate_effect_ = value;
} }
// Muestra una notificación de texto por pantalla;
void Screen::showNotification(const std::string &text1, const std::string &text2, int icon)
{
notify_->showText(text1, text2, icon);
}
// Obtiene el puntero al renderizador // Obtiene el puntero al renderizador
SDL_Renderer *Screen::getRenderer() SDL_Renderer *Screen::getRenderer()
{ {
@@ -490,8 +484,38 @@ void Screen::displayInfo()
} }
} }
// Indica si hay alguna notificación activa en pantalla // Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
bool Screen::notificationsAreActive() const SDL_Point Screen::getNewPosition()
{ {
return notify_->active(); // Obtiene la posición actual de la ventana
SDL_Point current_position;
SDL_GetWindowPosition(window_, &current_position.x, &current_position.y);
// Obtiene las dimensiones actuales de la ventana
int current_width, current_height;
SDL_GetWindowSize(window_, &current_width, &current_height);
// Obtiene las dimesiones que tendrá la ventana
const int new_width = param.game.width * options.video.window.size;
const int new_height = param.game.height * options.video.window.size;
// Obtiene el centro de la ventana actual
SDL_Point center;
center.x = current_position.x + current_width / 2;
center.y = current_position.y + current_height / 2;
// Calcula la nueva posición a partir del centro y las nuevas diemsiones
SDL_Point new_pos;
new_pos.x = center.x - new_width / 2;
new_pos.y = center.y - new_height / 2;
// Obtiene las dimensiones del escritorio
SDL_DisplayMode DM;
SDL_GetCurrentDisplayMode(0, &DM);
// Evita que la ventana quede fuera del escritorio
new_pos.x = std::clamp(new_pos.x, 30, DM.w - new_width);
new_pos.y = std::clamp(new_pos.y, 30, DM.h - new_height);
return new_pos;
} }

View File

@@ -8,7 +8,6 @@
#include <string> // for basic_string, string #include <string> // for basic_string, string
#include "utils.h" // for Color #include "utils.h" // for Color
#include <memory> #include <memory>
class Notify;
enum class ScreenFilter : int enum class ScreenFilter : int
{ {
@@ -29,11 +28,10 @@ private:
static Screen *screen_; static Screen *screen_;
// Objetos y punteros // Objetos y punteros
SDL_Window *window_; // Ventana de la aplicación SDL_Window *window_; // Ventana de la aplicación
SDL_Renderer *renderer_; // El renderizador de la ventana SDL_Renderer *renderer_; // El renderizador de la ventana
std::unique_ptr<Notify> notify_; // Pinta notificaciones en pantalla SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador
SDL_Texture *game_canvas_; // Textura donde se dibuja todo antes de volcarse al renderizador SDL_Texture *shader_canvas_; // Textura para pasarle al shader desde gameCanvas
SDL_Texture *shader_canvas_; // Textura para pasarle al shader desde gameCanvas
// Variables // Variables
SDL_Rect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla SDL_Rect src_rect_; // Coordenadas de donde va a pillar la textura del juego para dibujarla
@@ -85,6 +83,9 @@ private:
// Muestra información por pantalla // Muestra información por pantalla
void displayInfo(); void displayInfo();
// Calcula la nueva posición de la ventana a partir de la antigua al cambiarla de tamaño
SDL_Point getNewPosition();
// [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos screen desde fuera // [SINGLETON] Ahora el constructor y el destructor son privados, para no poder crear objetos screen desde fuera
// Constructor // Constructor
@@ -151,12 +152,6 @@ public:
// Atenua la pantalla // Atenua la pantalla
void attenuate(bool value); void attenuate(bool value);
// Muestra una notificación de texto por pantalla;
void showNotification(const std::string &text1 = std::string(), const std::string &text2 = std::string(), int icon = -1);
// Indica si hay alguna notificación activa en pantalla
bool notificationsAreActive() const;
// Obtiene el puntero al renderizador // Obtiene el puntero al renderizador
SDL_Renderer *getRenderer(); SDL_Renderer *getRenderer();
}; };

View File

@@ -1,5 +1,4 @@
#include "smart_sprite.h" #include "smart_sprite.h"
#include "moving_sprite.h" // for MovingSprite
class Texture; class Texture;
// Constructor // Constructor
@@ -14,8 +13,7 @@ void SmartSprite::init()
{ {
finished_counter_ = 0; finished_counter_ = 0;
on_destination_ = false; on_destination_ = false;
dest_x_ = 0; dest_x_ = dest_y_ = 0;
dest_y_ = 0;
finished_ = false; finished_ = false;
enabled_ = false; enabled_ = false;
} }
@@ -127,7 +125,7 @@ void SmartSprite::checkMove()
void SmartSprite::checkFinished() void SmartSprite::checkFinished()
{ {
// Comprueba si ha llegado a su destino // Comprueba si ha llegado a su destino
on_destination_ = (getPosX() == dest_x_ && getPosY() == dest_y_) ? true : false; on_destination_ = (getPosX() == dest_x_ && getPosY() == dest_y_);
if (on_destination_) if (on_destination_)
{ {

View File

@@ -1,10 +1,10 @@
#pragma once #pragma once
#include <memory> // for shared_ptr #include <memory> // for shared_ptr
#include "animated_sprite.h" // for AnimatedSprite #include "animated_sprite.h" // for SpriteAnimated
class Texture; class Texture;
// Clase SmartSprite // Clase SpriteSmart
class SmartSprite : public AnimatedSprite class SmartSprite : public AnimatedSprite
{ {
private: private:
@@ -16,12 +16,12 @@ private:
bool finished_; // Indica si ya ha terminado bool finished_; // Indica si ya ha terminado
bool enabled_; // Indica si el objeto está habilitado bool enabled_; // Indica si el objeto está habilitado
// Comprueba el movimiento
void checkMove();
// Comprueba si ha terminado // Comprueba si ha terminado
void checkFinished(); void checkFinished();
// Comprueba el movimiento
void checkMove();
public: public:
// Constructor // Constructor
explicit SmartSprite(std::shared_ptr<Texture> texture); explicit SmartSprite(std::shared_ptr<Texture> texture);

View File

@@ -1,18 +1,20 @@
#include "sprite.h" #include "sprite.h"
// Constructor // Constructor
Sprite::Sprite(int x, int y, int w, int h, std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture, int x, int y, int w, int h)
: texture_(texture), : texture_(texture),
pos_((SDL_Rect){x, y, w, h}), pos_((SDL_Rect){x, y, w, h}),
sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture, SDL_Rect rect)
: texture_(texture), : texture_(texture),
pos_(rect), pos_(rect),
sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {} sprite_clip_((SDL_Rect){0, 0, pos_.w, pos_.h}) {}
Sprite::Sprite(std::shared_ptr<Texture> texture) Sprite::Sprite(std::shared_ptr<Texture> texture)
: texture_(texture) {} : texture_(texture),
pos_({0, 0, texture_->getWidth(), texture_->getHeight()}),
sprite_clip_(pos_) {}
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
void Sprite::render() void Sprite::render()
@@ -21,13 +23,13 @@ void Sprite::render()
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getIntPosX() const int Sprite::getX() const
{ {
return pos_.x; return pos_.x;
} }
// Obten el valor de la variable // Obten el valor de la variable
int Sprite::getIntPosY() const int Sprite::getY() const
{ {
return pos_.y; return pos_.y;
} }
@@ -45,33 +47,33 @@ int Sprite::getHeight() const
} }
// Establece la posición del objeto // Establece la posición del objeto
void Sprite::setPos(int x, int y) void Sprite::setPosition(int x, int y)
{ {
pos_.x = x; pos_.x = x;
pos_.y = y; pos_.y = y;
} }
// Establece la posición del objeto // Establece la posición del objeto
void Sprite::setPos(SDL_Point p) void Sprite::setPosition(SDL_Point p)
{ {
pos_.x = p.x; pos_.x = p.x;
pos_.y = p.y; pos_.y = p.y;
} }
// Establece la posición del objeto // Establece la posición del objeto
void Sprite::setPos(SDL_Rect r) void Sprite::setPosition(SDL_Rect r)
{ {
pos_ = r; pos_ = r;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosX(int x) void Sprite::setX(int x)
{ {
pos_.x = x; pos_.x = x;
} }
// Establece el valor de la variable // Establece el valor de la variable
void Sprite::setPosY(int y) void Sprite::setY(int y)
{ {
pos_.y = y; pos_.y = y;
} }
@@ -119,19 +121,19 @@ void Sprite::setTexture(std::shared_ptr<Texture> texture)
} }
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
SDL_Rect Sprite::getPos() const SDL_Rect Sprite::getPosition() const
{ {
return pos_; return pos_;
} }
// Incrementa el valor de la variable // Incrementa el valor de la variable
void Sprite::incPosX(int value) void Sprite::incX(int value)
{ {
pos_.x += value; pos_.x += value;
} }
// Incrementa el valor de la variable // Incrementa el valor de la variable
void Sprite::incPosY(int value) void Sprite::incY(int value)
{ {
pos_.y += value; pos_.y += value;
} }

View File

@@ -15,39 +15,39 @@ protected:
public: public:
// Constructor // Constructor
explicit Sprite(int x = 0, int y = 0, int w = 0, int h = 0, std::shared_ptr<Texture> texture = nullptr); Sprite(std::shared_ptr<Texture>, int x, int y, int w, int h);
explicit Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture = nullptr); Sprite(std::shared_ptr<Texture>, SDL_Rect rect);
explicit Sprite(std::shared_ptr<Texture> texture = nullptr); explicit Sprite(std::shared_ptr<Texture>);
// Destructor // Destructor
virtual ~Sprite() = default; ~Sprite() = default;
// Muestra el sprite por pantalla // Muestra el sprite por pantalla
virtual void render(); virtual void render();
// Obten el valor de la variable // Obten el valor de la variable
int getIntPosX() const; int getX() const;
int getIntPosY() const; int getY() const;
int getWidth() const; int getWidth() const;
int getHeight() const; int getHeight() const;
// Devuelve el rectangulo donde está el sprite // Devuelve el rectangulo donde está el sprite
virtual SDL_Rect getPos() const; SDL_Rect getPosition() const;
// Establece el valor de la variable // Establece el valor de la variable
void setPosX(int x); void setX(int x);
void setPosY(int y); void setY(int y);
void setWidth(int w); void setWidth(int w);
void setHeight(int h); void setHeight(int h);
// Establece la posición del objeto // Establece la posición del objeto
void setPos(int x, int y); void setPosition(int x, int y);
void setPos(SDL_Point p); void setPosition(SDL_Point p);
virtual void setPos(SDL_Rect r); void setPosition(SDL_Rect r);
// Incrementa el valor de la variable // Incrementa el valor de la variable
void incPosX(int value); void incX(int value);
void incPosY(int value); void incY(int value);
// Obten el valor de la variable // Obten el valor de la variable
SDL_Rect getSpriteClip() const; SDL_Rect getSpriteClip() const;

View File

@@ -1,10 +1,10 @@
#include "text.h" #include "text.h"
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <fstream> // for basic_ostream, basic_ifstream, basic_istream #include <fstream> // for basic_ostream, basic_ifstream, basic_istream
#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 #include "utils.h" // for Color
// Llena una estructuta TextFile desde un fichero // Llena una estructuta TextFile desde un fichero
TextFile LoadTextFile(std::string file_path) TextFile LoadTextFile(std::string file_path)
@@ -22,9 +22,7 @@ TextFile LoadTextFile(std::string file_path)
} }
// Abre el fichero para leer los valores // Abre el fichero para leer los valores
#ifdef VERBOSE
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str(); const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str();
#endif
std::ifstream file(file_path); std::ifstream file(file_path);
if (file.is_open() && file.good()) if (file.is_open() && file.good())
@@ -56,19 +54,15 @@ TextFile LoadTextFile(std::string file_path)
line_read++; line_read++;
}; };
// Cierra el fichero // Cierra el fichero
#ifdef VERBOSE
std::cout << "Text loaded: " << file_name << std::endl; std::cout << "Text loaded: " << file_name << std::endl;
#endif
file.close(); file.close();
} }
// El fichero no se puede abrir // El fichero no se puede abrir
else else
{ {
#ifdef VERBOSE
std::cout << "Warning: Unable to open " << file_name << " file" << std::endl; std::cout << "Warning: Unable to open " << file_name << " file" << std::endl;
#endif
} }
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho // Establece las coordenadas para cada caracter ascii de la cadena y su ancho
@@ -99,7 +93,7 @@ Text::Text(const std::string &bitmap_file, const std::string &text_file, SDL_Ren
// Crea los objetos // Crea los objetos
texture_ = std::make_shared<Texture>(renderer, bitmap_file); texture_ = std::make_shared<Texture>(renderer, bitmap_file);
sprite_ = std::make_unique<Sprite>((SDL_Rect){0, 0, box_width_, box_height_}, texture_); sprite_ = std::make_unique<Sprite>(texture_, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -122,7 +116,7 @@ Text::Text(const std::string &text_file, std::shared_ptr<Texture> texture)
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>((SDL_Rect){0, 0, box_width_, box_height_}, texture); sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -142,7 +136,7 @@ Text::Text(TextFile *text_file, std::shared_ptr<Texture> texture)
} }
// Crea los objetos // Crea los objetos
sprite_ = std::make_unique<Sprite>((SDL_Rect){0, 0, box_width_, box_height_}, texture); sprite_ = std::make_unique<Sprite>(texture, (SDL_Rect){0, 0, box_width_, box_height_});
// Inicializa variables // Inicializa variables
fixed_width_ = false; fixed_width_ = false;
@@ -158,14 +152,14 @@ void Text::write(int x, int y, const std::string &text, int kerning, int lenght)
lenght = text.length(); lenght = text.length();
} }
sprite_->setPosY(y); sprite_->setY(y);
const auto width = sprite_->getWidth(); const auto width = sprite_->getWidth();
const auto height = sprite_->getHeight(); const auto height = sprite_->getHeight();
for (int i = 0; i < lenght; ++i) for (int i = 0; i < lenght; ++i)
{ {
const auto index = static_cast<int>(text[i]); const auto index = static_cast<int>(text[i]);
sprite_->setSpriteClip(offset_[index].x, offset_[index].y, width, height); sprite_->setSpriteClip(offset_[index].x, offset_[index].y, width, height);
sprite_->setPosX(x + shift); sprite_->setX(x + shift);
sprite_->render(); sprite_->render();
shift += fixed_width_ ? box_width_ : (offset_[int(text[i])].w + kerning); shift += fixed_width_ ? box_width_ : (offset_[int(text[i])].w + kerning);
} }

View File

@@ -61,17 +61,13 @@ bool Texture::loadFromFile(const std::string &path)
unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format); unsigned char *data = stbi_load(path.c_str(), &width, &height, &orig_format, req_format);
if (!data) if (!data)
{ {
#ifdef VERBOSE
std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl; std::cout << "Loading image failed: " << stbi_failure_reason() << std::endl;
#endif
exit(1); exit(1);
} }
else else
{ {
#ifdef VERBOSE
const std::string file_name = path.substr(path.find_last_of("\\/") + 1); const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
std::cout << "Image loaded: " << file_name << std::endl; std::cout << "Image loaded: " << file_name << std::endl;
#endif
} }
int depth, pitch; int depth, pitch;
@@ -99,9 +95,7 @@ bool Texture::loadFromFile(const std::string &path)
auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void *>(data), width, height, depth, pitch, pixel_format); auto loadedSurface = SDL_CreateRGBSurfaceWithFormatFrom(static_cast<void *>(data), width, height, depth, pitch, pixel_format);
if (loadedSurface == nullptr) if (loadedSurface == nullptr)
{ {
#ifdef VERBOSE
std::cout << "Unable to load image " << path << std::endl; std::cout << "Unable to load image " << path << std::endl;
#endif
} }
else else
{ {
@@ -109,9 +103,7 @@ bool Texture::loadFromFile(const std::string &path)
newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface); newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface);
if (newTexture == nullptr) if (newTexture == nullptr)
{ {
#ifdef VERBOSE
std::cout << "Unable to create texture from " << path << "! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create texture from " << path << "! SDL Error: " << SDL_GetError() << std::endl;
#endif
} }
else else
{ {
@@ -137,9 +129,7 @@ bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL
texture_ = SDL_CreateTexture(renderer_, format, access, width, height); texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_) if (!texture_)
{ {
#ifdef VERBOSE
std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl; std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl;
#endif
} }
else else
{ {

View File

@@ -60,7 +60,7 @@ void Tiledbg::fillTexture()
{ {
// Crea los objetos para pintar en la textura de fondo // Crea los objetos para pintar en la textura de fondo
auto bg_tile_texture = std::make_shared<Texture>(renderer_, texture_path_); auto bg_tile_texture = std::make_shared<Texture>(renderer_, texture_path_);
auto tile = std::make_unique<Sprite>((SDL_Rect){0, 0, tile_width_, tile_height_}, bg_tile_texture); auto tile = std::make_unique<Sprite>(bg_tile_texture, (SDL_Rect){0, 0, tile_width_, tile_height_});
// Prepara para dibujar sobre la textura // Prepara para dibujar sobre la textura
auto temp = SDL_GetRenderTarget(renderer_); auto temp = SDL_GetRenderTarget(renderer_);
@@ -74,8 +74,8 @@ void Tiledbg::fillTexture()
{ {
for (int j = 0; j < j_max; ++j) for (int j = 0; j < j_max; ++j)
{ {
tile->setPosX(i * tile_width_); tile->setX(i * tile_width_);
tile->setPosY(j * tile_height_); tile->setY(j * tile_height_);
tile->render(); tile->render();
} }
} }

View File

@@ -1,24 +1,25 @@
#include "title.h" #include "title.h"
#include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN #include <SDL2/SDL_events.h> // for SDL_PollEvent, SDL_Event, SDL_KEYDOWN
#include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3 #include <SDL2/SDL_keycode.h> // for SDLK_1, SDLK_2, SDLK_3
#include <SDL2/SDL_rect.h> // for SDL_Rect #include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer #include <SDL2/SDL_render.h> // for SDL_Renderer
#include <SDL2/SDL_timer.h> // for SDL_GetTicks #include <SDL2/SDL_timer.h> // for SDL_GetTicks
#include <string> // for char_traits, operator+, to_string, bas... #include <string> // for char_traits, operator+, to_string, bas...
#include <utility> // for move #include <utility> // for move
#include <vector> // for vector #include <vector> // for vector
#include "asset.h" // for Asset #include "asset.h" // for Asset
#include "global_inputs.h" // for check #include "global_inputs.h" // for check
#include "input.h" // for Input, InputType, INPUT_DO_NOT_ALLOW_R... #include "input.h" // for Input, InputType, INPUT_DO_NOT_ALLOW_R...
#include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P... #include "jail_audio.h" // for JA_GetMusicState, JA_Music_state, JA_P...
#include "lang.h" // for getText #include "lang.h" // for getText
#include "options.h" // for options #include "notifier.h" // for Notifier
#include "param.h" // for param #include "options.h" // for options
#include "screen.h" // for Screen #include "param.h" // for param
#include "section.h" // for Options, options, Name, name #include "screen.h" // for Screen
#include "texture.h" // for Texture #include "section.h" // for Options, options, Name, name
#include "utils.h" // for Param, OptionsController, Color, Param... #include "texture.h" // for Texture
struct JA_Music_t; // lines 17-17 #include "utils.h" // for Param, OptionsController, Color, Param...
struct JA_Music_t; // lines 17-17
// Constructor // Constructor
Title::Title(JA_Music_t *music) Title::Title(JA_Music_t *music)
@@ -38,7 +39,7 @@ Title::Title(JA_Music_t *music)
text2_ = std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer); text2_ = std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer);
mini_logo_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_jailgames_mini.png")); mini_logo_texture_ = std::make_shared<Texture>(renderer, Asset::get()->get("logo_jailgames_mini.png"));
mini_logo_sprite_ = std::make_unique<Sprite>(param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight(), mini_logo_texture_); mini_logo_sprite_ = std::make_unique<Sprite>(mini_logo_texture_, param.game.game_area.center_x - mini_logo_texture_->getWidth() / 2, 0, mini_logo_texture_->getWidth(), mini_logo_texture_->getHeight());
tiled_bg_ = std::make_unique<Tiledbg>(Asset::get()->get("title_bg_tile.png"), (SDL_Rect){0, 0, param.game.width, param.game.height}, TILED_MODE_RANDOM); tiled_bg_ = std::make_unique<Tiledbg>(Asset::get()->get("title_bg_tile.png"), (SDL_Rect){0, 0, param.game.width, param.game.height}, TILED_MODE_RANDOM);
@@ -161,7 +162,7 @@ void Title::render()
// Mini logo // Mini logo
const int pos1 = (param.game.height / 5 * 4) + BLOCK; const int pos1 = (param.game.height / 5 * 4) + BLOCK;
const int pos2 = pos1 + mini_logo_sprite_->getHeight() + 3; const int pos2 = pos1 + mini_logo_sprite_->getHeight() + 3;
mini_logo_sprite_->setPosY(pos1); mini_logo_sprite_->setY(pos1);
mini_logo_sprite_->render(); mini_logo_sprite_->render();
// Texto con el copyright // Texto con el copyright
@@ -354,7 +355,7 @@ void Title::swapControllers()
} }
} }
screen_->showNotification(text[0], text[1]); Notifier::get()->showText(text[0], text[1]);
resetCounter(); resetCounter();
} }

View File

@@ -214,3 +214,9 @@ double easeInOutSine(double t)
{ {
return -0.5 * (std::cos(M_PI * t) - 1); return -0.5 * (std::cos(M_PI * t) - 1);
} }
// Comprueba si una vector contiene una cadena
bool stringInVector(const std::vector<std::string> &vec, const std::string &str)
{
return std::find(vec.begin(), vec.end(), str) != vec.end();
}

View File

@@ -152,11 +152,12 @@ struct Zone
// param.game // param.game
struct ParamGame 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 item_size; // Tamaño de los items del juego int item_size; // Tamaño de los items del juego
Zone play_area; // Rectangulo con la posición de la zona de juego Zone play_area; // Rectangulo con la posición de la zona de juego
Zone game_area; // Rectangulo con las dimensiones del juego Zone game_area; // Rectangulo con las dimensiones del juego
int enter_name_seconds; // Duración en segundos para introducir el nombre al finalizar la partida
}; };
// param.fade // param.fade
@@ -282,6 +283,9 @@ double easeOutQuint(double t);
// Función de suavizado // Función de suavizado
double easeInOutSine(double t); double easeInOutSine(double t);
// Comprueba si una vector contiene una cadena
bool stringInVector(const std::vector<std::string> &vec, const std::string &str);
// Colores // Colores
extern const Color bg_color; extern const Color bg_color;
extern const Color no_color; extern const Color no_color;