Compare commits
10 Commits
2024-10-20
...
8f33308f8d
| Author | SHA1 | Date | |
|---|---|---|---|
| 8f33308f8d | |||
| 8c98430b68 | |||
| 6e2f80d8ce | |||
| 95478134dd | |||
| 528533fd9b | |||
| 5df85e1b1a | |||
| 1d0c2e01a5 | |||
| 236d6f58b6 | |||
| 898b551e06 | |||
| 84238032e0 |
@@ -7,6 +7,7 @@ game.play_area.rect.y 0 # Rectangulo con la posición de la zona de juego
|
|||||||
game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
|
game.play_area.rect.w 320 # Rectangulo con la posición de la zona de juego
|
||||||
game.play_area.rect.h 216 # Rectangulo con la posición de la zona de juego
|
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
|
game.enter_name_seconds 30 # Duración en segundos para introducir el nombre al finalizar la partida
|
||||||
|
game.game_text.dest_y
|
||||||
|
|
||||||
## FADE
|
## FADE
|
||||||
fade.num_squares_width 160
|
fade.num_squares_width 160
|
||||||
|
|||||||
|
Before Width: | Height: | Size: 337 B After Width: | Height: | Size: 295 B |
|
Before Width: | Height: | Size: 376 B After Width: | Height: | Size: 371 B |
|
Before Width: | Height: | Size: 364 B After Width: | Height: | Size: 332 B |
|
Before Width: | Height: | Size: 487 B After Width: | Height: | Size: 399 B |
|
Before Width: | Height: | Size: 580 B After Width: | Height: | Size: 453 B |
|
Before Width: | Height: | Size: 173 B After Width: | Height: | Size: 176 B |
|
Before Width: | Height: | Size: 172 B After Width: | Height: | Size: 172 B |
@@ -56,12 +56,6 @@ AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture)
|
|||||||
: MovingSprite(texture),
|
: MovingSprite(texture),
|
||||||
current_animation_(0) {}
|
current_animation_(0) {}
|
||||||
|
|
||||||
// Destructor
|
|
||||||
AnimatedSprite::~AnimatedSprite()
|
|
||||||
{
|
|
||||||
animations_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Obtiene el indice de la animación a partir del nombre
|
// Obtiene el indice de la animación a partir del nombre
|
||||||
int AnimatedSprite::getIndex(const std::string &name)
|
int AnimatedSprite::getIndex(const std::string &name)
|
||||||
{
|
{
|
||||||
@@ -260,12 +254,9 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
{
|
{
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
std::vector<Animation> animations;
|
std::vector<Animation> animations;
|
||||||
auto frames_per_row = 0;
|
auto frame_width = 1;
|
||||||
auto frame_width = 0;
|
auto frame_height = 1;
|
||||||
auto frame_height = 0;
|
|
||||||
auto max_tiles = 0;
|
|
||||||
|
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
std::string line;
|
std::string line;
|
||||||
|
|
||||||
@@ -273,9 +264,11 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
if (file.good())
|
if (file.good())
|
||||||
{
|
{
|
||||||
// Procesa el fichero linea a linea
|
// Procesa el fichero linea a linea
|
||||||
std::cout << "Animation loaded: " << file_name << std::endl;
|
std::cout << "Animation loaded: " << getFileName(file_path) << std::endl;
|
||||||
while (std::getline(file, line))
|
while (std::getline(file, line))
|
||||||
{
|
{
|
||||||
|
auto max_tiles = 1;
|
||||||
|
auto frames_per_row = 1;
|
||||||
// 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]")
|
||||||
{
|
{
|
||||||
@@ -324,7 +317,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
|
std::cout << "Warning: file " << getFileName(file_path).c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} while (line != "[/animation]");
|
} while (line != "[/animation]");
|
||||||
@@ -334,20 +327,15 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
else
|
if (line != "[animation]")
|
||||||
{
|
{
|
||||||
// Encuentra la posición del caracter '='
|
// Encuentra la posición del caracter '='
|
||||||
int pos = line.find("=");
|
size_t pos = line.find("=");
|
||||||
|
|
||||||
// Procesa las dos subcadenas
|
// Procesa las dos subcadenas
|
||||||
if (pos != (int)line.npos)
|
if (pos != line.npos)
|
||||||
{
|
{
|
||||||
if (line.substr(0, pos) == "frames_per_row")
|
if (line.substr(0, pos) == "frame_width")
|
||||||
{
|
|
||||||
frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
|
|
||||||
}
|
|
||||||
|
|
||||||
else if (line.substr(0, pos) == "frame_width")
|
|
||||||
{
|
{
|
||||||
frame_width = std::stoi(line.substr(pos + 1, line.length()));
|
frame_width = std::stoi(line.substr(pos + 1, line.length()));
|
||||||
}
|
}
|
||||||
@@ -359,21 +347,14 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Warning: file " << file_name.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
|
std::cout << "Warning: file " << getFileName(file_path) << "\n, unknown parameter \"" << line.substr(0, pos) << "\"" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Normaliza valores
|
frames_per_row = texture_->getWidth() / frame_width;
|
||||||
if (frames_per_row == 0 && frame_width > 0)
|
|
||||||
{
|
|
||||||
frames_per_row = texture_->getWidth() / frame_width;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (max_tiles == 0 && frame_width > 0 && frame_height > 0)
|
const auto w = texture_->getWidth() / frame_width;
|
||||||
{
|
const auto h = texture_->getHeight() / frame_height;
|
||||||
const auto w = texture_->getWidth() / frame_width;
|
max_tiles = w * h;
|
||||||
const auto h = texture_->getHeight() / frame_height;
|
|
||||||
max_tiles = w * h;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -384,7 +365,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
|||||||
// El fichero no se puede abrir
|
// El fichero no se puede abrir
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Warning: Unable to open " << file_name.c_str() << " file" << std::endl;
|
std::cout << "Warning: Unable to open " << getFileName(file_path).c_str() << " file" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pone un valor por defecto
|
// Pone un valor por defecto
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ public:
|
|||||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture);
|
explicit AnimatedSprite(std::shared_ptr<Texture> texture);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
virtual ~AnimatedSprite();
|
virtual ~AnimatedSprite() = default;
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void update() override;
|
void update() override;
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
#include <SDL2/SDL_stdinc.h> // for SDL_max
|
#include <SDL2/SDL_stdinc.h> // for SDL_max
|
||||||
#include <stddef.h> // for size_t
|
#include <stddef.h> // for size_t
|
||||||
#include <iostream> // for basic_ostream, operator<<, cout, endl
|
#include <iostream> // for basic_ostream, operator<<, cout, endl
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
// [SINGLETON] Hay que definir las variables estáticas, desde el .h sólo la hemos declarado
|
||||||
Asset *Asset::asset_ = nullptr;
|
Asset *Asset::asset_ = nullptr;
|
||||||
@@ -26,35 +28,19 @@ Asset *Asset::get()
|
|||||||
return Asset::asset_;
|
return Asset::asset_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Asset::Asset(const std::string &executable_path)
|
|
||||||
: executable_path_(executable_path.substr(0, executable_path.find_last_of("\\/")))
|
|
||||||
{
|
|
||||||
longest_name_ = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Añade un elemento a la lista
|
// Añade un elemento a la lista
|
||||||
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute)
|
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute)
|
||||||
{
|
{
|
||||||
AssetItem ai;
|
file_list_.emplace_back(absolute ? file : executable_path_ + file, type, required);
|
||||||
ai.file = absolute ? file : executable_path_ + file;
|
longest_name_ = std::max(longest_name_, static_cast<int>(file_list_.back().file.size()));
|
||||||
ai.type = type;
|
|
||||||
ai.required = required;
|
|
||||||
file_list_.push_back(ai);
|
|
||||||
|
|
||||||
const std::string file_name = file.substr(file.find_last_of("\\/") + 1);
|
|
||||||
longest_name_ = SDL_max(longest_name_, file_name.size());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Devuelve el fichero de un elemento de la lista a partir de una cadena
|
// Devuelve la ruta completa a un fichero a partir de una cadena
|
||||||
std::string Asset::get(const std::string &text) const
|
std::string Asset::get(const std::string &text) const
|
||||||
{
|
{
|
||||||
for (const auto &f : file_list_)
|
for (const auto &f : file_list_)
|
||||||
{
|
{
|
||||||
const size_t last_index = f.file.find_last_of("/") + 1;
|
if (getFileName(f.file) == text)
|
||||||
const std::string file = f.file.substr(last_index, std::string::npos);
|
|
||||||
|
|
||||||
if (file == text)
|
|
||||||
{
|
{
|
||||||
return f.file;
|
return f.file;
|
||||||
}
|
}
|
||||||
@@ -114,20 +100,12 @@ bool Asset::check() const
|
|||||||
// Comprueba que existe un fichero
|
// Comprueba que existe un fichero
|
||||||
bool Asset::checkFile(const std::string &path) const
|
bool Asset::checkFile(const std::string &path) const
|
||||||
{
|
{
|
||||||
auto success = false;
|
std::ifstream file(path);
|
||||||
|
bool success = file.good();
|
||||||
|
file.close();
|
||||||
|
|
||||||
// Comprueba si existe el fichero
|
|
||||||
auto file = SDL_RWFromFile(path.c_str(), "rb");
|
|
||||||
|
|
||||||
if (file)
|
|
||||||
{
|
|
||||||
success = true;
|
|
||||||
SDL_RWclose(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
const std::string file_name = path.substr(path.find_last_of("\\/") + 1);
|
|
||||||
if (!success)
|
if (!success)
|
||||||
printWithDots("Checking file : ", file_name, (success ? " [ OK ]" : " [ ERROR ]"));
|
printWithDots("Checking file : ", getFileName(path), "[ ERROR ]");
|
||||||
|
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <string> // for string, basic_string
|
#include <string> // for string, basic_string
|
||||||
#include <vector> // for vector
|
#include <vector> // for vector
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
enum class AssetType : int
|
enum class AssetType : int
|
||||||
{
|
{
|
||||||
@@ -27,14 +28,17 @@ private:
|
|||||||
// Estructura para definir un item
|
// Estructura para definir un item
|
||||||
struct AssetItem
|
struct AssetItem
|
||||||
{
|
{
|
||||||
std::string file; // Ruta del fichero desde la raiz del directorio
|
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||||
enum AssetType type; // Indica el tipo de recurso
|
AssetType type; // Indica el tipo de recurso
|
||||||
bool required; // Indica si es un fichero que debe de existir
|
bool required; // Indica si es un fichero que debe de existir
|
||||||
// bool absolute; // Indica si la ruta que se ha proporcionado es una ruta absoluta
|
|
||||||
|
// Constructor
|
||||||
|
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
|
||||||
|
: file(filePath), type(assetType), required(isRequired) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int longest_name_; // Contiene la longitud del nombre de fichero mas largo
|
int longest_name_ = 0; // Contiene la longitud del nombre de fichero mas largo
|
||||||
std::vector<AssetItem> file_list_; // Listado con todas las rutas a los ficheros
|
std::vector<AssetItem> file_list_; // Listado con todas las rutas a los ficheros
|
||||||
std::string executable_path_; // Ruta al ejecutable
|
std::string executable_path_; // Ruta al ejecutable
|
||||||
|
|
||||||
@@ -45,7 +49,8 @@ private:
|
|||||||
std::string getTypeName(AssetType type) const;
|
std::string getTypeName(AssetType type) const;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Asset(const std::string &executable_path);
|
explicit Asset(const std::string &executable_path)
|
||||||
|
: executable_path_(getPath(executable_path)) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Asset() = default;
|
~Asset() = default;
|
||||||
@@ -63,7 +68,7 @@ public:
|
|||||||
// Añade un elemento a la lista
|
// Añade un elemento a la lista
|
||||||
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false);
|
void add(const std::string &file, AssetType type, bool required = true, bool absolute = false);
|
||||||
|
|
||||||
// Devuelve un elemento de la lista a partir de una cadena
|
// Devuelve la ruta completa a un fichero a partir de una cadena
|
||||||
std::string get(const std::string &text) const;
|
std::string get(const std::string &text) const;
|
||||||
|
|
||||||
// Comprueba que existen todos los elementos
|
// Comprueba que existen todos los elementos
|
||||||
|
|||||||
@@ -20,16 +20,11 @@ Background::Background()
|
|||||||
grass_texture_(Resource::get()->getTexture("game_grass.png")),
|
grass_texture_(Resource::get()->getTexture("game_grass.png")),
|
||||||
gradients_texture_(Resource::get()->getTexture("game_sky_colors.png")),
|
gradients_texture_(Resource::get()->getTexture("game_sky_colors.png")),
|
||||||
|
|
||||||
gradient_number_(0),
|
|
||||||
alpha_(0),
|
|
||||||
clouds_speed_(0),
|
|
||||||
transition_(0),
|
|
||||||
counter_(0),
|
|
||||||
rect_({0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2}),
|
rect_({0, 0, gradients_texture_->getWidth() / 2, gradients_texture_->getHeight() / 2}),
|
||||||
src_rect_({0, 0, 320, 240}),
|
src_rect_({0, 0, 320, 240}),
|
||||||
dst_rect_({0, 0, 320, 240}),
|
dst_rect_({0, 0, 320, 240}),
|
||||||
base_(rect_.h),
|
base_(rect_.h),
|
||||||
color_({param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b}),
|
color_(Color(param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b)),
|
||||||
alpha_color_text_(param.background.attenuate_alpha),
|
alpha_color_text_(param.background.attenuate_alpha),
|
||||||
alpha_color_text_temp_(param.background.attenuate_alpha)
|
alpha_color_text_temp_(param.background.attenuate_alpha)
|
||||||
|
|
||||||
|
|||||||
@@ -74,11 +74,11 @@ private:
|
|||||||
SDL_Rect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo
|
SDL_Rect gradient_rect_[4]; // Vector con las coordenadas de los 4 degradados para el cielo
|
||||||
SDL_Rect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba
|
SDL_Rect top_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de arriba
|
||||||
SDL_Rect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo
|
SDL_Rect bottom_clouds_rect_[4]; // Vector con las coordenadas de los 4 nubes de abajo
|
||||||
int gradient_number_; // Indica el número de degradado de fondo que se va a dibujar
|
int gradient_number_ = 0; // Indica el número de degradado de fondo que se va a dibujar
|
||||||
int alpha_; // Transparencia entre los dos degradados
|
int alpha_ = 0; // Transparencia entre los dos degradados
|
||||||
float clouds_speed_; // Velocidad a la que se desplazan las nubes
|
float clouds_speed_ = 0; // Velocidad a la que se desplazan las nubes
|
||||||
float transition_; // Nivel de transición del fondo 0..1
|
float transition_ = 0; // Nivel de transición del fondo 0..1
|
||||||
int counter_; // Contador interno
|
int counter_ = 0; // Contador interno
|
||||||
SDL_Rect rect_; // Tamaño del objeto fondo
|
SDL_Rect rect_; // Tamaño del objeto fondo
|
||||||
SDL_Rect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla
|
SDL_Rect src_rect_; // Parte del objeto fondo que se va a dibujará en pantalla
|
||||||
SDL_Rect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla
|
SDL_Rect dst_rect_; // Posición donde dibujar la parte del objeto fondo que se dibujará en pantalla
|
||||||
|
|||||||
@@ -13,17 +13,10 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16
|
|||||||
pos_y_(y),
|
pos_y_(y),
|
||||||
vel_x_(vel_x),
|
vel_x_(vel_x),
|
||||||
being_created_(creation_timer > 0),
|
being_created_(creation_timer > 0),
|
||||||
blinking_(false),
|
|
||||||
enabled_(true),
|
|
||||||
invulnerable_(creation_timer > 0),
|
invulnerable_(creation_timer > 0),
|
||||||
stopped_(true),
|
|
||||||
visible_(true),
|
|
||||||
creation_counter_(creation_timer),
|
creation_counter_(creation_timer),
|
||||||
creation_counter_ini_(creation_timer),
|
creation_counter_ini_(creation_timer),
|
||||||
stopped_counter_(0),
|
|
||||||
kind_(kind),
|
kind_(kind),
|
||||||
counter_(0),
|
|
||||||
travel_y_(1.0f),
|
|
||||||
speed_(speed)
|
speed_(speed)
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -227,23 +220,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Valores para el efecto de rebote
|
|
||||||
bouncing_.enabled = false;
|
|
||||||
bouncing_.counter = 0;
|
|
||||||
bouncing_.speed = 2;
|
|
||||||
bouncing_.zoomW = 1.0f;
|
|
||||||
bouncing_.zoomH = 1.0f;
|
|
||||||
bouncing_.despX = 0.0f;
|
|
||||||
bouncing_.despY = 0.0f;
|
|
||||||
bouncing_.w = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f};
|
|
||||||
bouncing_.h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f};
|
|
||||||
|
|
||||||
// Configura el sprite
|
// Configura el sprite
|
||||||
sprite_->setPos({static_cast<int>(pos_x_), static_cast<int>(pos_y_), width_, height_});
|
sprite_->setPos({static_cast<int>(pos_x_), static_cast<int>(pos_y_), width_, height_});
|
||||||
|
|
||||||
// Tamaño del circulo de colisión
|
|
||||||
collider_.r = width_ / 2;
|
|
||||||
|
|
||||||
// Alinea el circulo de colisión con el objeto
|
// Alinea el circulo de colisión con el objeto
|
||||||
updateColliders();
|
updateColliders();
|
||||||
}
|
}
|
||||||
@@ -726,8 +705,8 @@ Circle &Balloon::getCollider()
|
|||||||
// Alinea el circulo de colisión con la posición del objeto globo
|
// Alinea el circulo de colisión con la posición del objeto globo
|
||||||
void Balloon::updateColliders()
|
void Balloon::updateColliders()
|
||||||
{
|
{
|
||||||
collider_.x = Uint16(pos_x_ + collider_.r);
|
collider_.x = static_cast<int>(pos_x_ + collider_.r);
|
||||||
collider_.y = pos_y_ + collider_.r;
|
collider_.y = static_cast<int>(pos_y_ + collider_.r);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene le valor de la variable
|
// Obtiene le valor de la variable
|
||||||
|
|||||||
@@ -74,49 +74,53 @@ private:
|
|||||||
// Estructura para las variables para el efecto de los rebotes
|
// Estructura para las variables para el efecto de los rebotes
|
||||||
struct Bouncing
|
struct Bouncing
|
||||||
{
|
{
|
||||||
bool enabled; // Si el efecto está activo
|
bool enabled = false; // Si el efecto está activo
|
||||||
Uint8 counter; // Countador para el efecto
|
Uint8 counter = 0; // Countador para el efecto
|
||||||
Uint8 speed; // Velocidad a la que transcurre el efecto
|
Uint8 speed = 2; // Velocidad a la que transcurre el efecto
|
||||||
float zoomW; // Zoom aplicado a la anchura
|
float zoomW = 1.0f; // Zoom aplicado a la anchura
|
||||||
float zoomH; // Zoom aplicado a la altura
|
float zoomH = 1.0f; // Zoom aplicado a la altura
|
||||||
float despX; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom
|
float despX = 0.0f; // Desplazamiento de pixeles en el eje X antes de pintar el objeto con zoom
|
||||||
float despY; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom
|
float despY = 0.0f; // Desplazamiento de pixeles en el eje Y antes de pintar el objeto con zoom
|
||||||
std::vector<float> w; // Vector con los valores de zoom para el ancho del globo
|
|
||||||
std::vector<float> h; // Vector con los valores de zoom para el alto del globo
|
std::vector<float> w = {1.10f, 1.05f, 1.00f, 0.95f, 0.90f, 0.95f, 1.00f, 1.02f, 1.05f, 1.02f}; // Vector con los valores de zoom para el ancho del globo
|
||||||
|
std::vector<float> h = {0.90f, 0.95f, 1.00f, 1.05f, 1.10f, 1.05f, 1.00f, 0.98f, 0.95f, 0.98f}; // Vector con los valores de zoom para el alto del globo
|
||||||
|
|
||||||
|
// Constructor por defecto
|
||||||
|
Bouncing() {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
float pos_x_; // Posición en el eje X
|
float pos_x_; // Posición en el eje X
|
||||||
float pos_y_; // Posición en el eje Y
|
float pos_y_; // Posición en el eje Y
|
||||||
Uint8 width_; // Ancho
|
Uint8 width_; // Ancho
|
||||||
Uint8 height_; // Alto
|
Uint8 height_; // Alto
|
||||||
float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
|
float vel_x_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
|
||||||
float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
|
float vel_y_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
|
||||||
float gravity_; // Aceleración en el eje Y. Modifica la velocidad
|
float gravity_; // Aceleración en el eje Y. Modifica la velocidad
|
||||||
float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo
|
float default_vel_y_; // Velocidad inicial que tienen al rebotar contra el suelo
|
||||||
float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y
|
float max_vel_y_; // Máxima velocidad que puede alcanzar el objeto en el eje Y
|
||||||
bool being_created_; // Indica si el globo se está creando
|
bool being_created_; // Indica si el globo se está creando
|
||||||
bool blinking_; // Indica si el globo está intermitente
|
bool blinking_ = false; // Indica si el globo está intermitente
|
||||||
bool enabled_; // Indica si el globo esta activo
|
bool enabled_ = true; // Indica si el globo esta activo
|
||||||
bool invulnerable_; // Indica si el globo es invulnerable
|
bool invulnerable_; // Indica si el globo es invulnerable
|
||||||
bool stopped_; // Indica si el globo está parado
|
bool stopped_ = true; // Indica si el globo está parado
|
||||||
bool visible_; // Indica si el globo es visible
|
bool visible_ = true; // Indica si el globo es visible
|
||||||
Circle collider_; // Circulo de colisión del objeto
|
Circle collider_ = Circle(0, 0, width_ / 2); // Circulo de colisión del objeto
|
||||||
Uint16 creation_counter_; // Temporizador para controlar el estado "creandose"
|
Uint16 creation_counter_; // Temporizador para controlar el estado "creandose"
|
||||||
Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
|
Uint16 creation_counter_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
|
||||||
Uint16 score_; // Puntos que da el globo al ser destruido
|
Uint16 score_; // Puntos que da el globo al ser destruido
|
||||||
Uint16 stopped_counter_; // Contador para controlar el estado "parado"
|
Uint16 stopped_counter_ = 0; // Contador para controlar el estado "parado"
|
||||||
Uint8 kind_; // Tipo de globo
|
Uint8 kind_; // Tipo de globo
|
||||||
Uint8 menace_; // Cantidad de amenaza que genera el globo
|
Uint8 menace_; // Cantidad de amenaza que genera el globo
|
||||||
Uint32 counter_; // Contador interno
|
Uint32 counter_ = 0; // Contador interno
|
||||||
float travel_y_; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
|
float travel_y_ = 1.0f; // Distancia que ha de recorrer el globo en el eje Y antes de que se le aplique la gravedad
|
||||||
float speed_; // Velocidad a la que se mueven los globos
|
float speed_; // Velocidad a la que se mueven los globos
|
||||||
Uint8 size_; // Tamaño del globo
|
Uint8 size_; // Tamaño del globo
|
||||||
Uint8 power_; // Cantidad de poder que alberga el globo
|
Uint8 power_; // Cantidad de poder que alberga el globo
|
||||||
Bouncing bouncing_; // Contiene las variables para el efecto de rebote
|
Bouncing bouncing_ = Bouncing(); // Contiene las variables para el efecto de rebote
|
||||||
|
|
||||||
// Alinea el circulo de colisión con la posición del objeto globo
|
// Alinea el circulo de colisión con la posición del objeto globo
|
||||||
void updateColliders();
|
void updateColliders();
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ struct BalloonFormationParams
|
|||||||
int creation_counter = 0; // Temporizador para la creación del enemigo
|
int creation_counter = 0; // Temporizador para la creación del enemigo
|
||||||
|
|
||||||
// Constructor que inicializa todos los campos con valores proporcionados o predeterminados
|
// Constructor que inicializa todos los campos con valores proporcionados o predeterminados
|
||||||
BalloonFormationParams(int x_val = 0, int y_val = 0, float vel_x_val = 0.0f, int kind_val = 0, int creation_counter_val = 0)
|
explicit BalloonFormationParams(int x_val = 0, int y_val = 0, float vel_x_val = 0.0f, int kind_val = 0, int creation_counter_val = 0)
|
||||||
: x(x_val), y(y_val), vel_x(vel_x_val), kind(kind_val), creation_counter(creation_counter_val) {}
|
: x(x_val), y(y_val), vel_x(vel_x_val), kind(kind_val), creation_counter(creation_counter_val) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -10,49 +10,22 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
DefineButtons::DefineButtons(std::unique_ptr<Text> text_)
|
DefineButtons::DefineButtons(std::unique_ptr<Text> text_)
|
||||||
: text_(std::move(text_))
|
: input_(Input::get()),
|
||||||
|
text_(std::move(text_))
|
||||||
{
|
{
|
||||||
// Copia punteros a los objetos
|
|
||||||
input_ = Input::get();
|
|
||||||
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
enabled_ = false;
|
|
||||||
x_ = param.game.width / 2;
|
x_ = param.game.width / 2;
|
||||||
y_ = param.title.press_start_position;
|
y_ = param.title.press_start_position;
|
||||||
index_controller_ = 0;
|
|
||||||
index_button_ = 0;
|
|
||||||
|
|
||||||
buttons_.clear();
|
buttons_.emplace_back(lang::getText(95), InputType::FIRE_LEFT, SDL_CONTROLLER_BUTTON_X);
|
||||||
DefineButtonsButton button;
|
buttons_.emplace_back(lang::getText(96), InputType::FIRE_CENTER, SDL_CONTROLLER_BUTTON_Y);
|
||||||
|
buttons_.emplace_back(lang::getText(97), InputType::FIRE_RIGHT, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
|
||||||
button.label = lang::getText(95);
|
buttons_.emplace_back(lang::getText(98), InputType::START, SDL_CONTROLLER_BUTTON_START);
|
||||||
button.input = InputType::FIRE_LEFT;
|
buttons_.emplace_back(lang::getText(99), InputType::EXIT, SDL_CONTROLLER_BUTTON_BACK);
|
||||||
button.button = SDL_CONTROLLER_BUTTON_X;
|
|
||||||
buttons_.push_back(button);
|
|
||||||
|
|
||||||
button.label = lang::getText(96);
|
|
||||||
button.input = InputType::FIRE_CENTER;
|
|
||||||
button.button = SDL_CONTROLLER_BUTTON_Y;
|
|
||||||
buttons_.push_back(button);
|
|
||||||
|
|
||||||
button.label = lang::getText(97);
|
|
||||||
button.input = InputType::FIRE_RIGHT;
|
|
||||||
button.button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
|
|
||||||
buttons_.push_back(button);
|
|
||||||
|
|
||||||
button.label = lang::getText(98);
|
|
||||||
button.input = InputType::START;
|
|
||||||
button.button = SDL_CONTROLLER_BUTTON_START;
|
|
||||||
buttons_.push_back(button);
|
|
||||||
|
|
||||||
button.label = lang::getText(99);
|
|
||||||
button.input = InputType::EXIT;
|
|
||||||
button.button = SDL_CONTROLLER_BUTTON_BACK;
|
|
||||||
buttons_.push_back(button);
|
|
||||||
|
|
||||||
for (int i = 0; i < input_->getNumControllers(); ++i)
|
for (int i = 0; i < input_->getNumControllers(); ++i)
|
||||||
{
|
{
|
||||||
controller_names_.push_back(input_->getControllerName(i));
|
controller_names_.emplace_back(input_->getControllerName(i));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent
|
#include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent
|
||||||
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
|
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
|
||||||
#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 Input;
|
class Input;
|
||||||
class Text;
|
class Text;
|
||||||
enum class InputType : int;
|
enum class InputType : int;
|
||||||
@@ -14,6 +14,10 @@ struct DefineButtonsButton
|
|||||||
std::string label; // Texto en pantalla para el botón
|
std::string label; // Texto en pantalla para el botón
|
||||||
InputType input; // Input asociado
|
InputType input; // Input asociado
|
||||||
SDL_GameControllerButton button; // Botón del mando correspondiente
|
SDL_GameControllerButton button; // Botón del mando correspondiente
|
||||||
|
|
||||||
|
// Constructor
|
||||||
|
DefineButtonsButton(const std::string &lbl, InputType inp, SDL_GameControllerButton btn)
|
||||||
|
: label(lbl), input(inp), button(btn) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Clase Bullet
|
// Clase Bullet
|
||||||
@@ -25,12 +29,12 @@ private:
|
|||||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
bool enabled_; // Indica si el objeto está habilitado
|
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||||
int x_; // Posición donde dibujar el texto
|
int x_; // Posición donde dibujar el texto
|
||||||
int y_; // Posición donde dibujar el texto
|
int y_; // Posición donde dibujar el texto
|
||||||
std::vector<DefineButtonsButton> buttons_; // Vector con las nuevas definiciones de botones/acciones
|
std::vector<DefineButtonsButton> buttons_; // Vector con las nuevas definiciones de botones/acciones
|
||||||
int index_controller_; // Indice del controlador a reasignar
|
int index_controller_ = 0; // Indice del controlador a reasignar
|
||||||
int index_button_; // Indice para saber qué bot´çon se está definiendo
|
int index_button_ = 0; // Indice para saber qué bot´çon se está definiendo
|
||||||
std::vector<std::string> controller_names_; // Nombres de los mandos
|
std::vector<std::string> controller_names_; // Nombres de los mandos
|
||||||
|
|
||||||
// Incrementa el indice de los botones
|
// Incrementa el indice de los botones
|
||||||
|
|||||||
@@ -84,13 +84,22 @@ Director::Director(int argc, const char *argv[])
|
|||||||
#ifdef ANBERNIC
|
#ifdef ANBERNIC
|
||||||
const std::string paramFilePath = asset->get("param_320x240.txt");
|
const std::string paramFilePath = asset->get("param_320x240.txt");
|
||||||
#else
|
#else
|
||||||
const std::string paramFilePath = param_file_argument_ == "--320x240" ? Asset::get()->get("param_320x240.txt") : Asset::get()->get("param_320x256.txt");
|
const std::string paramFilePath = overrides.param_file == "--320x240" ? Asset::get()->get("param_320x240.txt") : Asset::get()->get("param_320x256.txt");
|
||||||
#endif
|
#endif
|
||||||
loadParams(paramFilePath);
|
loadParams(paramFilePath);
|
||||||
|
|
||||||
// Carga el fichero de puntuaciones
|
// Carga el fichero de puntuaciones
|
||||||
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
|
{
|
||||||
manager->loadFromFile(Asset::get()->get("score.bin"));
|
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
|
||||||
|
if (overrides.clear_hi_score_table)
|
||||||
|
{
|
||||||
|
manager->clear();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
manager->loadFromFile(Asset::get()->get("score.bin"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Inicializa SDL
|
// Inicializa SDL
|
||||||
initSDL();
|
initSDL();
|
||||||
@@ -513,18 +522,33 @@ void Director::loadParams(const std::string &file_path)
|
|||||||
// Comprueba los parametros del programa
|
// Comprueba los parametros del programa
|
||||||
void Director::checkProgramArguments(int argc, const char *argv[])
|
void Director::checkProgramArguments(int argc, const char *argv[])
|
||||||
{
|
{
|
||||||
|
const std::vector<std::string> argument_list = {"--h", "--320x240", "--clear_score"};
|
||||||
|
|
||||||
// Establece la ruta del programa
|
// Establece la ruta del programa
|
||||||
executable_path_ = argv[0];
|
executable_path_ = argv[0];
|
||||||
|
|
||||||
// Valores por defecto
|
|
||||||
param_file_argument_.clear();
|
|
||||||
|
|
||||||
// Comprueba el resto de parámetros
|
// Comprueba el resto de parámetros
|
||||||
for (int i = 1; i < argc; ++i)
|
for (int i = 1; i < argc; ++i)
|
||||||
{
|
{
|
||||||
|
if (strcmp(argv[i], "--h") == 0)
|
||||||
|
{
|
||||||
|
for (const auto &argument : argument_list)
|
||||||
|
{
|
||||||
|
std::cout << argument << std::endl;
|
||||||
|
}
|
||||||
|
// std::exit(EXIT_SUCCESS);
|
||||||
|
section::name = section::Name::QUIT;
|
||||||
|
section::options = section::Options::QUIT_FROM_EVENT;
|
||||||
|
}
|
||||||
|
|
||||||
if (strcmp(argv[i], "--320x240") == 0)
|
if (strcmp(argv[i], "--320x240") == 0)
|
||||||
{
|
{
|
||||||
param_file_argument_ = argv[i];
|
overrides.param_file = argv[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (strcmp(argv[i], "--clear_score") == 0)
|
||||||
|
{
|
||||||
|
overrides.clear_hi_score_table = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -728,6 +752,7 @@ std::string Director::getLangFile(lang::Code code)
|
|||||||
return Asset::get()->get("en_UK.txt");
|
return Asset::get()->get("en_UK.txt");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#ifdef ARCADE
|
||||||
// Apaga el sistema
|
// Apaga el sistema
|
||||||
void Director::shutdownSystem()
|
void Director::shutdownSystem()
|
||||||
{
|
{
|
||||||
@@ -744,4 +769,5 @@ void Director::shutdownSystem()
|
|||||||
// Sistema operativo no compatible
|
// Sistema operativo no compatible
|
||||||
#error "Sistema operativo no soportado"
|
#error "Sistema operativo no soportado"
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
#endif //ARCADE
|
||||||
@@ -25,7 +25,6 @@ private:
|
|||||||
// Variables
|
// Variables
|
||||||
std::string executable_path_; // Path del ejecutable
|
std::string executable_path_; // Path del ejecutable
|
||||||
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
std::string system_folder_; // Carpeta del sistema donde guardar datos
|
||||||
std::string param_file_argument_; // Argumento para gestionar el fichero con los parametros del programa
|
|
||||||
|
|
||||||
// Inicializa jail_audio
|
// Inicializa jail_audio
|
||||||
void initJailAudio();
|
void initJailAudio();
|
||||||
@@ -71,9 +70,10 @@ 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);
|
||||||
|
#ifdef ARCADE
|
||||||
// Apaga el sistema
|
// Apaga el sistema
|
||||||
void shutdownSystem();
|
void shutdownSystem();
|
||||||
|
#endif
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ void Explosions::render()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Añade texturas al objeto
|
// Añade texturas al objeto
|
||||||
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> &animation)
|
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation)
|
||||||
{
|
{
|
||||||
textures_.emplace_back(ExplosionTexture(size, texture, animation));
|
textures_.emplace_back(ExplosionTexture(size, texture, animation));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ struct ExplosionTexture
|
|||||||
std::vector<std::string> animation; // Animación para la textura
|
std::vector<std::string> animation; // Animación para la textura
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, std::vector<std::string> anim)
|
ExplosionTexture(int sz, std::shared_ptr<Texture> tex, const std::vector<std::string> &anim)
|
||||||
: size(sz), texture(tex), animation(anim) {}
|
: size(sz), texture(tex), animation(anim) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ public:
|
|||||||
void render();
|
void render();
|
||||||
|
|
||||||
// Añade texturas al objeto
|
// Añade texturas al objeto
|
||||||
void addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> &animation);
|
void addTexture(int size, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||||
|
|
||||||
// Añade una explosión
|
// Añade una explosión
|
||||||
void add(int x, int y, int size);
|
void add(int x, int y, int size);
|
||||||
|
|||||||
186
source/game.cpp
@@ -64,8 +64,8 @@ Game::Game(int player_id, int current_stage, bool demo)
|
|||||||
explosions_ = std::make_unique<Explosions>();
|
explosions_ = std::make_unique<Explosions>();
|
||||||
balloon_formations_ = std::make_unique<BalloonFormations>();
|
balloon_formations_ = std::make_unique<BalloonFormations>();
|
||||||
|
|
||||||
// Carga los recursos
|
// Asigna los recursos a variables privadas del objeto
|
||||||
loadMedia();
|
setResources();
|
||||||
|
|
||||||
// Inicializa los vectores con los datos para la demo
|
// Inicializa los vectores con los datos para la demo
|
||||||
if (demo_.enabled)
|
if (demo_.enabled)
|
||||||
@@ -86,62 +86,26 @@ Game::Game(int player_id, int current_stage, bool demo)
|
|||||||
canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h);
|
canvas_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.play_area.rect.w, param.game.play_area.rect.h);
|
||||||
SDL_SetTextureBlendMode(canvas_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(canvas_, SDL_BLENDMODE_BLEND);
|
||||||
|
|
||||||
// Inicializa las variables necesarias para la sección 'Game'
|
|
||||||
init(player_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
Game::~Game()
|
|
||||||
{
|
|
||||||
// Guarda las puntuaciones en un fichero
|
|
||||||
if (!demo_.enabled)
|
|
||||||
{
|
|
||||||
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
|
|
||||||
manager->saveToFile(asset_->get("score.bin"));
|
|
||||||
}
|
|
||||||
#ifdef RECORDING
|
|
||||||
saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0));
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Elimina todos los objetos contenidos en vectores
|
|
||||||
deleteAllVectorObjects();
|
|
||||||
|
|
||||||
// Libera los recursos
|
|
||||||
unloadMedia();
|
|
||||||
|
|
||||||
Scoreboard::destroy();
|
|
||||||
|
|
||||||
SDL_DestroyTexture(canvas_);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inicializa las variables necesarias para la sección 'Game'
|
|
||||||
void Game::init(int player_id)
|
|
||||||
{
|
|
||||||
// Elimina qualquier jugador que hubiese antes de crear los nuevos
|
|
||||||
players_.clear();
|
|
||||||
|
|
||||||
// Crea los dos jugadores
|
// Crea los dos jugadores
|
||||||
auto player1 = std::make_unique<Player>(1, (param.game.play_area.first_quarter_x * ((0 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo_.enabled, ¶m.game.play_area.rect, player_textures_[0], player_animations_);
|
{
|
||||||
player1->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL);
|
const int y = param.game.play_area.rect.h - 30;
|
||||||
player1->setName(lang::getText(53));
|
players_.emplace_back(std::make_unique<Player>(1, param.game.play_area.first_quarter_x - 15, y, demo_.enabled, param.game.play_area.rect, player_textures_[0], player_animations_));
|
||||||
const auto controller1 = getController(player1->getId());
|
players_.back()->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL);
|
||||||
player1->setController(controller1);
|
players_.back()->setName(lang::getText(53));
|
||||||
players_.push_back(std::move(player1));
|
players_.back()->setController(getController(players_.back()->getId()));
|
||||||
|
|
||||||
auto player2 = std::make_unique<Player>(2, (param.game.play_area.first_quarter_x * ((1 * 2) + 1)) - 11, param.game.play_area.rect.h - 30, demo_.enabled, ¶m.game.play_area.rect, player_textures_[1], player_animations_);
|
players_.emplace_back(std::make_unique<Player>(2, param.game.play_area.third_quarter_x - 15, y, demo_.enabled, param.game.play_area.rect, player_textures_[1], player_animations_));
|
||||||
player2->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL);
|
players_.back()->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL);
|
||||||
player2->setName(lang::getText(54));
|
players_.back()->setName(lang::getText(54));
|
||||||
const auto controller2 = getController(player2->getId());
|
players_.back()->setController(getController(players_.back()->getId()));
|
||||||
player2->setController(controller2);
|
}
|
||||||
players_.push_back(std::move(player2));
|
|
||||||
|
|
||||||
// Obtiene mediante "playerID" el jugador que va a empezar jugar
|
// Activa el jugador que coincide con el "player_id"
|
||||||
auto main_player = getPlayer(player_id);
|
{
|
||||||
|
auto player = getPlayer(player_id);
|
||||||
// Cambia el estado del jugador seleccionado
|
player->setStatusPlaying(PlayerStatus::PLAYING);
|
||||||
main_player->setStatusPlaying(PlayerStatus::PLAYING);
|
player->setInvulnerable(false);
|
||||||
|
}
|
||||||
// Como es el principio del juego, empieza sin inmunidad
|
|
||||||
main_player->setInvulnerable(false);
|
|
||||||
|
|
||||||
// Variables relacionadas con la dificultad
|
// Variables relacionadas con la dificultad
|
||||||
switch (difficulty_)
|
switch (difficulty_)
|
||||||
@@ -150,8 +114,7 @@ void Game::init(int player_id)
|
|||||||
{
|
{
|
||||||
default_balloon_speed_ = BALLOON_SPEED_1;
|
default_balloon_speed_ = BALLOON_SPEED_1;
|
||||||
difficulty_score_multiplier_ = 0.5f;
|
difficulty_score_multiplier_ = 0.5f;
|
||||||
difficulty_color_ = difficulty_easy_color;
|
scoreboard_->setColor(scoreboard_easy_color);
|
||||||
scoreboard_->setColor(difficulty_color_);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,8 +122,7 @@ void Game::init(int player_id)
|
|||||||
{
|
{
|
||||||
default_balloon_speed_ = BALLOON_SPEED_1;
|
default_balloon_speed_ = BALLOON_SPEED_1;
|
||||||
difficulty_score_multiplier_ = 1.0f;
|
difficulty_score_multiplier_ = 1.0f;
|
||||||
difficulty_color_ = difficulty_normal_color;
|
scoreboard_->setColor(scoreboard_normal_color);
|
||||||
scoreboard_->setColor(scoreboard_color);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,8 +130,7 @@ void Game::init(int player_id)
|
|||||||
{
|
{
|
||||||
default_balloon_speed_ = BALLOON_SPEED_5;
|
default_balloon_speed_ = BALLOON_SPEED_5;
|
||||||
difficulty_score_multiplier_ = 1.5f;
|
difficulty_score_multiplier_ = 1.5f;
|
||||||
difficulty_color_ = difficulty_hard_color;
|
scoreboard_->setColor(scoreboard_hard_color);
|
||||||
scoreboard_->setColor(difficulty_color_);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,15 +140,13 @@ void Game::init(int player_id)
|
|||||||
|
|
||||||
// Variables para el marcador
|
// Variables para el marcador
|
||||||
scoreboard_->setPos({param.scoreboard.x, param.scoreboard.y, param.scoreboard.w, param.scoreboard.h});
|
scoreboard_->setPos({param.scoreboard.x, param.scoreboard.y, param.scoreboard.w, param.scoreboard.h});
|
||||||
|
scoreboard_->setMode(SCOREBOARD_CENTER_PANEL, ScoreboardMode::STAGE_INFO);
|
||||||
for (const auto &player : players_)
|
for (const auto &player : players_)
|
||||||
{
|
{
|
||||||
scoreboard_->setName(player->getScoreBoardPanel(), player->getName());
|
scoreboard_->setName(player->getScoreBoardPanel(), player->getName());
|
||||||
if (player->isWaiting())
|
if (player->isWaiting())
|
||||||
{
|
|
||||||
scoreboard_->setMode(player->getScoreBoardPanel(), ScoreboardMode::WAITING);
|
scoreboard_->setMode(player->getScoreBoardPanel(), ScoreboardMode::WAITING);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
scoreboard_->setMode(SCOREBOARD_CENTER_PANEL, ScoreboardMode::STAGE_INFO);
|
|
||||||
|
|
||||||
// Resto de variables
|
// Resto de variables
|
||||||
ticks_ = 0;
|
ticks_ = 0;
|
||||||
@@ -232,10 +191,12 @@ void Game::init(int player_id)
|
|||||||
if (demo_.enabled)
|
if (demo_.enabled)
|
||||||
{
|
{
|
||||||
// Selecciona una pantalla al azar
|
// Selecciona una pantalla al azar
|
||||||
constexpr auto demos = 3;
|
{
|
||||||
const auto demo = rand() % demos;
|
constexpr auto demos = 3;
|
||||||
const int stages[demos] = {0, 3, 5};
|
const auto demo = rand() % demos;
|
||||||
current_stage_ = stages[demo];
|
const int stages[demos] = {0, 3, 5};
|
||||||
|
current_stage_ = stages[demo];
|
||||||
|
}
|
||||||
|
|
||||||
// Actualiza el numero de globos explotados según la fase de la demo
|
// Actualiza el numero de globos explotados según la fase de la demo
|
||||||
for (int i = 0; i < current_stage_; ++i)
|
for (int i = 0; i < current_stage_; ++i)
|
||||||
@@ -299,11 +260,26 @@ void Game::init(int player_id)
|
|||||||
smart_sprites_.clear();
|
smart_sprites_.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga los recursos necesarios para la sección 'Game'
|
Game::~Game()
|
||||||
void Game::loadMedia()
|
|
||||||
{
|
{
|
||||||
unloadMedia();
|
// Guarda las puntuaciones en un fichero
|
||||||
|
if (!demo_.enabled)
|
||||||
|
{
|
||||||
|
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
|
||||||
|
manager->saveToFile(asset_->get("score.bin"));
|
||||||
|
}
|
||||||
|
#ifdef RECORDING
|
||||||
|
saveDemoFile(Asset::get()->get("demo1.bin"), demo_.data.at(0));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
Scoreboard::destroy();
|
||||||
|
|
||||||
|
SDL_DestroyTexture(canvas_);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asigna los recursos a variables privadas del objeto
|
||||||
|
void Game::setResources()
|
||||||
|
{
|
||||||
// Texturas
|
// Texturas
|
||||||
{
|
{
|
||||||
bullet_texture_ = Resource::get()->getTexture("bullet.png");
|
bullet_texture_ = Resource::get()->getTexture("bullet.png");
|
||||||
@@ -403,23 +379,6 @@ void Game::loadMedia()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Libera los recursos previamente cargados
|
|
||||||
void Game::unloadMedia()
|
|
||||||
{
|
|
||||||
// Texturas
|
|
||||||
game_text_textures_.clear();
|
|
||||||
balloon_textures_.clear();
|
|
||||||
explosions_textures_.clear();
|
|
||||||
item_textures_.clear();
|
|
||||||
player_textures_.clear();
|
|
||||||
|
|
||||||
// Animaciones
|
|
||||||
player_animations_.clear();
|
|
||||||
balloon_animations_.clear();
|
|
||||||
explosions_animations_.clear();
|
|
||||||
item_animations_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Crea una formación de enemigos
|
// Crea una formación de enemigos
|
||||||
void Game::deployBalloonFormation()
|
void Game::deployBalloonFormation()
|
||||||
{
|
{
|
||||||
@@ -1176,7 +1135,7 @@ ItemType Game::dropItem()
|
|||||||
// Crea un objeto item
|
// Crea un objeto item
|
||||||
void Game::createItem(ItemType type, float x, float y)
|
void Game::createItem(ItemType type, float x, float y)
|
||||||
{
|
{
|
||||||
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_.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]));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vacia el vector de items
|
// Vacia el vector de items
|
||||||
@@ -1371,8 +1330,9 @@ void Game::updateBalloonDeployCounter()
|
|||||||
// Actualiza el juego
|
// Actualiza el juego
|
||||||
void Game::update()
|
void Game::update()
|
||||||
{
|
{
|
||||||
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
|
constexpr int TICKS_SPEED = 15;
|
||||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks
|
// Actualiza el contador de ticks
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
@@ -1945,16 +1905,6 @@ void Game::checkEvents()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Elimina todos los objetos contenidos en vectores
|
|
||||||
void Game::deleteAllVectorObjects()
|
|
||||||
{
|
|
||||||
players_.clear();
|
|
||||||
balloons_.clear();
|
|
||||||
bullets_.clear();
|
|
||||||
items_.clear();
|
|
||||||
smart_sprites_.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Recarga las texturas
|
// Recarga las texturas
|
||||||
void Game::reloadTextures()
|
void Game::reloadTextures()
|
||||||
{
|
{
|
||||||
@@ -2014,8 +1964,8 @@ void Game::pause(bool value)
|
|||||||
// Añade una puntuación a la tabla de records
|
// Añade una puntuación a la tabla de records
|
||||||
void Game::addScoreToScoreBoard(const std::string &name, int score)
|
void Game::addScoreToScoreBoard(const std::string &name, int score)
|
||||||
{
|
{
|
||||||
const auto entry = (HiScoreEntry){trim(name), score};
|
const auto entry = HiScoreEntry(trim(name), score);
|
||||||
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
|
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
|
||||||
manager->add(entry);
|
manager->add(entry);
|
||||||
manager->saveToFile(asset_->get("score.bin"));
|
manager->saveToFile(asset_->get("score.bin"));
|
||||||
}
|
}
|
||||||
@@ -2057,26 +2007,28 @@ void Game::checkPlayersStatusPlaying()
|
|||||||
// Obtiene un jugador a partir de su "id"
|
// Obtiene un jugador a partir de su "id"
|
||||||
std::shared_ptr<Player> Game::getPlayer(int id)
|
std::shared_ptr<Player> Game::getPlayer(int id)
|
||||||
{
|
{
|
||||||
for (const auto &player : players_)
|
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player)
|
||||||
{
|
{ return player->getId() == id; });
|
||||||
if (player->getId() == id)
|
|
||||||
{
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (it != players_.end())
|
||||||
|
{
|
||||||
|
return *it;
|
||||||
|
}
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene un controlador a partir del "id" del jugador
|
// Obtiene un controlador a partir del "id" del jugador
|
||||||
int Game::getController(int player_id)
|
int Game::getController(int player_id)
|
||||||
{
|
{
|
||||||
for (int i = 0; i < (int)options.controller.size(); ++i)
|
auto it = std::find_if(options.controller.begin(), options.controller.end(),
|
||||||
|
[player_id](const auto &controller)
|
||||||
|
{
|
||||||
|
return controller.player_id == player_id;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (it != options.controller.end())
|
||||||
{
|
{
|
||||||
if (options.controller[i].player_id == player_id)
|
return std::distance(options.controller.begin(), it);
|
||||||
{
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1;
|
return -1;
|
||||||
@@ -2117,7 +2069,7 @@ void Game::checkPauseInput()
|
|||||||
void Game::handleDemoMode()
|
void Game::handleDemoMode()
|
||||||
{
|
{
|
||||||
int i = 0;
|
int i = 0;
|
||||||
for (auto &player : players_)
|
for (const auto &player : players_)
|
||||||
{
|
{
|
||||||
if (player->isPlaying())
|
if (player->isPlaying())
|
||||||
{
|
{
|
||||||
@@ -2169,7 +2121,7 @@ void Game::handleFireInput(const std::shared_ptr<Player> &player, BulletType bul
|
|||||||
// Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
// Gestiona las entradas de todos los jugadores en el modo normal (fuera del modo demo).
|
||||||
void Game::handlePlayersInput()
|
void Game::handlePlayersInput()
|
||||||
{
|
{
|
||||||
for (auto &player : players_)
|
for (const auto &player : players_)
|
||||||
{
|
{
|
||||||
if (player->isPlaying())
|
if (player->isPlaying())
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -76,6 +76,12 @@ private:
|
|||||||
int item_clock_odds; // Probabilidad de aparición del objeto
|
int item_clock_odds; // Probabilidad de aparición del objeto
|
||||||
int item_coffee_odds; // Probabilidad de aparición del objeto
|
int item_coffee_odds; // Probabilidad de aparición del objeto
|
||||||
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
int item_coffee_machine_odds; // Probabilidad de aparición del objeto
|
||||||
|
|
||||||
|
// Constructor con valores predeterminados
|
||||||
|
explicit Helper(bool nc = false, bool ncm = false, bool npb = false, int c = 0, int ido = 0, int igo = 0, int ipo = 0, int ico = 0, int icoffo = 0, int icmo = 0)
|
||||||
|
: need_coffee(nc), need_coffee_machine(ncm), need_power_ball(npb), counter(c),
|
||||||
|
item_disk_odds(ido), item_gavina_odds(igo), item_pacmar_odds(ipo), item_clock_odds(ico),
|
||||||
|
item_coffee_odds(icoffo), item_coffee_machine_odds(icmo) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Constantes
|
// Constantes
|
||||||
@@ -87,7 +93,6 @@ private:
|
|||||||
static constexpr int GAME_COMPLETED_END_ = 700;
|
static constexpr int GAME_COMPLETED_END_ = 700;
|
||||||
static constexpr int GAME_OVER_COUNTER_ = 350;
|
static constexpr int GAME_OVER_COUNTER_ = 350;
|
||||||
static constexpr int TIME_STOPPED_COUNTER_ = 300;
|
static constexpr int TIME_STOPPED_COUNTER_ = 300;
|
||||||
static constexpr int TICKS_SPEED_ = 15;
|
|
||||||
|
|
||||||
// Porcentaje de aparición de los objetos
|
// Porcentaje de aparición de los objetos
|
||||||
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
static constexpr int ITEM_POINTS_1_DISK_ODDS_ = 10;
|
||||||
@@ -164,7 +169,6 @@ private:
|
|||||||
int game_completed_counter_; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
int game_completed_counter_; // Contador para el tramo final, cuando se ha completado la partida y ya no aparecen más enemigos
|
||||||
GameDifficulty difficulty_; // Dificultad del juego
|
GameDifficulty difficulty_; // Dificultad del juego
|
||||||
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
float difficulty_score_multiplier_; // Multiplicador de puntos en función de la dificultad
|
||||||
Color difficulty_color_; // Color asociado a la dificultad
|
|
||||||
int last_stage_reached_; // Contiene el número de la última pantalla que se ha alcanzado
|
int last_stage_reached_; // Contiene el número de la última pantalla que se ha alcanzado
|
||||||
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
Demo demo_; // Variable con todas las variables relacionadas con el modo demo
|
||||||
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
int total_power_to_complete_game_; // La suma del poder necesario para completar todas las fases
|
||||||
@@ -183,14 +187,8 @@ private:
|
|||||||
// Comprueba los eventos que hay en cola
|
// Comprueba los eventos que hay en cola
|
||||||
void checkEvents();
|
void checkEvents();
|
||||||
|
|
||||||
// Inicializa las variables necesarias para la sección 'Game'
|
// Asigna los recursos a variables privadas del objeto
|
||||||
void init(int player_id);
|
void setResources();
|
||||||
|
|
||||||
// Carga los recursos necesarios para la sección 'Game'
|
|
||||||
void loadMedia();
|
|
||||||
|
|
||||||
// Libera los recursos previamente cargados
|
|
||||||
void unloadMedia();
|
|
||||||
|
|
||||||
// Crea una formación de enemigos
|
// Crea una formación de enemigos
|
||||||
void deployBalloonFormation();
|
void deployBalloonFormation();
|
||||||
@@ -366,9 +364,6 @@ private:
|
|||||||
// Comprueba si todos los jugadores han terminado de jugar
|
// Comprueba si todos los jugadores han terminado de jugar
|
||||||
bool allPlayersAreNotPlaying();
|
bool allPlayersAreNotPlaying();
|
||||||
|
|
||||||
// Elimina todos los objetos contenidos en vectores
|
|
||||||
void deleteAllVectorObjects();
|
|
||||||
|
|
||||||
// Recarga las texturas
|
// Recarga las texturas
|
||||||
void reloadTextures();
|
void reloadTextures();
|
||||||
|
|
||||||
|
|||||||
@@ -51,7 +51,6 @@ void GameLogo::init()
|
|||||||
shake_.origin = xp;
|
shake_.origin = xp;
|
||||||
|
|
||||||
// Inicializa el bitmap de 'Coffee'
|
// Inicializa el bitmap de 'Coffee'
|
||||||
coffee_sprite_->init();
|
|
||||||
coffee_sprite_->setPosX(xp);
|
coffee_sprite_->setPosX(xp);
|
||||||
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - desp);
|
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - desp);
|
||||||
coffee_sprite_->setWidth(coffee_texture_->getWidth());
|
coffee_sprite_->setWidth(coffee_texture_->getWidth());
|
||||||
@@ -67,7 +66,6 @@ void GameLogo::init()
|
|||||||
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
|
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
|
||||||
|
|
||||||
// Inicializa el bitmap de 'Crisis'
|
// Inicializa el bitmap de 'Crisis'
|
||||||
crisis_sprite_->init();
|
|
||||||
crisis_sprite_->setPosX(xp + 15);
|
crisis_sprite_->setPosX(xp + 15);
|
||||||
crisis_sprite_->setPosY(y_ + desp);
|
crisis_sprite_->setPosY(y_ + desp);
|
||||||
crisis_sprite_->setWidth(crisis_texture_->getWidth());
|
crisis_sprite_->setWidth(crisis_texture_->getWidth());
|
||||||
|
|||||||
@@ -61,8 +61,9 @@ HiScoreTable::~HiScoreTable()
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void HiScoreTable::update()
|
void HiScoreTable::update()
|
||||||
{
|
{
|
||||||
// Actualiza las variables
|
constexpr int TICKS_SPEED = 15;
|
||||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks
|
// Actualiza el contador de ticks
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
@@ -87,7 +88,7 @@ void HiScoreTable::update()
|
|||||||
|
|
||||||
if (counter_ == 150)
|
if (counter_ == 150)
|
||||||
{
|
{
|
||||||
background_->setColor({0, 0, 0});
|
background_->setColor(Color(0, 0, 0));
|
||||||
background_->setAlpha(96);
|
background_->setAlpha(96);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ class HiScoreTable
|
|||||||
private:
|
private:
|
||||||
// Constantes
|
// Constantes
|
||||||
static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador
|
static constexpr Uint16 COUNTER_END_ = 800; // Valor final para el contador
|
||||||
static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa
|
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
|||||||
@@ -25,32 +25,22 @@ struct JA_Music_t; // lines 22-22
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Instructions::Instructions()
|
Instructions::Instructions()
|
||||||
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
|
texture_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
backbuffer_(SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height)),
|
||||||
|
text_(std::make_unique<Text>(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"))),
|
||||||
|
tiled_bg_(std::make_unique<TiledBG>((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::STATIC)),
|
||||||
|
fade_(std::make_unique<Fade>())
|
||||||
{
|
{
|
||||||
// Copia los punteros
|
|
||||||
renderer_ = Screen::get()->getRenderer();
|
|
||||||
|
|
||||||
// Crea objetos
|
|
||||||
text_ = std::make_unique<Text>(Resource::get()->getTexture("smb2.gif"), Resource::get()->getTextFile("smb2.txt"));
|
|
||||||
tiled_bg_ = std::make_unique<TiledBG>((SDL_Rect){0, 0, param.game.width, param.game.height}, TiledBGMode::STATIC);
|
|
||||||
fade_ = std::make_unique<Fade>();
|
|
||||||
|
|
||||||
// Crea un backbuffer para el renderizador
|
// Crea un backbuffer para el renderizador
|
||||||
backbuffer_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
|
||||||
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
||||||
|
|
||||||
// Crea una textura para el texto fijo
|
// Crea una textura para el texto fijo
|
||||||
texture_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
|
||||||
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
|
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
|
||||||
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
section::name = section::Name::INSTRUCTIONS;
|
section::name = section::Name::INSTRUCTIONS;
|
||||||
ticks_ = 0;
|
|
||||||
ticks_speed_ = 15;
|
|
||||||
counter_ = 0;
|
|
||||||
counter_end_ = 700;
|
|
||||||
view_ = {0, 0, param.game.width, param.game.height};
|
view_ = {0, 0, param.game.width, param.game.height};
|
||||||
sprite_pos_ = {0, 0};
|
|
||||||
item_space_ = 2;
|
|
||||||
|
|
||||||
// Inicializa objetos
|
// Inicializa objetos
|
||||||
fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
|
fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
|
||||||
@@ -214,8 +204,9 @@ void Instructions::fillBackbuffer()
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Instructions::update()
|
void Instructions::update()
|
||||||
{
|
{
|
||||||
// Actualiza las variables
|
constexpr int TICKS_SPEED = 15;
|
||||||
if (SDL_GetTicks() - ticks_ > ticks_speed_)
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks
|
// Actualiza el contador de ticks
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
|
|||||||
@@ -30,24 +30,23 @@ class Instructions
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
|
SDL_Texture *texture_; // Textura fija con el texto
|
||||||
|
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
||||||
|
|
||||||
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
|
||||||
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
std::vector<std::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
||||||
std::unique_ptr<Text> text_; // Objeto para escribir texto
|
std::unique_ptr<Text> text_; // Objeto para escribir texto
|
||||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||||
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
std::unique_ptr<Fade> fade_; // Objeto para renderizar fades
|
||||||
|
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
|
||||||
SDL_Texture *texture_; // Textura fija con el texto
|
|
||||||
SDL_Texture *backbuffer_; // Textura para usar como backbuffer
|
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int counter_; // Contador
|
int counter_ = 0; // Contador
|
||||||
int counter_end_; // Valor final para el contador
|
int counter_end_ = 700; // Valor final para el contador
|
||||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||||
Uint32 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
|
SDL_Rect view_; // Vista del backbuffer que se va amostrar por pantalla
|
||||||
SDL_Rect view_; // Vista del backbuffer que se va amostrar por pantalla
|
SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite
|
||||||
SDL_Point sprite_pos_; // Posición del primer sprite
|
int item_space_ = 2; // Espacio entre los items
|
||||||
int item_space_; // Espacio entre los items
|
|
||||||
|
|
||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void update();
|
void update();
|
||||||
|
|||||||
@@ -21,17 +21,13 @@ struct JA_Music_t; // lines 19-19
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Intro::Intro()
|
Intro::Intro()
|
||||||
|
: texture_(Resource::get()->getTexture("intro.png")),
|
||||||
|
text_(std::make_shared<Text>(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt")))
|
||||||
{
|
{
|
||||||
// Reserva memoria para los objetos
|
|
||||||
texture_ = Resource::get()->getTexture("intro.png");
|
|
||||||
text_ = std::make_shared<Text>(Resource::get()->getTexture("nokia.png"), Resource::get()->getTextFile("nokia.txt"));
|
|
||||||
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
section::name = section::Name::INTRO;
|
section::name = section::Name::INTRO;
|
||||||
section::options = section::Options::NONE;
|
section::options = section::Options::NONE;
|
||||||
ticks_ = 0;
|
|
||||||
ticks_speed_ = 15;
|
|
||||||
scene_ = 1;
|
|
||||||
|
|
||||||
// Inicializa los bitmaps de la intro
|
// Inicializa los bitmaps de la intro
|
||||||
constexpr int totalBitmaps = 6;
|
constexpr int totalBitmaps = 6;
|
||||||
@@ -372,7 +368,9 @@ void Intro::updateScenes()
|
|||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void Intro::update()
|
void Intro::update()
|
||||||
{
|
{
|
||||||
if (SDL_GetTicks() - ticks_ > ticks_speed_)
|
constexpr int TICKS_SPEED = 15;
|
||||||
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks
|
// Actualiza el contador de ticks
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
|
|||||||
@@ -26,9 +26,8 @@ private:
|
|||||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||||
Uint8 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
|
int scene_ = 1; // Indica que escena está activa
|
||||||
int scene_; // Indica que escena está activa
|
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void update();
|
void update();
|
||||||
|
|||||||
@@ -5,27 +5,26 @@
|
|||||||
class Texture;
|
class Texture;
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation)
|
Item::Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation)
|
||||||
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
|
: sprite_(std::make_unique<AnimatedSprite>(texture, animation)),
|
||||||
accel_x_(0.0f),
|
|
||||||
floor_collision_(false),
|
|
||||||
type_(type),
|
type_(type),
|
||||||
enabled_(true),
|
play_area_(play_area)
|
||||||
play_area_(play_area),
|
|
||||||
time_to_live_(600)
|
|
||||||
{
|
{
|
||||||
if (type == ItemType::COFFEE_MACHINE)
|
switch (type)
|
||||||
|
{
|
||||||
|
case ItemType::COFFEE_MACHINE:
|
||||||
{
|
{
|
||||||
width_ = 28;
|
width_ = 28;
|
||||||
height_ = 37;
|
height_ = 37;
|
||||||
pos_x_ = (((int)x + (play_area->w / 2)) % (play_area->w - width_ - 5)) + 2;
|
pos_x_ = ((static_cast<int>(x) + (play_area.w / 2)) % (play_area.w - width_ - 5)) + 2;
|
||||||
pos_y_ = -height_;
|
pos_y_ = -height_;
|
||||||
vel_x_ = 0.0f;
|
vel_x_ = 0.0f;
|
||||||
vel_y_ = -0.1f;
|
vel_y_ = -0.1f;
|
||||||
accel_y_ = 0.1f;
|
accel_y_ = 0.1f;
|
||||||
collider_.r = 10;
|
collider_.r = 10;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
else
|
default:
|
||||||
{
|
{
|
||||||
width_ = 20;
|
width_ = 20;
|
||||||
height_ = 20;
|
height_ = 20;
|
||||||
@@ -35,6 +34,8 @@ Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr
|
|||||||
vel_y_ = -4.0f;
|
vel_y_ = -4.0f;
|
||||||
accel_y_ = 0.2f;
|
accel_y_ = 0.2f;
|
||||||
collider_.r = width_ / 2;
|
collider_.r = width_ / 2;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sprite_->setPosX(pos_x_);
|
sprite_->setPosX(pos_x_);
|
||||||
@@ -45,20 +46,20 @@ Item::Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr
|
|||||||
// Centra el objeto en la posición X
|
// Centra el objeto en la posición X
|
||||||
void Item::allignTo(int x)
|
void Item::allignTo(int x)
|
||||||
{
|
{
|
||||||
pos_x_ = float(x - (width_ / 2));
|
pos_x_ = static_cast<float>(x - (width_ / 2));
|
||||||
|
|
||||||
if (pos_x_ < param.game.play_area.rect.x)
|
if (pos_x_ < param.game.play_area.rect.x)
|
||||||
{
|
{
|
||||||
pos_x_ = param.game.play_area.rect.x + 1;
|
pos_x_ = param.game.play_area.rect.x + 1;
|
||||||
}
|
}
|
||||||
else if ((pos_x_ + width_) > play_area_->w)
|
else if (pos_x_ + width_ > play_area_.w)
|
||||||
{
|
{
|
||||||
pos_x_ = float(play_area_->w - width_ - 1);
|
pos_x_ = static_cast<float>(play_area_.w - width_ - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Posición X,Y del sprite
|
// Posición X,Y del sprite
|
||||||
sprite_->setPosX(int(pos_x_));
|
sprite_->setPosX(pos_x_);
|
||||||
sprite_->setPosY(int(pos_y_));
|
sprite_->setPosY(pos_y_);
|
||||||
|
|
||||||
// Alinea el circulo de colisión con el objeto
|
// Alinea el circulo de colisión con el objeto
|
||||||
shiftColliders();
|
shiftColliders();
|
||||||
@@ -94,7 +95,7 @@ void Item::move()
|
|||||||
vel_y_ += accel_y_;
|
vel_y_ += accel_y_;
|
||||||
|
|
||||||
// Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
|
// Si queda fuera de pantalla, corregimos su posición y cambiamos su sentido
|
||||||
if ((pos_x_ < param.game.play_area.rect.x) || (pos_x_ + width_ > play_area_->w))
|
if ((pos_x_ < param.game.play_area.rect.x) || (pos_x_ + width_ > play_area_.w))
|
||||||
{
|
{
|
||||||
// Corregir posición
|
// Corregir posición
|
||||||
pos_x_ -= vel_x_;
|
pos_x_ -= vel_x_;
|
||||||
@@ -114,14 +115,14 @@ void Item::move()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si el objeto se sale por la parte inferior
|
// Si el objeto se sale por la parte inferior
|
||||||
if (pos_y_ + height_ > play_area_->h)
|
if (pos_y_ + height_ > play_area_.h)
|
||||||
{
|
{
|
||||||
// Detiene el objeto
|
// Detiene el objeto
|
||||||
vel_y_ = 0;
|
vel_y_ = 0;
|
||||||
vel_x_ = 0;
|
vel_x_ = 0;
|
||||||
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 (type_ == ItemType::COFFEE_MACHINE)
|
if (type_ == ItemType::COFFEE_MACHINE)
|
||||||
{
|
{
|
||||||
floor_collision_ = true;
|
floor_collision_ = true;
|
||||||
|
|||||||
@@ -29,20 +29,20 @@ private:
|
|||||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los graficos del objeto
|
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los graficos del objeto
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
float pos_x_; // Posición X del objeto
|
float pos_x_; // Posición X del objeto
|
||||||
float pos_y_; // Posición Y del objeto
|
float pos_y_; // Posición Y del objeto
|
||||||
int width_; // Ancho del objeto
|
int width_; // Ancho del objeto
|
||||||
int height_; // Alto del objeto
|
int height_; // Alto del objeto
|
||||||
float vel_x_; // Velocidad en el eje X
|
float vel_x_; // Velocidad en el eje X
|
||||||
float vel_y_; // Velocidad en el eje Y
|
float vel_y_; // Velocidad en el eje Y
|
||||||
float accel_x_; // Aceleración en el eje X
|
float accel_x_ = 0.0f; // 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_ = false; // Indica si el objeto colisiona con el suelo
|
||||||
ItemType type_; // 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_ = true; // 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
|
||||||
Uint16 time_to_live_; // Temporizador con el tiempo que el objeto está presente
|
Uint16 time_to_live_ = 600; // Temporizador con el tiempo que el objeto está presente
|
||||||
|
|
||||||
// Alinea el circulo de colisión con la posición del objeto
|
// Alinea el circulo de colisión con la posición del objeto
|
||||||
void shiftColliders();
|
void shiftColliders();
|
||||||
@@ -58,7 +58,7 @@ private:
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Item(ItemType type, float x, float y, SDL_Rect *play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
Item(ItemType type, float x, float y, SDL_Rect &play_area, std::shared_ptr<Texture> texture, const std::vector<std::string> &animation);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Item() = default;
|
~Item() = default;
|
||||||
|
|||||||
@@ -19,13 +19,13 @@
|
|||||||
Logo::Logo()
|
Logo::Logo()
|
||||||
: since_texture_(Resource::get()->getTexture("logo_since_1998.png")),
|
: since_texture_(Resource::get()->getTexture("logo_since_1998.png")),
|
||||||
since_sprite_(std::make_unique<Sprite>(since_texture_)),
|
since_sprite_(std::make_unique<Sprite>(since_texture_)),
|
||||||
jail_texture_(Resource::get()->getTexture("logo_jailgames.png"))
|
jail_texture_(Resource::get()->getTexture("logo_jailgames.png")),
|
||||||
|
ticks_(0)
|
||||||
{
|
{
|
||||||
|
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
counter_ = 0;
|
counter_ = 0;
|
||||||
section::name = section::Name::LOGO;
|
section::name = section::Name::LOGO;
|
||||||
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_->setPosition({(param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight()});
|
since_sprite_->setPosition({(param.game.width - since_texture_->getWidth()) / 2, 83 + jail_texture_->getHeight() + 5, since_texture_->getWidth(), since_texture_->getHeight()});
|
||||||
@@ -45,14 +45,14 @@ Logo::Logo()
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Inicializa el vector de colores
|
// Inicializa el vector de colores
|
||||||
color_.push_back({0x00, 0x00, 0x00}); // Black
|
color_.push_back(Color(0x00, 0x00, 0x00)); // Black
|
||||||
color_.push_back({0x00, 0x00, 0xd8}); // Blue
|
color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
|
||||||
color_.push_back({0xd8, 0x00, 0x00}); // Red
|
color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
|
||||||
color_.push_back({0xd8, 0x00, 0xd8}); // Magenta
|
color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
|
||||||
color_.push_back({0x00, 0xd8, 0x00}); // Green
|
color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
|
||||||
color_.push_back({0x00, 0xd8, 0xd8}); // Cyan
|
color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
|
||||||
color_.push_back({0xd8, 0xd8, 0x00}); // Yellow
|
color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
|
||||||
color_.push_back({0xFF, 0xFF, 0xFF}); // Bright white
|
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recarga todas las texturas
|
// Recarga todas las texturas
|
||||||
@@ -165,7 +165,8 @@ void Logo::updateTextureColors()
|
|||||||
// Actualiza las variables
|
// Actualiza las variables
|
||||||
void Logo::update()
|
void Logo::update()
|
||||||
{
|
{
|
||||||
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
|
constexpr int TICKS_SPEED = 15;
|
||||||
|
|
||||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks
|
// Actualiza el contador de ticks
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ class Logo
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Constantes
|
// Constantes
|
||||||
static constexpr Uint32 TICKS_SPEED = 15; // Velocidad a la que se repiten los bucles del programa
|
|
||||||
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
|
static constexpr int SHOW_SINCE_SPRITE_COUNTER_MARK = 70; // Tiempo del contador en el que empieza a verse el sprite de "SINCE 1998"
|
||||||
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro
|
static constexpr int INIT_FADE_COUNTER_MARK = 300; // Tiempo del contador cuando inicia el fade a negro
|
||||||
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo
|
static constexpr int END_LOGO_COUNTER_MARK = 400; // Tiempo del contador para terminar el logo
|
||||||
|
|||||||
@@ -6,43 +6,36 @@
|
|||||||
#include <iostream> // for basic_ostream, char_traits, operator<<
|
#include <iostream> // for basic_ostream, char_traits, operator<<
|
||||||
#include "utils.h" // for HiScoreEntry
|
#include "utils.h" // for HiScoreEntry
|
||||||
|
|
||||||
// Constructor
|
|
||||||
ManageHiScoreTable::ManageHiScoreTable(std::vector<HiScoreEntry> *table)
|
|
||||||
: table_(table) {}
|
|
||||||
|
|
||||||
// Resetea la tabla a los valores por defecto
|
// Resetea la tabla a los valores por defecto
|
||||||
void ManageHiScoreTable::clear()
|
void ManageHiScoreTable::clear()
|
||||||
{
|
{
|
||||||
// Limpia la tabla
|
// Limpia la tabla
|
||||||
table_->clear();
|
table_.clear();
|
||||||
|
|
||||||
// Añade 10 entradas predefinidas
|
// Añade 10 entradas predefinidas
|
||||||
table_->push_back({"Bry", 1000000});
|
table_.push_back(HiScoreEntry("Bry", 1000000));
|
||||||
table_->push_back({"Usufondo", 500000});
|
table_.push_back(HiScoreEntry("Usufondo", 500000));
|
||||||
table_->push_back({"G.Lucas", 100000});
|
table_.push_back(HiScoreEntry("G.Lucas", 100000));
|
||||||
table_->push_back({"P.Delgat", 50000});
|
table_.push_back(HiScoreEntry("P.Delgat", 50000));
|
||||||
table_->push_back({"P.Arrabalera", 10000});
|
table_.push_back(HiScoreEntry("P.Arrabalera", 10000));
|
||||||
table_->push_back({"Pelechano", 5000});
|
table_.push_back(HiScoreEntry("Pelechano", 5000));
|
||||||
table_->push_back({"Sahuquillo", 1000});
|
table_.push_back(HiScoreEntry("Sahuquillo", 1000));
|
||||||
table_->push_back({"Bacteriol", 500});
|
table_.push_back(HiScoreEntry("Bacteriol", 500));
|
||||||
table_->push_back({"Pepe", 200});
|
table_.push_back(HiScoreEntry("Pepe", 200));
|
||||||
table_->push_back({"Rosita", 100});
|
table_.push_back(HiScoreEntry("Rosita", 100));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Añade un elemento a la tabla
|
// Añade un elemento a la tabla
|
||||||
void ManageHiScoreTable::add(HiScoreEntry entry)
|
void ManageHiScoreTable::add(HiScoreEntry entry)
|
||||||
{
|
{
|
||||||
// Añade la entrada a la tabla
|
// Añade la entrada a la tabla
|
||||||
table_->push_back(entry);
|
table_.push_back(entry);
|
||||||
|
|
||||||
// Ordena la tabla
|
// Ordena la tabla
|
||||||
sort();
|
sort();
|
||||||
|
|
||||||
// Deja solo las 10 primeras entradas
|
// Deja solo las 10 primeras entradas
|
||||||
if (static_cast<int>(table_->size()) > 10)
|
table_.resize(10);
|
||||||
{
|
|
||||||
table_->resize(10);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ordena la tabla
|
// Ordena la tabla
|
||||||
@@ -51,28 +44,27 @@ void ManageHiScoreTable::sort()
|
|||||||
struct
|
struct
|
||||||
{
|
{
|
||||||
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
|
bool operator()(const HiScoreEntry &a, const HiScoreEntry &b) const { return a.score > b.score; }
|
||||||
} custom_less;
|
} scoreDescendingComparator;
|
||||||
|
|
||||||
std::sort(table_->begin(), table_->end(), custom_less);
|
std::sort(table_.begin(), table_.end(), scoreDescendingComparator);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Carga la tabla con los datos de un fichero
|
// Carga la tabla con los datos de un fichero
|
||||||
bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
||||||
{
|
{
|
||||||
clear();
|
clear();
|
||||||
|
|
||||||
auto success = true;
|
auto success = true;
|
||||||
auto file = SDL_RWFromFile(file_path.c_str(), "r+b");
|
auto file = SDL_RWFromFile(file_path.c_str(), "r+b");
|
||||||
|
|
||||||
if (file)
|
if (file)
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||||
std::cout << "Reading file: " << file_name.c_str() << std::endl;
|
|
||||||
for (int i = 0; i < (int)table_->size(); ++i)
|
for (auto &entry : table_)
|
||||||
{
|
{
|
||||||
int nameSize = 0;
|
int nameSize = 0;
|
||||||
|
|
||||||
if (SDL_RWread(file, &table_->at(i).score, sizeof(int), 1) == 0)
|
if (SDL_RWread(file, &entry.score, sizeof(int), 1) == 0)
|
||||||
{
|
{
|
||||||
success = false;
|
success = false;
|
||||||
break;
|
break;
|
||||||
@@ -84,19 +76,15 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
char *name = static_cast<char *>(malloc(nameSize + 1));
|
std::vector<char> nameBuffer(nameSize + 1);
|
||||||
if (SDL_RWread(file, name, sizeof(char) * nameSize, 1) == 0)
|
if (SDL_RWread(file, nameBuffer.data(), sizeof(char) * nameSize, 1) == 0)
|
||||||
{
|
{
|
||||||
success = false;
|
success = false;
|
||||||
free(name);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
nameBuffer[nameSize] = '\0';
|
||||||
name[nameSize] = 0;
|
entry.name = std::string(nameBuffer.data());
|
||||||
table_->at(i).name = name;
|
|
||||||
free(name);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_RWclose(file);
|
SDL_RWclose(file);
|
||||||
@@ -113,28 +101,26 @@ 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)
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
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");
|
||||||
|
|
||||||
if (file)
|
if (file)
|
||||||
{
|
{
|
||||||
// Guarda los datos
|
// Guarda los datos
|
||||||
for (int i = 0; i < (int)table_->size(); ++i)
|
for (int i = 0; i < (int)table_.size(); ++i)
|
||||||
{
|
{
|
||||||
SDL_RWwrite(file, &table_->at(i).score, sizeof(int), 1);
|
SDL_RWwrite(file, &table_.at(i).score, sizeof(int), 1);
|
||||||
const int nameSize = (int)table_->at(i).name.size();
|
const int nameSize = (int)table_.at(i).name.size();
|
||||||
SDL_RWwrite(file, &nameSize, sizeof(int), 1);
|
SDL_RWwrite(file, &nameSize, sizeof(int), 1);
|
||||||
SDL_RWwrite(file, table_->at(i).name.c_str(), nameSize, 1);
|
SDL_RWwrite(file, table_.at(i).name.c_str(), nameSize, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Writing file: " << file_name.c_str() << std::endl;
|
std::cout << "Writing file: " << getFileName(file_path).c_str() << std::endl;
|
||||||
// Cierra el fichero
|
|
||||||
SDL_RWclose(file);
|
SDL_RWclose(file);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl;
|
std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl;
|
||||||
}
|
}
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
@@ -17,14 +17,15 @@ class ManageHiScoreTable
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Variables
|
// Variables
|
||||||
std::vector<HiScoreEntry> *table_; // Tabla con los records
|
std::vector<HiScoreEntry> &table_; // Tabla con los records
|
||||||
|
|
||||||
// Ordena la tabla
|
// Ordena la tabla
|
||||||
void sort();
|
void sort();
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> *table);
|
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||||
|
: table_(table) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~ManageHiScoreTable() = default;
|
~ManageHiScoreTable() = default;
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
Notifier *Notifier::notifier_ = nullptr;
|
Notifier *Notifier::notifier_ = nullptr;
|
||||||
|
|
||||||
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
// [SINGLETON] Crearemos el objeto screen con esta función estática
|
||||||
void Notifier::init(std::string icon_file, std::shared_ptr<Text> text, const std::string &sound_file)
|
void Notifier::init(const std::string &icon_file, std::shared_ptr<Text> text, const std::string &sound_file)
|
||||||
{
|
{
|
||||||
Notifier::notifier_ = new Notifier(icon_file, text, sound_file);
|
Notifier::notifier_ = new Notifier(icon_file, text, sound_file);
|
||||||
}
|
}
|
||||||
@@ -165,7 +165,7 @@ void Notifier::clearFinishedNotifications()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Notifier::showText(std::string text1, std::string text2, int icon, std::string code)
|
void Notifier::showText(std::string text1, std::string text2, int icon, const std::string &code)
|
||||||
{
|
{
|
||||||
// Cuenta el número de textos a mostrar
|
// Cuenta el número de textos a mostrar
|
||||||
const int num_texts = !text1.empty() + !text2.empty();
|
const int num_texts = !text1.empty() + !text2.empty();
|
||||||
@@ -286,7 +286,7 @@ void Notifier::showText(std::string text1, std::string text2, int icon, std::str
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Escribe el texto de la notificación
|
// Escribe el texto de la notificación
|
||||||
Color color = {255, 255, 255};
|
Color color{255, 255, 255};
|
||||||
if (num_texts == 2)
|
if (num_texts == 2)
|
||||||
{ // Dos lineas de texto
|
{ // 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, text1, color);
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ private:
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// [SINGLETON] Crearemos el objeto notifier con esta función estática
|
// [SINGLETON] Crearemos el objeto notifier con esta función estática
|
||||||
static void init(std::string icon_file, std::shared_ptr<Text> text, const std::string &sound_file);
|
static void init(const std::string &icon_file, std::shared_ptr<Text> text, const std::string &sound_file);
|
||||||
|
|
||||||
// [SINGLETON] Destruiremos el objeto notifier con esta función estática
|
// [SINGLETON] Destruiremos el objeto notifier con esta función estática
|
||||||
static void destroy();
|
static void destroy();
|
||||||
@@ -111,7 +111,7 @@ public:
|
|||||||
* @param icon Icono opcional para mostrar (valor predeterminado: -1).
|
* @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).
|
* @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());
|
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, const std::string &code = std::string());
|
||||||
|
|
||||||
// Indica si hay notificaciones activas
|
// Indica si hay notificaciones activas
|
||||||
bool isActive();
|
bool isActive();
|
||||||
|
|||||||
@@ -86,14 +86,13 @@ bool loadOptionsFile(std::string file_path)
|
|||||||
bool success = true;
|
bool success = true;
|
||||||
|
|
||||||
// Variables para manejar el fichero
|
// Variables para manejar el fichero
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
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
|
||||||
std::cout << "Reading file: " << file_name << std::endl;
|
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||||
std::string line;
|
std::string line;
|
||||||
while (std::getline(file, line))
|
while (std::getline(file, line))
|
||||||
{
|
{
|
||||||
@@ -105,14 +104,12 @@ 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())))
|
||||||
{
|
{
|
||||||
std::cout << "Warning: file " << file_name << std::endl;
|
std::cout << "Warning: file " << getFileName(file_path) << 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;
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cierra el fichero
|
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,16 +143,15 @@ 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)
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
std::ofstream file(file_path);
|
std::ofstream file(file_path);
|
||||||
|
|
||||||
if (!file.good())
|
if (!file.good())
|
||||||
{
|
{
|
||||||
std::cout << file_name << " can't be opened" << std::endl;
|
std::cout << getFileName(file_path) << " can't be opened" << std::endl;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cout << "Writing file: " << file_name << std::endl;
|
std::cout << "Writing file: " << getFileName(file_path) << std::endl;
|
||||||
|
|
||||||
// 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));
|
||||||
|
|||||||
@@ -78,8 +78,7 @@ void loadParamsFromFile(const std::string &file_path)
|
|||||||
throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
|
throw std::runtime_error("No se pudo abrir el archivo: " + file_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||||
std::cout << "Reading file: " << file_name << std::endl;
|
|
||||||
|
|
||||||
std::string line, param1, param2;
|
std::string line, param1, param2;
|
||||||
while (std::getline(file, line))
|
while (std::getline(file, line))
|
||||||
|
|||||||
@@ -11,26 +11,18 @@
|
|||||||
#include "options.h"
|
#include "options.h"
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Player::Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, const 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, const 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),
|
|
||||||
id_(id),
|
id_(id),
|
||||||
pos_x_(x),
|
play_area_(play_area),
|
||||||
pos_y_(y),
|
|
||||||
default_pos_x_(x),
|
default_pos_x_(x),
|
||||||
default_pos_y_(y),
|
default_pos_y_(y),
|
||||||
status_playing_(PlayerStatus::WAITING),
|
|
||||||
scoreboard_panel_(0),
|
|
||||||
name_(std::string()),
|
|
||||||
controller_index_(0),
|
|
||||||
demo_(demo)
|
demo_(demo)
|
||||||
{
|
{
|
||||||
// Reserva memoria para los objetos
|
// Configura objetos
|
||||||
power_sprite_->getTexture()->setAlpha(224);
|
power_sprite_->getTexture()->setAlpha(224);
|
||||||
|
|
||||||
// Establece los offsets para el sprite de PowerUp
|
|
||||||
power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
|
power_up_desp_x_ = (power_sprite_->getWidth() - player_sprite_->getWidth()) / 2;
|
||||||
power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight()));
|
power_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight()));
|
||||||
|
|
||||||
@@ -46,25 +38,21 @@ void Player::init()
|
|||||||
pos_x_ = default_pos_x_;
|
pos_x_ = default_pos_x_;
|
||||||
pos_y_ = default_pos_y_;
|
pos_y_ = default_pos_y_;
|
||||||
status_walking_ = PlayerStatus::WALKING_STOP;
|
status_walking_ = PlayerStatus::WALKING_STOP;
|
||||||
status_firing_ = PlayerStatus::FIRING_NO;
|
status_firing_ = PlayerStatus::FIRING_NONE;
|
||||||
|
status_playing_ = PlayerStatus::WAITING;
|
||||||
invulnerable_ = true;
|
invulnerable_ = true;
|
||||||
invulnerable_counter_ = PLAYER_INVULNERABLE_COUNTER;
|
invulnerable_counter_ = INVULNERABLE_COUNTER_;
|
||||||
power_up_ = false;
|
power_up_ = false;
|
||||||
power_up_counter_ = PLAYER_POWERUP_COUNTER;
|
power_up_counter_ = POWERUP_COUNTER_;
|
||||||
extra_hit_ = false;
|
extra_hit_ = false;
|
||||||
coffees_ = 0;
|
coffees_ = 0;
|
||||||
input_ = true;
|
|
||||||
continue_ticks_ = 0;
|
continue_ticks_ = 0;
|
||||||
continue_counter_ = 10;
|
continue_counter_ = 10;
|
||||||
enter_name_ticks_ = 0;
|
enter_name_ticks_ = 0;
|
||||||
enter_name_counter_ = param.game.enter_name_seconds;
|
enter_name_counter_ = param.game.enter_name_seconds;
|
||||||
width_ = 30;
|
|
||||||
height_ = 30;
|
|
||||||
collider_.r = 9;
|
|
||||||
shiftColliders();
|
shiftColliders();
|
||||||
vel_x_ = 0;
|
vel_x_ = 0;
|
||||||
vel_y_ = 0;
|
vel_y_ = 0;
|
||||||
base_speed_ = 1.5;
|
|
||||||
score_ = 0;
|
score_ = 0;
|
||||||
score_multiplier_ = 1.0f;
|
score_multiplier_ = 1.0f;
|
||||||
cooldown_ = 10;
|
cooldown_ = 10;
|
||||||
@@ -107,14 +95,14 @@ void Player::setInputPlaying(InputType input)
|
|||||||
{
|
{
|
||||||
case InputType::LEFT:
|
case InputType::LEFT:
|
||||||
{
|
{
|
||||||
vel_x_ = -base_speed_;
|
vel_x_ = -BASE_SPEED_;
|
||||||
setWalkingStatus(PlayerStatus::WALKING_LEFT);
|
setWalkingStatus(PlayerStatus::WALKING_LEFT);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case InputType::RIGHT:
|
case InputType::RIGHT:
|
||||||
{
|
{
|
||||||
vel_x_ = base_speed_;
|
vel_x_ = BASE_SPEED_;
|
||||||
setWalkingStatus(PlayerStatus::WALKING_RIGHT);
|
setWalkingStatus(PlayerStatus::WALKING_RIGHT);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -186,7 +174,7 @@ void Player::move()
|
|||||||
pos_x_ += vel_x_;
|
pos_x_ += vel_x_;
|
||||||
|
|
||||||
// Si el jugador abandona el area de juego por los laterales
|
// Si el jugador abandona el area de juego por los laterales
|
||||||
if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + width_ > play_area_->w + 5))
|
if ((pos_x_ < param.game.play_area.rect.x - 5) || (pos_x_ + WIDTH_ > play_area_.w + 5))
|
||||||
{
|
{
|
||||||
// Restaura su posición
|
// Restaura su posición
|
||||||
pos_x_ -= vel_x_;
|
pos_x_ -= vel_x_;
|
||||||
@@ -203,7 +191,7 @@ void Player::move()
|
|||||||
player_sprite_->update();
|
player_sprite_->update();
|
||||||
|
|
||||||
// Si el cadaver abandona el area de juego por los laterales
|
// Si el cadaver abandona el area de juego por los laterales
|
||||||
if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + width_ > play_area_->w))
|
if ((player_sprite_->getPosX() < param.game.play_area.rect.x) || (player_sprite_->getPosX() + WIDTH_ > play_area_.w))
|
||||||
{
|
{
|
||||||
// Restaura su posición
|
// Restaura su posición
|
||||||
const float vx = player_sprite_->getVelX();
|
const float vx = player_sprite_->getVelX();
|
||||||
@@ -226,7 +214,7 @@ void Player::render()
|
|||||||
{
|
{
|
||||||
if (power_up_ && isPlaying())
|
if (power_up_ && isPlaying())
|
||||||
{
|
{
|
||||||
if (power_up_counter_ > (PLAYER_POWERUP_COUNTER / 4) || power_up_counter_ % 20 > 4)
|
if (power_up_counter_ > (POWERUP_COUNTER_ / 4) || power_up_counter_ % 20 > 4)
|
||||||
{
|
{
|
||||||
power_sprite_->render();
|
power_sprite_->render();
|
||||||
}
|
}
|
||||||
@@ -261,7 +249,7 @@ void Player::setAnimation()
|
|||||||
// Establece la animación a partir de las cadenas
|
// Establece la animación a partir de las cadenas
|
||||||
if (isPlaying())
|
if (isPlaying())
|
||||||
{
|
{
|
||||||
if (status_firing_ == PlayerStatus::FIRING_NO)
|
if (status_firing_ == PlayerStatus::FIRING_NONE)
|
||||||
{ // No esta disparando
|
{ // No esta disparando
|
||||||
player_sprite_->setCurrentAnimation(a_walking);
|
player_sprite_->setCurrentAnimation(a_walking);
|
||||||
player_sprite_->setFlip(flip_walk);
|
player_sprite_->setFlip(flip_walk);
|
||||||
@@ -301,13 +289,13 @@ int Player::getPosY() const
|
|||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
int Player::getWidth() const
|
int Player::getWidth() const
|
||||||
{
|
{
|
||||||
return width_;
|
return WIDTH_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
int Player::getHeight() const
|
int Player::getHeight() const
|
||||||
{
|
{
|
||||||
return height_;
|
return HEIGHT_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Indica si el jugador puede disparar
|
// Indica si el jugador puede disparar
|
||||||
@@ -336,7 +324,7 @@ void Player::updateCooldown()
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
setFiringStatus(PlayerStatus::FIRING_NO);
|
setFiringStatus(PlayerStatus::FIRING_NONE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -459,8 +447,8 @@ void Player::setStatusPlaying(PlayerStatus value)
|
|||||||
{
|
{
|
||||||
case PlayerStatus::PLAYING:
|
case PlayerStatus::PLAYING:
|
||||||
{
|
{
|
||||||
status_playing_ = PlayerStatus::PLAYING;
|
|
||||||
init();
|
init();
|
||||||
|
status_playing_ = PlayerStatus::PLAYING;
|
||||||
setScoreboardMode(ScoreboardMode::SCORE);
|
setScoreboardMode(ScoreboardMode::SCORE);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -556,7 +544,7 @@ bool Player::isInvulnerable() const
|
|||||||
void Player::setInvulnerable(bool value)
|
void Player::setInvulnerable(bool value)
|
||||||
{
|
{
|
||||||
invulnerable_ = value;
|
invulnerable_ = value;
|
||||||
invulnerable_counter_ = invulnerable_ ? PLAYER_INVULNERABLE_COUNTER : 0;
|
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
@@ -599,7 +587,7 @@ bool Player::isPowerUp() const
|
|||||||
void Player::setPowerUp()
|
void Player::setPowerUp()
|
||||||
{
|
{
|
||||||
power_up_ = true;
|
power_up_ = true;
|
||||||
power_up_counter_ = PLAYER_POWERUP_COUNTER;
|
power_up_counter_ = POWERUP_COUNTER_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el valor de la variable
|
// Obtiene el valor de la variable
|
||||||
@@ -654,18 +642,6 @@ void Player::removeExtraHit()
|
|||||||
extra_hit_ = coffees_ == 0 ? false : true;
|
extra_hit_ = coffees_ == 0 ? false : true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Habilita la entrada de ordenes
|
|
||||||
void Player::enableInput()
|
|
||||||
{
|
|
||||||
input_ = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deshabilita la entrada de ordenes
|
|
||||||
void Player::disableInput()
|
|
||||||
{
|
|
||||||
input_ = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Devuelve el número de cafes actuales
|
// Devuelve el número de cafes actuales
|
||||||
int Player::getCoffees() const
|
int Player::getCoffees() const
|
||||||
{
|
{
|
||||||
@@ -681,8 +657,8 @@ Circle &Player::getCollider()
|
|||||||
// 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 Player::shiftColliders()
|
void Player::shiftColliders()
|
||||||
{
|
{
|
||||||
collider_.x = int(pos_x_ + (width_ / 2));
|
collider_.x = static_cast<int>(pos_x_ + (WIDTH_ / 2));
|
||||||
collider_.y = int(pos_y_ + (height_ / 2));
|
collider_.y = static_cast<int>(pos_y_ + (HEIGHT_ / 2));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pone las texturas del jugador
|
// Pone las texturas del jugador
|
||||||
@@ -703,9 +679,8 @@ void Player::updateContinueCounter()
|
|||||||
{
|
{
|
||||||
if (status_playing_ == PlayerStatus::CONTINUE)
|
if (status_playing_ == PlayerStatus::CONTINUE)
|
||||||
{
|
{
|
||||||
constexpr Uint32 ticks_speed = 1000;
|
constexpr int TICKS_SPEED = 1000;
|
||||||
|
if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED)
|
||||||
if (SDL_GetTicks() - continue_ticks_ > ticks_speed)
|
|
||||||
{
|
{
|
||||||
decContinueCounter();
|
decContinueCounter();
|
||||||
}
|
}
|
||||||
@@ -717,9 +692,8 @@ void Player::updateEnterNameCounter()
|
|||||||
{
|
{
|
||||||
if (status_playing_ == PlayerStatus::ENTERING_NAME)
|
if (status_playing_ == PlayerStatus::ENTERING_NAME)
|
||||||
{
|
{
|
||||||
constexpr Uint32 ticks_speed = 1000;
|
constexpr int TICKS_SPEED = 1000;
|
||||||
|
if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED)
|
||||||
if (SDL_GetTicks() - enter_name_ticks_ > ticks_speed)
|
|
||||||
{
|
{
|
||||||
decEnterNameCounter();
|
decEnterNameCounter();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ enum class PlayerStatus
|
|||||||
FIRING_UP,
|
FIRING_UP,
|
||||||
FIRING_LEFT,
|
FIRING_LEFT,
|
||||||
FIRING_RIGHT,
|
FIRING_RIGHT,
|
||||||
FIRING_NO,
|
FIRING_NONE,
|
||||||
|
|
||||||
PLAYING,
|
PLAYING,
|
||||||
CONTINUE,
|
CONTINUE,
|
||||||
@@ -35,54 +35,55 @@ enum class PlayerStatus
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Variables del jugador
|
// Variables del jugador
|
||||||
constexpr int PLAYER_INVULNERABLE_COUNTER = 200;
|
|
||||||
constexpr int PLAYER_POWERUP_COUNTER = 1500;
|
|
||||||
|
|
||||||
// Clase Player
|
// Clase Player
|
||||||
class Player
|
class Player
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
|
// Constantes
|
||||||
|
static constexpr int POWERUP_COUNTER_ = 1500; // Duración del estado PowerUp
|
||||||
|
static constexpr int INVULNERABLE_COUNTER_ = 200; // Duración del estado invulnerable
|
||||||
|
static constexpr int WIDTH_ = 30; // Anchura
|
||||||
|
static constexpr int HEIGHT_ = 30; // Altura
|
||||||
|
static constexpr float BASE_SPEED_ = 1.5f; // Velocidad base del jugador
|
||||||
|
|
||||||
// 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
|
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
|
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
|
||||||
float pos_x_; // Posicion en el eje X
|
SDL_Rect play_area_; // Rectangulo con la zona de juego
|
||||||
int pos_y_; // Posicion en el eje Y
|
float pos_x_ = 0.0f; // Posicion en el eje X
|
||||||
float default_pos_x_; // Posición inicial para el jugador
|
int pos_y_ = 0; // Posicion en el eje Y
|
||||||
int default_pos_y_; // Posición inicial para el jugador
|
float default_pos_x_; // Posición inicial para el jugador
|
||||||
int width_; // Anchura
|
int default_pos_y_; // Posición inicial para el jugador
|
||||||
int height_; // Altura
|
float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X
|
||||||
float vel_x_; // Cantidad de pixeles a desplazarse en el eje X
|
int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
|
||||||
int vel_y_; // Cantidad de pixeles a desplazarse en el eje Y
|
int cooldown_ = 10; // Contador durante el cual no puede disparar
|
||||||
float base_speed_; // Velocidad base del jugador
|
int score_ = 0; // Puntos del jugador
|
||||||
int cooldown_; // Contador durante el cual no puede disparar
|
float score_multiplier_ = 1.0f; // Multiplicador de puntos
|
||||||
int score_; // Puntos del jugador
|
PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse
|
||||||
float score_multiplier_; // Multiplicador de puntos
|
PlayerStatus status_firing_ = PlayerStatus::FIRING_NONE; // Estado del jugador al disparar
|
||||||
PlayerStatus status_walking_; // Estado del jugador al moverse
|
PlayerStatus status_playing_ = PlayerStatus::WAITING; // Estado del jugador en el juego
|
||||||
PlayerStatus status_firing_; // Estado del jugador al disparar
|
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
||||||
PlayerStatus status_playing_; // Estado del jugador en el juego
|
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
|
||||||
bool invulnerable_; // Indica si el jugador es invulnerable
|
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
||||||
int invulnerable_counter_; // Contador para la invulnerabilidad
|
int coffees_ = 0; // Indica cuantos cafes lleva acumulados
|
||||||
bool extra_hit_; // Indica si el jugador tiene un toque extra
|
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
||||||
int coffees_; // Indica cuantos cafes lleva acumulados
|
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
|
||||||
bool power_up_; // Indica si el jugador tiene activo el modo PowerUp
|
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||||
int power_up_counter_; // Temporizador para el modo PowerUp
|
Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador
|
||||||
int power_up_desp_x_; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
int continue_counter_ = 10; // Contador para poder continuar
|
||||||
bool input_; // Indica si puede recibir ordenes de entrada
|
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
|
||||||
Circle collider_; // Circulo de colisión del jugador
|
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
|
||||||
int continue_counter_; // Contador para poder continuar
|
std::string name_; // Nombre del jugador
|
||||||
Uint32 continue_ticks_; // Variable para poder cambiar el contador de continue en función del tiempo
|
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
|
||||||
int scoreboard_panel_; // Panel del marcador asociado al jugador
|
int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse
|
||||||
std::string name_; // Nombre del jugador
|
bool demo_; // Para que el jugador sepa si está en el modo demostración
|
||||||
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
|
int enter_name_counter_; // Contador para poner nombre
|
||||||
int controller_index_; // Indice del array de mandos que utilizará para moverse
|
Uint32 enter_name_ticks_ = 0; // Variable para poder cambiar el contador de poner nombre en función del tiempo
|
||||||
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();
|
||||||
@@ -113,7 +114,7 @@ private:
|
|||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
Player(int id, float x, int y, bool demo, SDL_Rect *play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
|
Player(int id, float x, int y, bool demo, SDL_Rect &play_area, std::vector<std::shared_ptr<Texture>> texture, const std::vector<std::vector<std::string>> &animations);
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Player() = default;
|
~Player() = default;
|
||||||
@@ -256,12 +257,6 @@ public:
|
|||||||
// Quita el toque extra al jugador
|
// Quita el toque extra al jugador
|
||||||
void removeExtraHit();
|
void removeExtraHit();
|
||||||
|
|
||||||
// Habilita la entrada de ordenes
|
|
||||||
void enableInput();
|
|
||||||
|
|
||||||
// Deshabilita la entrada de ordenes
|
|
||||||
void disableInput();
|
|
||||||
|
|
||||||
// Devuelve el número de cafes actuales
|
// Devuelve el número de cafes actuales
|
||||||
int getCoffees() const;
|
int getCoffees() const;
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#include <algorithm>
|
||||||
|
#include <stdexcept>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include "resource.h"
|
#include "resource.h"
|
||||||
#include "asset.h"
|
#include "asset.h"
|
||||||
@@ -51,13 +53,14 @@ Resource::~Resource()
|
|||||||
// Obtiene el sonido a partir de un nombre
|
// Obtiene el sonido a partir de un nombre
|
||||||
JA_Sound_t *Resource::getSound(const std::string &name)
|
JA_Sound_t *Resource::getSound(const std::string &name)
|
||||||
{
|
{
|
||||||
for (const auto &s : sounds_)
|
auto it = std::find_if(sounds_.begin(), sounds_.end(), [&name](const auto &s)
|
||||||
|
{ return s.name == name; });
|
||||||
|
|
||||||
|
if (it != sounds_.end())
|
||||||
{
|
{
|
||||||
if (s.name == name)
|
return it->sound;
|
||||||
{
|
|
||||||
return s.sound;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Error: Sonido no encontrado " << name << std::endl;
|
std::cerr << "Error: Sonido no encontrado " << name << std::endl;
|
||||||
throw std::runtime_error("Sonido no encontrado: " + name);
|
throw std::runtime_error("Sonido no encontrado: " + name);
|
||||||
}
|
}
|
||||||
@@ -65,13 +68,14 @@ JA_Sound_t *Resource::getSound(const std::string &name)
|
|||||||
// Obtiene la música a partir de un nombre
|
// Obtiene la música a partir de un nombre
|
||||||
JA_Music_t *Resource::getMusic(const std::string &name)
|
JA_Music_t *Resource::getMusic(const std::string &name)
|
||||||
{
|
{
|
||||||
for (const auto &m : musics_)
|
auto it = std::find_if(musics_.begin(), musics_.end(), [&name](const auto &m)
|
||||||
|
{ return m.name == name; });
|
||||||
|
|
||||||
|
if (it != musics_.end())
|
||||||
{
|
{
|
||||||
if (m.name == name)
|
return it->music;
|
||||||
{
|
|
||||||
return m.music;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Error: Música no encontrada " << name << std::endl;
|
std::cerr << "Error: Música no encontrada " << name << std::endl;
|
||||||
throw std::runtime_error("Música no encontrada: " + name);
|
throw std::runtime_error("Música no encontrada: " + name);
|
||||||
}
|
}
|
||||||
@@ -79,13 +83,14 @@ JA_Music_t *Resource::getMusic(const std::string &name)
|
|||||||
// Obtiene la textura a partir de un nombre
|
// Obtiene la textura a partir de un nombre
|
||||||
std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
|
std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
|
||||||
{
|
{
|
||||||
for (const auto &t : textures_)
|
auto it = std::find_if(textures_.begin(), textures_.end(), [&name](const auto &t)
|
||||||
|
{ return t.name == name; });
|
||||||
|
|
||||||
|
if (it != textures_.end())
|
||||||
{
|
{
|
||||||
if (t.name == name)
|
return it->texture;
|
||||||
{
|
|
||||||
return t.texture;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Error: Imagen no encontrada " << name << std::endl;
|
std::cerr << "Error: Imagen no encontrada " << name << std::endl;
|
||||||
throw std::runtime_error("Imagen no encontrada: " + name);
|
throw std::runtime_error("Imagen no encontrada: " + name);
|
||||||
}
|
}
|
||||||
@@ -93,13 +98,14 @@ std::shared_ptr<Texture> Resource::getTexture(const std::string &name)
|
|||||||
// Obtiene el fichero de texto a partir de un nombre
|
// Obtiene el fichero de texto a partir de un nombre
|
||||||
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
|
std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
|
||||||
{
|
{
|
||||||
for (const auto &t : text_files_)
|
auto it = std::find_if(text_files_.begin(), text_files_.end(), [&name](const auto &t)
|
||||||
|
{ return t.name == name; });
|
||||||
|
|
||||||
|
if (it != text_files_.end())
|
||||||
{
|
{
|
||||||
if (t.name == name)
|
return it->text_file;
|
||||||
{
|
|
||||||
return t.text_file;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Error: TextFile no encontrado " << name << std::endl;
|
std::cerr << "Error: TextFile no encontrado " << name << std::endl;
|
||||||
throw std::runtime_error("TextFile no encontrado: " + name);
|
throw std::runtime_error("TextFile no encontrado: " + name);
|
||||||
}
|
}
|
||||||
@@ -107,13 +113,14 @@ std::shared_ptr<TextFile> Resource::getTextFile(const std::string &name)
|
|||||||
// Obtiene la animación a partir de un nombre
|
// Obtiene la animación a partir de un nombre
|
||||||
Animations &Resource::getAnimation(const std::string &name)
|
Animations &Resource::getAnimation(const std::string &name)
|
||||||
{
|
{
|
||||||
for (auto &a : animations_)
|
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](auto &a)
|
||||||
|
{ return a.name == name; });
|
||||||
|
|
||||||
|
if (it != animations_.end())
|
||||||
{
|
{
|
||||||
if (a.name == name)
|
return it->animation;
|
||||||
{
|
|
||||||
return a.animation;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cerr << "Error: Animación no encontrada " << name << std::endl;
|
std::cerr << "Error: Animación no encontrada " << name << std::endl;
|
||||||
throw std::runtime_error("Animación no encontrada: " + name);
|
throw std::runtime_error("Animación no encontrada: " + name);
|
||||||
}
|
}
|
||||||
@@ -128,19 +135,12 @@ DemoData &Resource::getDemoData(int index)
|
|||||||
void Resource::loadSounds()
|
void Resource::loadSounds()
|
||||||
{
|
{
|
||||||
std::cout << "\n>> SOUND FILES" << std::endl;
|
std::cout << "\n>> SOUND FILES" << std::endl;
|
||||||
|
|
||||||
// Obtiene la lista con las rutas a los ficheros de sonidos
|
|
||||||
auto list = Asset::get()->getListByType(AssetType::SOUND);
|
auto list = Asset::get()->getListByType(AssetType::SOUND);
|
||||||
sounds_.clear();
|
sounds_.clear();
|
||||||
|
|
||||||
for (const auto &l : list)
|
for (const auto &l : list)
|
||||||
{
|
{
|
||||||
// Encuentra el último índice de '/'
|
auto name = getFileName(l);
|
||||||
auto last_index = l.find_last_of('/') + 1;
|
|
||||||
|
|
||||||
// Obtiene la subcadena desde el último '/'
|
|
||||||
auto name = l.substr(last_index);
|
|
||||||
|
|
||||||
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
|
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
|
||||||
printWithDots("Sound : ", name, "[ LOADED ]");
|
printWithDots("Sound : ", name, "[ LOADED ]");
|
||||||
}
|
}
|
||||||
@@ -150,19 +150,12 @@ void Resource::loadSounds()
|
|||||||
void Resource::loadMusics()
|
void Resource::loadMusics()
|
||||||
{
|
{
|
||||||
std::cout << "\n>> MUSIC FILES" << std::endl;
|
std::cout << "\n>> MUSIC FILES" << std::endl;
|
||||||
|
|
||||||
// Obtiene la lista con las rutas a los ficheros musicales
|
|
||||||
auto list = Asset::get()->getListByType(AssetType::MUSIC);
|
auto list = Asset::get()->getListByType(AssetType::MUSIC);
|
||||||
musics_.clear();
|
musics_.clear();
|
||||||
|
|
||||||
for (const auto &l : list)
|
for (const auto &l : list)
|
||||||
{
|
{
|
||||||
// Encuentra el último índice de '/'
|
auto name = getFileName(l);
|
||||||
auto last_index = l.find_last_of('/') + 1;
|
|
||||||
|
|
||||||
// Obtiene la subcadena desde el último '/'
|
|
||||||
auto name = l.substr(last_index);
|
|
||||||
|
|
||||||
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
|
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
|
||||||
printWithDots("Music : ", name, "[ LOADED ]");
|
printWithDots("Music : ", name, "[ LOADED ]");
|
||||||
}
|
}
|
||||||
@@ -172,19 +165,12 @@ void Resource::loadMusics()
|
|||||||
void Resource::loadTextures()
|
void Resource::loadTextures()
|
||||||
{
|
{
|
||||||
std::cout << "\n>> TEXTURES" << std::endl;
|
std::cout << "\n>> TEXTURES" << std::endl;
|
||||||
|
|
||||||
// Obtiene la lista con las rutas a los ficheros png
|
|
||||||
auto list = Asset::get()->getListByType(AssetType::BITMAP);
|
auto list = Asset::get()->getListByType(AssetType::BITMAP);
|
||||||
textures_.clear();
|
textures_.clear();
|
||||||
|
|
||||||
for (const auto &l : list)
|
for (const auto &l : list)
|
||||||
{
|
{
|
||||||
// Encuentra el último índice de '/'
|
auto name = getFileName(l);
|
||||||
auto last_index = l.find_last_of('/') + 1;
|
|
||||||
|
|
||||||
// Obtiene la subcadena desde el último '/'
|
|
||||||
auto name = l.substr(last_index);
|
|
||||||
|
|
||||||
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
|
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,18 +179,12 @@ void Resource::loadTextures()
|
|||||||
void Resource::loadTextFiles()
|
void Resource::loadTextFiles()
|
||||||
{
|
{
|
||||||
std::cout << "\n>> TEXT FILES" << std::endl;
|
std::cout << "\n>> TEXT FILES" << std::endl;
|
||||||
// Obtiene la lista con las rutas a los ficheros png
|
|
||||||
auto list = Asset::get()->getListByType(AssetType::FONT);
|
auto list = Asset::get()->getListByType(AssetType::FONT);
|
||||||
text_files_.clear();
|
text_files_.clear();
|
||||||
|
|
||||||
for (const auto &l : list)
|
for (const auto &l : list)
|
||||||
{
|
{
|
||||||
// Encuentra el último índice de '/'
|
auto name = getFileName(l);
|
||||||
auto last_index = l.find_last_of('/') + 1;
|
|
||||||
|
|
||||||
// Obtiene la subcadena desde el último '/'
|
|
||||||
auto name = l.substr(last_index);
|
|
||||||
|
|
||||||
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
|
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -213,18 +193,12 @@ void Resource::loadTextFiles()
|
|||||||
void Resource::loadAnimations()
|
void Resource::loadAnimations()
|
||||||
{
|
{
|
||||||
std::cout << "\n>> ANIMATIONS" << std::endl;
|
std::cout << "\n>> ANIMATIONS" << std::endl;
|
||||||
// Obtiene la lista con las rutas a los ficheros ani
|
|
||||||
auto list = Asset::get()->getListByType(AssetType::ANIMATION);
|
auto list = Asset::get()->getListByType(AssetType::ANIMATION);
|
||||||
animations_.clear();
|
animations_.clear();
|
||||||
|
|
||||||
for (const auto &l : list)
|
for (const auto &l : list)
|
||||||
{
|
{
|
||||||
// Encuentra el último índice de '/'
|
auto name = getFileName(l);
|
||||||
auto last_index = l.find_last_of('/') + 1;
|
|
||||||
|
|
||||||
// Obtiene la subcadena desde el último '/'
|
|
||||||
auto name = l.substr(last_index);
|
|
||||||
|
|
||||||
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
|
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ struct ResourceAnimation
|
|||||||
Animations animation; // Objeto con las animaciones
|
Animations animation; // Objeto con las animaciones
|
||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
ResourceAnimation(const std::string &name, Animations animation)
|
ResourceAnimation(const std::string &name, const Animations &animation)
|
||||||
: name(name), animation(animation) {}
|
: name(name), animation(animation) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -37,19 +37,9 @@ Scoreboard *Scoreboard::get()
|
|||||||
// Constructor
|
// Constructor
|
||||||
Scoreboard::Scoreboard()
|
Scoreboard::Scoreboard()
|
||||||
: renderer_(Screen::get()->getRenderer()),
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
|
|
||||||
game_power_meter_texture_(Resource::get()->getTexture("game_power_meter.png")),
|
game_power_meter_texture_(Resource::get()->getTexture("game_power_meter.png")),
|
||||||
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
|
power_meter_sprite_(std::make_unique<Sprite>(game_power_meter_texture_)),
|
||||||
text_scoreboard_(std::make_unique<Text>(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt"))),
|
text_scoreboard_(std::make_unique<Text>(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt")))
|
||||||
|
|
||||||
stage_(1),
|
|
||||||
hi_score_(0),
|
|
||||||
power_(0),
|
|
||||||
hi_score_name_(std::string()),
|
|
||||||
color_({0, 0, 0}),
|
|
||||||
rect_({0, 0, 320, 40}),
|
|
||||||
ticks_(SDL_GetTicks()),
|
|
||||||
counter_(0)
|
|
||||||
{
|
{
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
|
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
|
||||||
@@ -108,7 +98,9 @@ std::string Scoreboard::updateScoreText(int num)
|
|||||||
// Actualiza el contador
|
// Actualiza el contador
|
||||||
void Scoreboard::updateCounter()
|
void Scoreboard::updateCounter()
|
||||||
{
|
{
|
||||||
if (SDL_GetTicks() - ticks_ > SCOREBOARD_TICK_SPEED_)
|
constexpr int TICKS_SPEED = 100;
|
||||||
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
counter_++;
|
counter_++;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect
|
#include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect
|
||||||
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
|
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
|
||||||
#include <SDL2/SDL_stdinc.h> // for Uint32
|
#include <SDL2/SDL_stdinc.h> // for Uint32
|
||||||
|
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
|
||||||
#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
|
||||||
@@ -41,9 +42,6 @@ struct Panel
|
|||||||
class Scoreboard
|
class Scoreboard
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Constantes
|
|
||||||
static constexpr int SCOREBOARD_TICK_SPEED_ = 100;
|
|
||||||
|
|
||||||
// [SINGLETON] Objeto scoreboard privado para Don Melitón
|
// [SINGLETON] Objeto scoreboard privado para Don Melitón
|
||||||
static Scoreboard *scoreboard_;
|
static Scoreboard *scoreboard_;
|
||||||
|
|
||||||
@@ -54,25 +52,25 @@ private:
|
|||||||
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
std::unique_ptr<Sprite> power_meter_sprite_; // Sprite para el medidor de poder de la fase
|
||||||
std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
|
std::unique_ptr<Text> text_scoreboard_; // Fuente para el marcador del juego
|
||||||
|
|
||||||
SDL_Texture *background_; // Textura para dibujar el marcador
|
SDL_Texture *background_ = nullptr; // Textura para dibujar el marcador
|
||||||
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
std::vector<SDL_Texture *> panel_texture_; // Texturas para dibujar cada panel
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
std::string name_[SCOREBOARD_MAX_PANELS]; // Nom de cada jugador
|
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador
|
||||||
std::string record_name_[SCOREBOARD_MAX_PANELS]; // Nombre introducido para la tabla de records
|
std::string record_name_[SCOREBOARD_MAX_PANELS] = {}; // Nombre introducido para la tabla de records
|
||||||
int selector_pos_[SCOREBOARD_MAX_PANELS]; // Posición del selector de letra para introducir el nombre
|
int selector_pos_[SCOREBOARD_MAX_PANELS] = {}; // Posición del selector de letra para introducir el nombre
|
||||||
int score_[SCOREBOARD_MAX_PANELS]; // Puntuación de los jugadores
|
int score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
|
||||||
float mult_[SCOREBOARD_MAX_PANELS]; // Multiplicador de los jugadores
|
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador de los jugadores
|
||||||
int continue_counter_[SCOREBOARD_MAX_PANELS]; // Tiempo para continuar de los jugadores
|
int continue_counter_[SCOREBOARD_MAX_PANELS] = {}; // Tiempo para continuar de los jugadores
|
||||||
Panel panel_[SCOREBOARD_MAX_PANELS]; // Lista con todos los paneles del marcador
|
Panel panel_[SCOREBOARD_MAX_PANELS] = {}; // Lista con todos los paneles del marcador
|
||||||
int stage_; // Número de fase actual
|
int stage_ = 1; // Número de fase actual
|
||||||
int hi_score_; // Máxima puntuación
|
int hi_score_ = 0; // Máxima puntuación
|
||||||
float power_; // Poder actual de la fase
|
float power_ = 0; // Poder actual de la fase
|
||||||
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
|
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
|
||||||
Color color_; // Color del marcador
|
Color color_ = Color(); // Color del marcador
|
||||||
SDL_Rect rect_; // Posición y dimensiones del marcador
|
SDL_Rect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||||
Uint32 ticks_; // Variable donde almacenar el valor de SDL_GetTiks()
|
Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
|
||||||
int counter_; // Contador
|
int counter_ = 0; // Contador
|
||||||
|
|
||||||
// Puntos predefinidos para colocar elementos en los paneles
|
// Puntos predefinidos para colocar elementos en los paneles
|
||||||
SDL_Point slot4_1_, slot4_2_, slot4_3_, slot4_4_;
|
SDL_Point slot4_1_, slot4_2_, slot4_3_, slot4_4_;
|
||||||
|
|||||||
@@ -51,23 +51,13 @@ Screen::Screen(SDL_Window *window, SDL_Renderer *renderer)
|
|||||||
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)),
|
||||||
|
|
||||||
src_rect_({0, 0, param.game.width, param.game.height}),
|
src_rect_({0, 0, param.game.width, param.game.height}),
|
||||||
dst_rect_({0, 0, param.game.width, param.game.height}),
|
dst_rect_({0, 0, param.game.width, param.game.height})
|
||||||
border_color_({0x00, 0x00, 0x00}),
|
|
||||||
attenuate_effect_(false),
|
|
||||||
fps_ticks_(0),
|
|
||||||
fps_counter_(0),
|
|
||||||
fps_(0),
|
|
||||||
#ifdef DEBUG
|
|
||||||
show_info_(true)
|
|
||||||
#else
|
|
||||||
show_info_(false)
|
|
||||||
#endif
|
|
||||||
{
|
{
|
||||||
// Inicializa variables
|
// Inicializa variables
|
||||||
flash_effect_.enabled = false;
|
flash_effect_.enabled = false;
|
||||||
flash_effect_.counter = 0;
|
flash_effect_.counter = 0;
|
||||||
flash_effect_.lenght = 0;
|
flash_effect_.lenght = 0;
|
||||||
flash_effect_.color = {0xFF, 0xFF, 0xFF};
|
flash_effect_.color = Color(0xFF, 0xFF, 0xFF);
|
||||||
shake_effect_.enabled = false;
|
shake_effect_.enabled = false;
|
||||||
shake_effect_.desp = 2;
|
shake_effect_.desp = 2;
|
||||||
shake_effect_.delay = 3;
|
shake_effect_.delay = 3;
|
||||||
@@ -480,7 +470,9 @@ void Screen::displayInfo()
|
|||||||
// Resolution
|
// Resolution
|
||||||
dbg_print(0, 0, info_resolution_.c_str(), 255, 255, 0);
|
dbg_print(0, 0, info_resolution_.c_str(), 255, 255, 0);
|
||||||
|
|
||||||
dbg_print(0, 8, std::to_string(globalInputs::service_pressed_counter[0]).c_str(), 255, 255, 0);
|
// Contador de service_pressed_counter
|
||||||
|
if (const int counter = globalInputs::service_pressed_counter[0]; counter > 0)
|
||||||
|
dbg_print(0, 8, std::to_string(counter).c_str(), 255, 0, 255);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,15 +34,19 @@ private:
|
|||||||
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
|
||||||
SDL_Rect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
|
SDL_Rect dst_rect_; // Coordenadas donde se va a dibujar la textura del juego sobre la pantalla o ventana
|
||||||
Color border_color_; // Color del borde añadido a la textura de juego para rellenar la pantalla
|
Color border_color_ = Color(); // Color del borde añadido a la textura de juego para rellenar la pantalla
|
||||||
bool attenuate_effect_; // Indica si la pantalla ha de estar atenuada
|
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||||
Uint32 fps_ticks_; // Ticks para contar los frames por segundo
|
Uint32 fps_ticks_ = 0; // Ticks para contar los frames por segundo
|
||||||
int fps_counter_; // Contador de frames por segundo
|
int fps_counter_ = 0; // Contador de frames por segundo
|
||||||
int fps_; // Frames calculados en el último segundo
|
int fps_; // Frames calculados en el último segundo
|
||||||
bool show_info_; // Indica si ha de mostrar/ocultar la información de la pantalla
|
std::string info_resolution_; // Texto con la informacion de la pantalla
|
||||||
std::string info_resolution_; // Texto con la informacion de la pantalla
|
#ifdef DEBUG
|
||||||
|
bool show_info_ = true; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||||
|
#else
|
||||||
|
bool show_info_ = false; // Indica si ha de mostrar/ocultar la información de la pantalla
|
||||||
|
#endif
|
||||||
|
|
||||||
struct FlashEffect
|
struct FlashEffect
|
||||||
{
|
{
|
||||||
@@ -111,7 +115,7 @@ public:
|
|||||||
void checkInput();
|
void checkInput();
|
||||||
|
|
||||||
// Limpia la pantalla
|
// Limpia la pantalla
|
||||||
void clean(Color color = {0x00, 0x00, 0x00});
|
void clean(Color color = Color(0x00, 0x00, 0x00));
|
||||||
|
|
||||||
// Prepara para empezar a dibujar en la textura de juego
|
// Prepara para empezar a dibujar en la textura de juego
|
||||||
void start();
|
void start();
|
||||||
|
|||||||
@@ -3,20 +3,7 @@ class Texture;
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
SmartSprite::SmartSprite(std::shared_ptr<Texture> texture)
|
SmartSprite::SmartSprite(std::shared_ptr<Texture> texture)
|
||||||
: AnimatedSprite(texture)
|
: AnimatedSprite(texture) {}
|
||||||
{
|
|
||||||
init();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inicializa el objeto
|
|
||||||
void SmartSprite::init()
|
|
||||||
{
|
|
||||||
finished_counter_ = 0;
|
|
||||||
on_destination_ = false;
|
|
||||||
dest_x_ = dest_y_ = 0;
|
|
||||||
finished_ = false;
|
|
||||||
enabled_ = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||||
void SmartSprite::update()
|
void SmartSprite::update()
|
||||||
|
|||||||
@@ -9,12 +9,12 @@ class SmartSprite : public AnimatedSprite
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Variables
|
// Variables
|
||||||
bool on_destination_; // Indica si está en el destino
|
bool on_destination_ = false; // Indica si está en el destino
|
||||||
int dest_x_; // Posicion de destino en el eje X
|
int dest_x_ = 0; // Posicion de destino en el eje X
|
||||||
int dest_y_; // Posicion de destino en el eje Y
|
int dest_y_ = 0; // Posicion de destino en el eje Y
|
||||||
int finished_counter_; // Contador para deshabilitarlo
|
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||||
bool finished_; // Indica si ya ha terminado
|
bool finished_ = false; // Indica si ya ha terminado
|
||||||
bool enabled_; // Indica si el objeto está habilitado
|
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||||
|
|
||||||
// Comprueba si ha terminado
|
// Comprueba si ha terminado
|
||||||
void checkFinished();
|
void checkFinished();
|
||||||
@@ -29,9 +29,6 @@ public:
|
|||||||
// Destructor
|
// Destructor
|
||||||
~SmartSprite() = default;
|
~SmartSprite() = default;
|
||||||
|
|
||||||
// Inicializa el objeto
|
|
||||||
void init();
|
|
||||||
|
|
||||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||||
void update() override;
|
void update() override;
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Abre el fichero para leer los valores
|
// Abre el fichero para leer los valores
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1).c_str();
|
|
||||||
std::ifstream file(file_path);
|
std::ifstream file(file_path);
|
||||||
|
|
||||||
if (file.is_open() && file.good())
|
if (file.is_open() && file.good())
|
||||||
@@ -56,15 +55,15 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
printWithDots("Text File : ", file_name, "[ LOADED ]");
|
printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]");
|
||||||
file.close();
|
file.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// El fichero no se puede abrir
|
// El fichero no se puede abrir
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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
|
||||||
|
|||||||
@@ -33,13 +33,13 @@ class Text
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
std::unique_ptr<Sprite> sprite_; // Objeto con los graficos para el texto
|
std::unique_ptr<Sprite> sprite_ = nullptr; // Objeto con los graficos para el texto
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int box_width_; // Anchura de la caja de cada caracter en el png
|
int box_width_ = 0; // Anchura de la caja de cada caracter en el png
|
||||||
int box_height_; // Altura de la caja de cada caracter en el png
|
int box_height_ = 0; // Altura de la caja de cada caracter en el png
|
||||||
bool fixed_width_; // Indica si el texto se ha de escribir con longitud fija en todas las letras
|
bool fixed_width_ = false; // Indica si el texto se ha de escribir con longitud fija en todas las letras
|
||||||
TextOffset offset_[128]; // Vector con las posiciones y ancho de cada letra
|
TextOffset offset_[128] = {}; // Vector con las posiciones y ancho de cada letra
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
|
|||||||
@@ -15,13 +15,8 @@
|
|||||||
|
|
||||||
// Constructor
|
// Constructor
|
||||||
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
||||||
: texture_(nullptr),
|
: renderer_(renderer),
|
||||||
renderer_(renderer),
|
path_(path)
|
||||||
surface_(nullptr),
|
|
||||||
width_(0),
|
|
||||||
height_(0),
|
|
||||||
path_(path),
|
|
||||||
current_palette_(0)
|
|
||||||
{
|
{
|
||||||
// Carga el fichero en la textura
|
// Carga el fichero en la textura
|
||||||
if (!path_.empty())
|
if (!path_.empty())
|
||||||
@@ -40,10 +35,10 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
|||||||
{
|
{
|
||||||
// Crea la surface desde un fichero
|
// Crea la surface desde un fichero
|
||||||
surface_ = loadSurface(path_);
|
surface_ = loadSurface(path_);
|
||||||
|
|
||||||
// Añade la propia paleta del fichero a la lista
|
// Añade la propia paleta del fichero a la lista
|
||||||
addPaletteFromFile(path_);
|
addPaletteFromFile(path_);
|
||||||
//setPaletteColor(0, 0, 0x00000000);
|
// setPaletteColor(0, 0, 0x00000000);
|
||||||
|
|
||||||
// Crea la textura, establece el BlendMode y copia la surface a la textura
|
// Crea la textura, establece el BlendMode y copia la surface a la textura
|
||||||
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
|
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
|
||||||
@@ -69,13 +64,12 @@ bool Texture::loadFromFile(const std::string &file_path)
|
|||||||
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
unsigned char *data = stbi_load(file_path.c_str(), &width, &height, &orig_format, req_format);
|
||||||
if (!data)
|
if (!data)
|
||||||
{
|
{
|
||||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||||
printWithDots("Image : ", file_name, "[ LOADED ]");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int depth, pitch;
|
int depth, pitch;
|
||||||
@@ -320,13 +314,12 @@ std::vector<Uint32> Texture::loadPaletteFromFile(const std::string &file_path)
|
|||||||
FILE *f = fopen(file_path.c_str(), "rb");
|
FILE *f = fopen(file_path.c_str(), "rb");
|
||||||
if (!f)
|
if (!f)
|
||||||
{
|
{
|
||||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||||
printWithDots("Image : ", file_name, "[ LOADED ]");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fseek(f, 0, SEEK_END);
|
fseek(f, 0, SEEK_END);
|
||||||
|
|||||||
@@ -24,16 +24,16 @@ class Texture
|
|||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
SDL_Texture *texture_; // La textura
|
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
SDL_Texture *texture_ = nullptr; // La textura
|
||||||
std::shared_ptr<Surface> surface_; // Surface para usar imagenes en formato gif con paleta
|
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imagenes en formato gif con paleta
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int width_; // Ancho de la imagen
|
|
||||||
int height_; // Alto de la imagen
|
|
||||||
std::string path_; // Ruta de la imagen de la textura
|
std::string path_; // Ruta de la imagen de la textura
|
||||||
|
int width_ = 0; // Ancho de la imagen
|
||||||
|
int height_ = 0; // Alto de la imagen
|
||||||
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
|
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
|
||||||
int current_palette_; // Indice de la paleta en uso
|
int current_palette_ = 0; // Indice de la paleta en uso
|
||||||
|
|
||||||
// Crea una surface desde un fichero .gif
|
// Crea una surface desde un fichero .gif
|
||||||
std::shared_ptr<Surface> loadSurface(const std::string &file_name);
|
std::shared_ptr<Surface> loadSurface(const std::string &file_name);
|
||||||
|
|||||||
@@ -12,7 +12,9 @@
|
|||||||
TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
||||||
: renderer_(Screen::get()->getRenderer()),
|
: renderer_(Screen::get()->getRenderer()),
|
||||||
pos_(pos),
|
pos_(pos),
|
||||||
counter_(0),
|
// Coloca la ventana que recorre el mosaico de fondo de manera que coincida
|
||||||
|
// con el mosaico que hay pintado en el titulo al iniciar
|
||||||
|
window_({128, 96, pos_.w, pos_.h}),
|
||||||
mode_(mode == TiledBGMode::RANDOM ? static_cast<TiledBGMode>(rand() % 2) : mode)
|
mode_(mode == TiledBGMode::RANDOM ? static_cast<TiledBGMode>(rand() % 2) : mode)
|
||||||
{
|
{
|
||||||
// Crea la textura para el mosaico de fondo
|
// Crea la textura para el mosaico de fondo
|
||||||
@@ -21,10 +23,6 @@ TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
|||||||
// Rellena la textura con el contenido
|
// Rellena la textura con el contenido
|
||||||
fillTexture();
|
fillTexture();
|
||||||
|
|
||||||
// Coloca la ventana que recorre el mosaico de fondo de manera que coincida
|
|
||||||
// con el mosaico que hay pintado en el titulo al iniciar
|
|
||||||
window_ = {128, 96, pos_.w, pos_.h};
|
|
||||||
|
|
||||||
// Inicializa los valores del vector con los valores del seno
|
// Inicializa los valores del vector con los valores del seno
|
||||||
for (int i = 0; i < 360; ++i)
|
for (int i = 0; i < 360; ++i)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -29,12 +29,12 @@ private:
|
|||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||||
SDL_Rect window_; // Ventana visible para la textura de fondo del titulo
|
|
||||||
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
SDL_Texture *canvas_; // Textura donde dibujar el fondo formado por tiles
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
SDL_Rect pos_; // Posición y tamaño del mosaico
|
SDL_Rect pos_; // Posición y tamaño del mosaico
|
||||||
int counter_; // Contador
|
SDL_Rect window_; // Ventana visible para la textura de fondo del titulo
|
||||||
|
int counter_ = 0; // Contador
|
||||||
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
TiledBGMode mode_; // Tipo de movimiento del mosaico
|
||||||
double sin_[360]; // Vector con los valores del seno precalculados
|
double sin_[360]; // Vector con los valores del seno precalculados
|
||||||
|
|
||||||
|
|||||||
@@ -32,11 +32,6 @@ Title::Title()
|
|||||||
mini_logo_texture_(Resource::get()->getTexture("logo_jailgames_mini.png")),
|
mini_logo_texture_(Resource::get()->getTexture("logo_jailgames_mini.png")),
|
||||||
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())),
|
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())),
|
||||||
define_buttons_(std::make_unique<DefineButtons>(std::move(text2_))),
|
define_buttons_(std::make_unique<DefineButtons>(std::move(text2_))),
|
||||||
counter_(0),
|
|
||||||
ticks_(0),
|
|
||||||
demo_(true),
|
|
||||||
next_section_(section::Name::GAME),
|
|
||||||
post_fade_(0),
|
|
||||||
num_controllers_(Input::get()->getNumControllers())
|
num_controllers_(Input::get()->getNumControllers())
|
||||||
{
|
{
|
||||||
// Configura objetos
|
// Configura objetos
|
||||||
@@ -59,8 +54,9 @@ Title::~Title()
|
|||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void Title::update()
|
void Title::update()
|
||||||
{
|
{
|
||||||
// Calcula la lógica de los objetos
|
constexpr int TICKS_SPEED = 15;
|
||||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
|
||||||
|
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||||
{
|
{
|
||||||
// Actualiza el contador de ticks_
|
// Actualiza el contador de ticks_
|
||||||
ticks_ = SDL_GetTicks();
|
ticks_ = SDL_GetTicks();
|
||||||
@@ -138,7 +134,7 @@ void Title::render()
|
|||||||
|
|
||||||
if (section::options == section::Options::TITLE_2)
|
if (section::options == section::Options::TITLE_2)
|
||||||
{
|
{
|
||||||
constexpr Color shadow = {0x14, 0x87, 0xc4};
|
constexpr Color shadow = Color(0x14, 0x87, 0xc4);
|
||||||
|
|
||||||
// 'PRESS TO PLAY'
|
// 'PRESS TO PLAY'
|
||||||
if (counter_ % 50 > 14 && !define_buttons_->isEnabled())
|
if (counter_ % 50 > 14 && !define_buttons_->isEnabled())
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
#include "text.h" // for Text
|
#include "text.h" // for Text
|
||||||
#include "tiled_bg.h" // for TiledBG
|
#include "tiled_bg.h" // for TiledBG
|
||||||
class Input; // lines 17-17
|
class Input; // lines 17-17
|
||||||
|
#include "section.h" // for Options, options, Name, name
|
||||||
class Screen; // lines 18-18
|
class Screen; // lines 18-18
|
||||||
class Texture; // lines 20-20
|
class Texture; // lines 20-20
|
||||||
namespace section
|
namespace section
|
||||||
@@ -42,27 +43,23 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = true;
|
|||||||
class Title
|
class Title
|
||||||
{
|
{
|
||||||
private:
|
private:
|
||||||
// Constantes
|
|
||||||
static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa
|
|
||||||
|
|
||||||
// Objetos y punteros
|
// Objetos y punteros
|
||||||
std::unique_ptr<Text> text1_; // Objeto de texto para poder escribir textos en pantalla
|
std::unique_ptr<Text> text1_; // Objeto de texto para poder escribir textos en pantalla
|
||||||
std::unique_ptr<Text> text2_; // Objeto de texto para poder escribir textos en pantalla
|
std::unique_ptr<Text> text2_; // Objeto de texto para poder escribir textos en pantalla
|
||||||
std::unique_ptr<Fade> fade_; // Objeto para realizar fundidos en pantalla
|
std::unique_ptr<Fade> fade_; // Objeto para realizar fundidos en pantalla
|
||||||
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
std::unique_ptr<TiledBG> tiled_bg_; // Objeto para dibujar el mosaico animado de fondo
|
||||||
std::unique_ptr<GameLogo> game_logo_; // Objeto para dibujar el logo con el título del juego
|
std::unique_ptr<GameLogo> game_logo_; // Objeto para dibujar el logo con el título del juego
|
||||||
std::shared_ptr<Texture> mini_logo_texture_; // Textura con el logo de JailGames mini
|
std::shared_ptr<Texture> mini_logo_texture_; // Textura con el logo de JailGames mini
|
||||||
std::unique_ptr<Sprite> mini_logo_sprite_; // Sprite con el logo de JailGames mini
|
std::unique_ptr<Sprite> mini_logo_sprite_; // Sprite con el logo de JailGames mini
|
||||||
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
|
std::unique_ptr<DefineButtons> define_buttons_; // Objeto para definir los botones del joystic
|
||||||
|
|
||||||
|
|
||||||
// Variable
|
// Variable
|
||||||
int counter_; // Temporizador para la pantalla de titulo
|
int counter_ = 0; // Temporizador para la pantalla de titulo
|
||||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||||
bool demo_; // Indica si el modo demo estará activo
|
bool demo_ = true; // Indica si el modo demo estará activo
|
||||||
section::Name next_section_; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
|
section::Name next_section_ = section::Name::GAME; // Indica cual es la siguiente sección a cargar cuando termine el contador del titulo
|
||||||
int post_fade_; // Opción a realizar cuando termina el fundido
|
int post_fade_ = 0; // Opción a realizar cuando termina el fundido
|
||||||
int num_controllers_; // Número de mandos conectados
|
int num_controllers_; // Número de mandos conectados
|
||||||
|
|
||||||
// Actualiza las variables del objeto
|
// Actualiza las variables del objeto
|
||||||
void update();
|
void update();
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
#include <filesystem>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <algorithm> // for min, clamp, find_if_not, transform
|
#include <algorithm> // for min, clamp, find_if_not, transform
|
||||||
@@ -8,18 +9,20 @@
|
|||||||
struct JA_Music_t; // lines 7-7
|
struct JA_Music_t; // lines 7-7
|
||||||
struct JA_Sound_t; // lines 8-8
|
struct JA_Sound_t; // lines 8-8
|
||||||
|
|
||||||
|
// Variables
|
||||||
|
Overrides overrides = Overrides();
|
||||||
|
|
||||||
// Colores
|
// Colores
|
||||||
const Color bg_color = {0x27, 0x27, 0x36};
|
const Color bg_color = Color(0x27, 0x27, 0x36);
|
||||||
const Color no_color = {0xFF, 0xFF, 0xFF};
|
const Color no_color = Color(0xFF, 0xFF, 0xFF);
|
||||||
const Color shdw_txt_color = {0x43, 0x43, 0x4F};
|
const Color shdw_txt_color = Color(0x43, 0x43, 0x4F);
|
||||||
const Color separator_color = {0x0D, 0x1A, 0x2B};
|
const Color separator_color = Color(0x0D, 0x1A, 0x2B);
|
||||||
const Color scoreboard_color = {0x2E, 0x3F, 0x47};
|
const Color scoreboard_easy_color = Color(0x4B, 0x69, 0x2F);
|
||||||
const Color difficulty_easy_color = {0x4B, 0x69, 0x2F};
|
const Color scoreboard_normal_color = Color(0x2E, 0x3F, 0x47);
|
||||||
const Color difficulty_normal_color = {0xFF, 0x7A, 0x00};
|
const Color scoreboard_hard_color = Color(0x76, 0x42, 0x8A);
|
||||||
const Color difficulty_hard_color = {0x76, 0x42, 0x8A};
|
const Color flash_color = Color(0xFF, 0xFF, 0xFF);
|
||||||
const Color flash_color = {0xFF, 0xFF, 0xFF};
|
const Color fade_color = Color(0x27, 0x27, 0x36);
|
||||||
const Color fade_color = {0x27, 0x27, 0x36};
|
const Color orange_color = Color(0xFF, 0x7A, 0x00);
|
||||||
const Color orange_color = {0xFF, 0x7A, 0x00};
|
|
||||||
|
|
||||||
// Calcula el cuadrado de la distancia entre dos puntos
|
// Calcula el cuadrado de la distancia entre dos puntos
|
||||||
double distanceSquared(int x1, int y1, int x2, int y2)
|
double distanceSquared(int x1, int y1, int x2, int y2)
|
||||||
@@ -218,8 +221,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]");
|
||||||
printWithDots("DemoData : ", file_name, "[ LOADED ]");
|
|
||||||
|
|
||||||
// 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)
|
||||||
@@ -241,7 +243,6 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
|
|||||||
bool saveDemoFile(const std::string &file_path, const DemoData &dd)
|
bool saveDemoFile(const std::string &file_path, const DemoData &dd)
|
||||||
{
|
{
|
||||||
auto success = true;
|
auto success = true;
|
||||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
|
||||||
auto file = SDL_RWFromFile(file_path.c_str(), "w+b");
|
auto file = SDL_RWFromFile(file_path.c_str(), "w+b");
|
||||||
|
|
||||||
if (file)
|
if (file)
|
||||||
@@ -251,24 +252,37 @@ bool saveDemoFile(const std::string &file_path, const DemoData &dd)
|
|||||||
{
|
{
|
||||||
if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1)
|
if (SDL_RWwrite(file, &data, sizeof(DemoKeys), 1) != 1)
|
||||||
{
|
{
|
||||||
std::cerr << "Error al escribir el fichero " << file_name << std::endl;
|
std::cerr << "Error al escribir el fichero " << getFileName(file_path) << std::endl;
|
||||||
success = false;
|
success = false;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (success)
|
if (success)
|
||||||
{
|
{
|
||||||
std::cout << "Writing file " << file_name.c_str() << std::endl;
|
std::cout << "Writing file " << getFileName(file_path).c_str() << std::endl;
|
||||||
}
|
}
|
||||||
// Cierra el fichero
|
// Cierra el fichero
|
||||||
SDL_RWclose(file);
|
SDL_RWclose(file);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
std::cout << "Error: Unable to save " << file_name.c_str() << " file! " << SDL_GetError() << std::endl;
|
std::cout << "Error: Unable to save " << getFileName(file_path).c_str() << " file! " << SDL_GetError() << std::endl;
|
||||||
success = false;
|
success = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
#endif // RECORDING
|
#endif // RECORDING
|
||||||
|
|
||||||
|
// Obtiene el nombre de un fichero a partir de una ruta completa
|
||||||
|
std::string getFileName(const std::string &path)
|
||||||
|
{
|
||||||
|
return std::filesystem::path(path).filename().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtiene la ruta eliminando el nombre del fichero
|
||||||
|
std::string getPath(const std::string &full_path)
|
||||||
|
{
|
||||||
|
std::filesystem::path path(full_path);
|
||||||
|
return path.parent_path().string();
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,17 +29,39 @@ enum class GameDifficulty
|
|||||||
HARD = 2,
|
HARD = 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Variables para que los argumentos del programa tengan mas peso que los definidos en otros lugares
|
||||||
|
struct Overrides
|
||||||
|
{
|
||||||
|
std::string param_file; // Fichero de parametros a utilizar
|
||||||
|
bool clear_hi_score_table; // Reinicia la tabla de records
|
||||||
|
bool set_v_sync; // Establece el vsync
|
||||||
|
|
||||||
|
// Constructor por defecto
|
||||||
|
Overrides()
|
||||||
|
: param_file(""), clear_hi_score_table(false), set_v_sync(false) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
extern Overrides overrides;
|
||||||
|
|
||||||
// Estructura para definir un circulo
|
// Estructura para definir un circulo
|
||||||
struct Circle
|
struct Circle
|
||||||
{
|
{
|
||||||
int x, y, r;
|
int x, y, r;
|
||||||
|
|
||||||
|
// Constructor por defecto
|
||||||
|
Circle() : x(0), y(0), r(0) {}
|
||||||
|
|
||||||
|
// Constructor
|
||||||
|
Circle(int xCoord, int yCoord, int radius)
|
||||||
|
: x(xCoord), y(yCoord), r(radius) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para definir un color
|
// Estructura para definir un color
|
||||||
struct Color
|
struct Color
|
||||||
{
|
{
|
||||||
Uint8 r, g, b;
|
Uint8 r, g, b;
|
||||||
constexpr Color(int red = 255, int green = 255, int blue = 255) : r(red), g(green), b(blue) {}
|
constexpr Color() : r(0), g(0), b(0) {}
|
||||||
|
explicit constexpr Color(int red, int green, int blue) : r(red), g(green), b(blue) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Posiciones de las notificaciones
|
// Posiciones de las notificaciones
|
||||||
@@ -57,6 +79,10 @@ struct HiScoreEntry
|
|||||||
{
|
{
|
||||||
std::string name; // Nombre
|
std::string name; // Nombre
|
||||||
int score; // Puntuación
|
int score; // Puntuación
|
||||||
|
|
||||||
|
// Constructor
|
||||||
|
explicit HiScoreEntry(const std::string &n = "", int s = 0)
|
||||||
|
: name(n), score(s) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
struct DemoKeys
|
struct DemoKeys
|
||||||
@@ -69,7 +95,7 @@ struct DemoKeys
|
|||||||
Uint8 fire_right;
|
Uint8 fire_right;
|
||||||
|
|
||||||
// Constructor que inicializa todos los campos
|
// Constructor que inicializa todos los campos
|
||||||
DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
|
explicit DemoKeys(Uint8 l = 0, Uint8 r = 0, Uint8 ni = 0, Uint8 f = 0, Uint8 fl = 0, Uint8 fr = 0)
|
||||||
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
|
: left(l), right(r), no_input(ni), fire(f), fire_left(fl), fire_right(fr) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,6 +108,14 @@ struct Demo
|
|||||||
int counter; // Contador para el modo demo
|
int counter; // Contador para el modo demo
|
||||||
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
|
DemoKeys keys; // Variable con las pulsaciones de teclas del modo demo
|
||||||
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
|
std::vector<DemoData> data; // Vector con diferentes sets de datos con los movimientos para la demo
|
||||||
|
|
||||||
|
// Constructor por defecto
|
||||||
|
Demo()
|
||||||
|
: enabled(false), recording(false), counter(0), keys(), data() {}
|
||||||
|
|
||||||
|
// Constructor con parámetros
|
||||||
|
Demo(bool e, bool r, int c, const DemoKeys &k, const std::vector<DemoData> &d)
|
||||||
|
: enabled(e), recording(r), counter(c), keys(k), data(d) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para las opciones de la ventana
|
// Estructura para las opciones de la ventana
|
||||||
@@ -289,15 +323,20 @@ DemoData loadDemoDataFromFile(const std::string &file_path);
|
|||||||
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
|
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Obtiene el nombre de un fichero a partir de una ruta
|
||||||
|
std::string getFileName(const std::string &path);
|
||||||
|
|
||||||
|
// Obtiene la ruta eliminando el nombre del fichero
|
||||||
|
std::string getPath(const std::string &full_path);
|
||||||
|
|
||||||
// Colores
|
// Colores
|
||||||
extern const Color bg_color;
|
extern const Color bg_color;
|
||||||
extern const Color no_color;
|
extern const Color no_color;
|
||||||
extern const Color shdw_txt_color;
|
extern const Color shdw_txt_color;
|
||||||
extern const Color separator_color;
|
extern const Color separator_color;
|
||||||
extern const Color scoreboard_color;
|
extern const Color scoreboard_easy_color;
|
||||||
extern const Color difficulty_easy_color;
|
extern const Color scoreboard_normal_color;
|
||||||
extern const Color difficulty_normal_color;
|
extern const Color scoreboard_hard_color;
|
||||||
extern const Color difficulty_hard_color;
|
|
||||||
extern const Color flash_color;
|
extern const Color flash_color;
|
||||||
extern const Color fade_color;
|
extern const Color fade_color;
|
||||||
extern const Color orange_color;
|
extern const Color orange_color;
|
||||||
@@ -1,22 +1,6 @@
|
|||||||
#include "writer.h"
|
#include "writer.h"
|
||||||
#include "text.h" // for Text
|
#include "text.h" // for Text
|
||||||
|
|
||||||
// Constructor
|
|
||||||
Writer::Writer(std::shared_ptr<Text> text)
|
|
||||||
: text_(text),
|
|
||||||
pos_x_(0),
|
|
||||||
pos_y_(0),
|
|
||||||
kerning_(0),
|
|
||||||
caption_(std::string()),
|
|
||||||
speed_(0),
|
|
||||||
writing_counter_(0),
|
|
||||||
index_(0),
|
|
||||||
lenght_(0),
|
|
||||||
completed_(false),
|
|
||||||
enabled_(false),
|
|
||||||
enabled_counter_(0),
|
|
||||||
finished_(false) {}
|
|
||||||
|
|
||||||
// Actualiza el objeto
|
// Actualiza el objeto
|
||||||
void Writer::update()
|
void Writer::update()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <memory> // for shared_ptr
|
#include <memory> // for shared_ptr
|
||||||
#include <string> // for string
|
#include <string> // for string
|
||||||
class Text;
|
class Text;
|
||||||
|
|
||||||
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
|
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un objeto Text
|
||||||
@@ -12,22 +12,23 @@ private:
|
|||||||
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
|
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
|
||||||
|
|
||||||
// Variables
|
// Variables
|
||||||
int pos_x_; // Posicion en el eje X donde empezar a escribir el texto
|
int pos_x_ = 0; // Posicion en el eje X donde empezar a escribir el texto
|
||||||
int pos_y_; // Posicion en el eje Y donde empezar a escribir el texto
|
int pos_y_ = 0; // Posicion en el eje Y donde empezar a escribir el texto
|
||||||
int kerning_; // Kerning del texto, es decir, espaciado entre caracteres
|
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
|
||||||
std::string caption_; // El texto para escribir
|
std::string caption_ = std::string(); // El texto para escribir
|
||||||
int speed_; // Velocidad de escritura
|
int speed_ = 0; // Velocidad de escritura
|
||||||
int writing_counter_; // Temporizador de escritura para cada caracter
|
int writing_counter_ = 0; // Temporizador de escritura para cada caracter
|
||||||
int index_; // Posición del texto que se está escribiendo
|
int index_ = 0; // Posición del texto que se está escribiendo
|
||||||
int lenght_; // Longitud de la cadena a escribir
|
int lenght_ = 0; // Longitud de la cadena a escribir
|
||||||
bool completed_; // Indica si se ha escrito todo el texto
|
bool completed_ = false; // Indica si se ha escrito todo el texto
|
||||||
bool enabled_; // Indica si el objeto está habilitado
|
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||||
int enabled_counter_; // Temporizador para deshabilitar el objeto
|
int enabled_counter_ = 0; // Temporizador para deshabilitar el objeto
|
||||||
bool finished_; // Indica si ya ha terminado
|
bool finished_ = false; // Indica si ya ha terminado
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Constructor
|
// Constructor
|
||||||
explicit Writer(std::shared_ptr<Text> text);
|
explicit Writer(std::shared_ptr<Text> text)
|
||||||
|
: text_(text) {}
|
||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
~Writer() = default;
|
~Writer() = default;
|
||||||
|
|||||||