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.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.game_text.dest_y
|
||||
|
||||
## FADE
|
||||
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),
|
||||
current_animation_(0) {}
|
||||
|
||||
// Destructor
|
||||
AnimatedSprite::~AnimatedSprite()
|
||||
{
|
||||
animations_.clear();
|
||||
}
|
||||
|
||||
// Obtiene el indice de la animación a partir del nombre
|
||||
int AnimatedSprite::getIndex(const std::string &name)
|
||||
{
|
||||
@@ -260,12 +254,9 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
||||
{
|
||||
// Inicializa variables
|
||||
std::vector<Animation> animations;
|
||||
auto frames_per_row = 0;
|
||||
auto frame_width = 0;
|
||||
auto frame_height = 0;
|
||||
auto max_tiles = 0;
|
||||
auto frame_width = 1;
|
||||
auto frame_height = 1;
|
||||
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
std::ifstream file(file_path);
|
||||
std::string line;
|
||||
|
||||
@@ -273,9 +264,11 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
||||
if (file.good())
|
||||
{
|
||||
// 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))
|
||||
{
|
||||
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
|
||||
if (line == "[animation]")
|
||||
{
|
||||
@@ -324,7 +317,7 @@ std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path
|
||||
|
||||
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]");
|
||||
@@ -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
|
||||
else
|
||||
if (line != "[animation]")
|
||||
{
|
||||
// Encuentra la posición del caracter '='
|
||||
int pos = line.find("=");
|
||||
size_t pos = line.find("=");
|
||||
|
||||
// Procesa las dos subcadenas
|
||||
if (pos != (int)line.npos)
|
||||
if (pos != line.npos)
|
||||
{
|
||||
if (line.substr(0, pos) == "frames_per_row")
|
||||
{
|
||||
frames_per_row = std::stoi(line.substr(pos + 1, line.length()));
|
||||
}
|
||||
|
||||
else if (line.substr(0, pos) == "frame_width")
|
||||
if (line.substr(0, pos) == "frame_width")
|
||||
{
|
||||
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
|
||||
{
|
||||
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
|
||||
if (frames_per_row == 0 && frame_width > 0)
|
||||
{
|
||||
frames_per_row = texture_->getWidth() / frame_width;
|
||||
}
|
||||
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;
|
||||
max_tiles = w * h;
|
||||
}
|
||||
const auto w = texture_->getWidth() / frame_width;
|
||||
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
|
||||
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
|
||||
|
||||
@@ -49,7 +49,7 @@ public:
|
||||
explicit AnimatedSprite(std::shared_ptr<Texture> texture);
|
||||
|
||||
// Destructor
|
||||
virtual ~AnimatedSprite();
|
||||
virtual ~AnimatedSprite() = default;
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void update() override;
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include <SDL2/SDL_stdinc.h> // for SDL_max
|
||||
#include <stddef.h> // for size_t
|
||||
#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
|
||||
Asset *Asset::asset_ = nullptr;
|
||||
@@ -26,35 +28,19 @@ Asset *Asset::get()
|
||||
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
|
||||
void Asset::add(const std::string &file, AssetType type, bool required, bool absolute)
|
||||
{
|
||||
AssetItem ai;
|
||||
ai.file = absolute ? file : executable_path_ + file;
|
||||
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());
|
||||
file_list_.emplace_back(absolute ? file : executable_path_ + file, type, required);
|
||||
longest_name_ = std::max(longest_name_, static_cast<int>(file_list_.back().file.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
|
||||
{
|
||||
for (const auto &f : file_list_)
|
||||
{
|
||||
const size_t last_index = f.file.find_last_of("/") + 1;
|
||||
const std::string file = f.file.substr(last_index, std::string::npos);
|
||||
|
||||
if (file == text)
|
||||
if (getFileName(f.file) == text)
|
||||
{
|
||||
return f.file;
|
||||
}
|
||||
@@ -114,20 +100,12 @@ bool Asset::check() const
|
||||
// Comprueba que existe un fichero
|
||||
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)
|
||||
printWithDots("Checking file : ", file_name, (success ? " [ OK ]" : " [ ERROR ]"));
|
||||
printWithDots("Checking file : ", getFileName(path), "[ ERROR ]");
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <string> // for string, basic_string
|
||||
#include <vector> // for vector
|
||||
#include "utils.h"
|
||||
|
||||
enum class AssetType : int
|
||||
{
|
||||
@@ -27,14 +28,17 @@ private:
|
||||
// Estructura para definir un item
|
||||
struct AssetItem
|
||||
{
|
||||
std::string file; // Ruta del fichero desde la raiz del directorio
|
||||
enum AssetType type; // Indica el tipo de recurso
|
||||
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
|
||||
std::string file; // Ruta del fichero desde la raíz del directorio
|
||||
AssetType type; // Indica el tipo de recurso
|
||||
bool required; // Indica si es un fichero que debe de existir
|
||||
|
||||
// Constructor
|
||||
AssetItem(const std::string &filePath, AssetType assetType, bool isRequired)
|
||||
: file(filePath), type(assetType), required(isRequired) {}
|
||||
};
|
||||
|
||||
// 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::string executable_path_; // Ruta al ejecutable
|
||||
|
||||
@@ -45,7 +49,8 @@ private:
|
||||
std::string getTypeName(AssetType type) const;
|
||||
|
||||
// Constructor
|
||||
explicit Asset(const std::string &executable_path);
|
||||
explicit Asset(const std::string &executable_path)
|
||||
: executable_path_(getPath(executable_path)) {}
|
||||
|
||||
// Destructor
|
||||
~Asset() = default;
|
||||
@@ -63,7 +68,7 @@ public:
|
||||
// Añade un elemento a la lista
|
||||
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;
|
||||
|
||||
// Comprueba que existen todos los elementos
|
||||
|
||||
@@ -20,16 +20,11 @@ Background::Background()
|
||||
grass_texture_(Resource::get()->getTexture("game_grass.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}),
|
||||
src_rect_({0, 0, 320, 240}),
|
||||
dst_rect_({0, 0, 320, 240}),
|
||||
base_(rect_.h),
|
||||
color_({param.background.attenuate_color.r, param.background.attenuate_color.g, param.background.attenuate_color.b}),
|
||||
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_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 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
|
||||
int gradient_number_; // Indica el número de degradado de fondo que se va a dibujar
|
||||
int alpha_; // Transparencia entre los dos degradados
|
||||
float clouds_speed_; // Velocidad a la que se desplazan las nubes
|
||||
float transition_; // Nivel de transición del fondo 0..1
|
||||
int counter_; // Contador interno
|
||||
int gradient_number_ = 0; // Indica el número de degradado de fondo que se va a dibujar
|
||||
int alpha_ = 0; // Transparencia entre los dos degradados
|
||||
float clouds_speed_ = 0; // Velocidad a la que se desplazan las nubes
|
||||
float transition_ = 0; // Nivel de transición del fondo 0..1
|
||||
int counter_ = 0; // Contador interno
|
||||
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 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),
|
||||
vel_x_(vel_x),
|
||||
being_created_(creation_timer > 0),
|
||||
blinking_(false),
|
||||
enabled_(true),
|
||||
invulnerable_(creation_timer > 0),
|
||||
stopped_(true),
|
||||
visible_(true),
|
||||
creation_counter_(creation_timer),
|
||||
creation_counter_ini_(creation_timer),
|
||||
stopped_counter_(0),
|
||||
kind_(kind),
|
||||
counter_(0),
|
||||
travel_y_(1.0f),
|
||||
speed_(speed)
|
||||
{
|
||||
|
||||
@@ -227,23 +220,9 @@ Balloon::Balloon(float x, float y, Uint8 kind, float vel_x, float speed, Uint16
|
||||
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
|
||||
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
|
||||
updateColliders();
|
||||
}
|
||||
@@ -726,8 +705,8 @@ Circle &Balloon::getCollider()
|
||||
// Alinea el circulo de colisión con la posición del objeto globo
|
||||
void Balloon::updateColliders()
|
||||
{
|
||||
collider_.x = Uint16(pos_x_ + collider_.r);
|
||||
collider_.y = pos_y_ + collider_.r;
|
||||
collider_.x = static_cast<int>(pos_x_ + collider_.r);
|
||||
collider_.y = static_cast<int>(pos_y_ + collider_.r);
|
||||
}
|
||||
|
||||
// Obtiene le valor de la variable
|
||||
|
||||
@@ -74,49 +74,53 @@ private:
|
||||
// Estructura para las variables para el efecto de los rebotes
|
||||
struct Bouncing
|
||||
{
|
||||
bool enabled; // Si el efecto está activo
|
||||
Uint8 counter; // Countador para el efecto
|
||||
Uint8 speed; // Velocidad a la que transcurre el efecto
|
||||
float zoomW; // Zoom aplicado a la anchura
|
||||
float zoomH; // Zoom aplicado a la altura
|
||||
float despX; // 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
|
||||
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
|
||||
bool enabled = false; // Si el efecto está activo
|
||||
Uint8 counter = 0; // Countador para el efecto
|
||||
Uint8 speed = 2; // Velocidad a la que transcurre el efecto
|
||||
float zoomW = 1.0f; // Zoom aplicado a la anchura
|
||||
float zoomH = 1.0f; // Zoom aplicado a la altura
|
||||
float despX = 0.0f; // Desplazamiento de pixeles en el eje X 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 = {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
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite del objeto globo
|
||||
|
||||
// Variables
|
||||
float pos_x_; // Posición en el eje X
|
||||
float pos_y_; // Posición en el eje Y
|
||||
Uint8 width_; // Ancho
|
||||
Uint8 height_; // Alto
|
||||
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 gravity_; // Aceleración en el eje Y. Modifica la velocidad
|
||||
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
|
||||
bool being_created_; // Indica si el globo se está creando
|
||||
bool blinking_; // Indica si el globo está intermitente
|
||||
bool enabled_; // Indica si el globo esta activo
|
||||
bool invulnerable_; // Indica si el globo es invulnerable
|
||||
bool stopped_; // Indica si el globo está parado
|
||||
bool visible_; // Indica si el globo es visible
|
||||
Circle collider_; // Circulo de colisión del objeto
|
||||
Uint16 creation_counter_; // 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 stopped_counter_; // Contador para controlar el estado "parado"
|
||||
Uint8 kind_; // Tipo de globo
|
||||
Uint8 menace_; // Cantidad de amenaza que genera el globo
|
||||
Uint32 counter_; // 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 speed_; // Velocidad a la que se mueven los globos
|
||||
Uint8 size_; // Tamaño del globo
|
||||
Uint8 power_; // Cantidad de poder que alberga el globo
|
||||
Bouncing bouncing_; // Contiene las variables para el efecto de rebote
|
||||
float pos_x_; // Posición en el eje X
|
||||
float pos_y_; // Posición en el eje Y
|
||||
Uint8 width_; // Ancho
|
||||
Uint8 height_; // Alto
|
||||
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 gravity_; // Aceleración en el eje Y. Modifica la velocidad
|
||||
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
|
||||
bool being_created_; // Indica si el globo se está creando
|
||||
bool blinking_ = false; // Indica si el globo está intermitente
|
||||
bool enabled_ = true; // Indica si el globo esta activo
|
||||
bool invulnerable_; // Indica si el globo es invulnerable
|
||||
bool stopped_ = true; // Indica si el globo está parado
|
||||
bool visible_ = true; // Indica si el globo es visible
|
||||
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_ini_; // Valor inicial para el temporizador para controlar el estado "creandose"
|
||||
Uint16 score_; // Puntos que da el globo al ser destruido
|
||||
Uint16 stopped_counter_ = 0; // Contador para controlar el estado "parado"
|
||||
Uint8 kind_; // Tipo de globo
|
||||
Uint8 menace_; // Cantidad de amenaza que genera el globo
|
||||
Uint32 counter_ = 0; // Contador interno
|
||||
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
|
||||
Uint8 size_; // Tamaño del globo
|
||||
Uint8 power_; // Cantidad de poder que alberga el globo
|
||||
Bouncing bouncing_ = Bouncing(); // Contiene las variables para el efecto de rebote
|
||||
|
||||
// Alinea el circulo de colisión con la posición del objeto globo
|
||||
void updateColliders();
|
||||
|
||||
@@ -13,7 +13,7 @@ struct BalloonFormationParams
|
||||
int creation_counter = 0; // Temporizador para la creación del enemigo
|
||||
|
||||
// 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) {}
|
||||
};
|
||||
|
||||
|
||||
@@ -10,49 +10,22 @@
|
||||
|
||||
// Constructor
|
||||
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
|
||||
enabled_ = false;
|
||||
x_ = param.game.width / 2;
|
||||
y_ = param.title.press_start_position;
|
||||
index_controller_ = 0;
|
||||
index_button_ = 0;
|
||||
|
||||
buttons_.clear();
|
||||
DefineButtonsButton button;
|
||||
|
||||
button.label = lang::getText(95);
|
||||
button.input = InputType::FIRE_LEFT;
|
||||
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);
|
||||
buttons_.emplace_back(lang::getText(95), InputType::FIRE_LEFT, SDL_CONTROLLER_BUTTON_X);
|
||||
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);
|
||||
buttons_.emplace_back(lang::getText(98), InputType::START, SDL_CONTROLLER_BUTTON_START);
|
||||
buttons_.emplace_back(lang::getText(99), InputType::EXIT, SDL_CONTROLLER_BUTTON_BACK);
|
||||
|
||||
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
|
||||
|
||||
#include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent
|
||||
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
|
||||
#include <memory> // for shared_ptr, unique_ptr
|
||||
#include <string> // for string
|
||||
#include <vector> // for vector
|
||||
#include <SDL2/SDL_events.h> // for SDL_ControllerButtonEvent
|
||||
#include <SDL2/SDL_gamecontroller.h> // for SDL_GameControllerButton
|
||||
#include <memory> // for shared_ptr, unique_ptr
|
||||
#include <string> // for string
|
||||
#include <vector> // for vector
|
||||
class Input;
|
||||
class Text;
|
||||
enum class InputType : int;
|
||||
@@ -14,6 +14,10 @@ struct DefineButtonsButton
|
||||
std::string label; // Texto en pantalla para el botón
|
||||
InputType input; // Input asociado
|
||||
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
|
||||
@@ -25,12 +29,12 @@ private:
|
||||
std::shared_ptr<Text> text_; // Objeto para escribir texto
|
||||
|
||||
// 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 y_; // Posición donde dibujar el texto
|
||||
std::vector<DefineButtonsButton> buttons_; // Vector con las nuevas definiciones de botones/acciones
|
||||
int index_controller_; // Indice del controlador a reasignar
|
||||
int index_button_; // Indice para saber qué bot´çon se está definiendo
|
||||
int index_controller_ = 0; // Indice del controlador a reasignar
|
||||
int index_button_ = 0; // Indice para saber qué bot´çon se está definiendo
|
||||
std::vector<std::string> controller_names_; // Nombres de los mandos
|
||||
|
||||
// Incrementa el indice de los botones
|
||||
|
||||
@@ -84,13 +84,22 @@ Director::Director(int argc, const char *argv[])
|
||||
#ifdef ANBERNIC
|
||||
const std::string paramFilePath = asset->get("param_320x240.txt");
|
||||
#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
|
||||
loadParams(paramFilePath);
|
||||
|
||||
// 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
|
||||
initSDL();
|
||||
@@ -513,18 +522,33 @@ void Director::loadParams(const std::string &file_path)
|
||||
// Comprueba los parametros del programa
|
||||
void Director::checkProgramArguments(int argc, const char *argv[])
|
||||
{
|
||||
const std::vector<std::string> argument_list = {"--h", "--320x240", "--clear_score"};
|
||||
|
||||
// Establece la ruta del programa
|
||||
executable_path_ = argv[0];
|
||||
|
||||
// Valores por defecto
|
||||
param_file_argument_.clear();
|
||||
|
||||
// Comprueba el resto de parámetros
|
||||
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)
|
||||
{
|
||||
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");
|
||||
}
|
||||
|
||||
#ifdef ARCADE
|
||||
// Apaga el sistema
|
||||
void Director::shutdownSystem()
|
||||
{
|
||||
@@ -744,4 +769,5 @@ void Director::shutdownSystem()
|
||||
// Sistema operativo no compatible
|
||||
#error "Sistema operativo no soportado"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif //ARCADE
|
||||
@@ -25,7 +25,6 @@ private:
|
||||
// Variables
|
||||
std::string executable_path_; // Path del ejecutable
|
||||
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
|
||||
void initJailAudio();
|
||||
@@ -71,9 +70,10 @@ private:
|
||||
|
||||
// Obtiene una fichero a partir de un lang::Code
|
||||
std::string getLangFile(lang::Code code);
|
||||
|
||||
#ifdef ARCADE
|
||||
// Apaga el sistema
|
||||
void shutdownSystem();
|
||||
#endif
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
|
||||
@@ -38,7 +38,7 @@ void Explosions::render()
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ struct ExplosionTexture
|
||||
std::vector<std::string> animation; // Animación para la textura
|
||||
|
||||
// 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) {}
|
||||
};
|
||||
|
||||
@@ -45,7 +45,7 @@ public:
|
||||
void render();
|
||||
|
||||
// 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
|
||||
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>();
|
||||
balloon_formations_ = std::make_unique<BalloonFormations>();
|
||||
|
||||
// Carga los recursos
|
||||
loadMedia();
|
||||
// Asigna los recursos a variables privadas del objeto
|
||||
setResources();
|
||||
|
||||
// Inicializa los vectores con los datos para la demo
|
||||
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);
|
||||
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
|
||||
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);
|
||||
player1->setName(lang::getText(53));
|
||||
const auto controller1 = getController(player1->getId());
|
||||
player1->setController(controller1);
|
||||
players_.push_back(std::move(player1));
|
||||
{
|
||||
const int y = param.game.play_area.rect.h - 30;
|
||||
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_));
|
||||
players_.back()->setScoreBoardPanel(SCOREBOARD_LEFT_PANEL);
|
||||
players_.back()->setName(lang::getText(53));
|
||||
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_);
|
||||
player2->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL);
|
||||
player2->setName(lang::getText(54));
|
||||
const auto controller2 = getController(player2->getId());
|
||||
player2->setController(controller2);
|
||||
players_.push_back(std::move(player2));
|
||||
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_));
|
||||
players_.back()->setScoreBoardPanel(SCOREBOARD_RIGHT_PANEL);
|
||||
players_.back()->setName(lang::getText(54));
|
||||
players_.back()->setController(getController(players_.back()->getId()));
|
||||
}
|
||||
|
||||
// Obtiene mediante "playerID" el jugador que va a empezar jugar
|
||||
auto main_player = getPlayer(player_id);
|
||||
|
||||
// Cambia el estado del jugador seleccionado
|
||||
main_player->setStatusPlaying(PlayerStatus::PLAYING);
|
||||
|
||||
// Como es el principio del juego, empieza sin inmunidad
|
||||
main_player->setInvulnerable(false);
|
||||
// Activa el jugador que coincide con el "player_id"
|
||||
{
|
||||
auto player = getPlayer(player_id);
|
||||
player->setStatusPlaying(PlayerStatus::PLAYING);
|
||||
player->setInvulnerable(false);
|
||||
}
|
||||
|
||||
// Variables relacionadas con la dificultad
|
||||
switch (difficulty_)
|
||||
@@ -150,8 +114,7 @@ void Game::init(int player_id)
|
||||
{
|
||||
default_balloon_speed_ = BALLOON_SPEED_1;
|
||||
difficulty_score_multiplier_ = 0.5f;
|
||||
difficulty_color_ = difficulty_easy_color;
|
||||
scoreboard_->setColor(difficulty_color_);
|
||||
scoreboard_->setColor(scoreboard_easy_color);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -159,8 +122,7 @@ void Game::init(int player_id)
|
||||
{
|
||||
default_balloon_speed_ = BALLOON_SPEED_1;
|
||||
difficulty_score_multiplier_ = 1.0f;
|
||||
difficulty_color_ = difficulty_normal_color;
|
||||
scoreboard_->setColor(scoreboard_color);
|
||||
scoreboard_->setColor(scoreboard_normal_color);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -168,8 +130,7 @@ void Game::init(int player_id)
|
||||
{
|
||||
default_balloon_speed_ = BALLOON_SPEED_5;
|
||||
difficulty_score_multiplier_ = 1.5f;
|
||||
difficulty_color_ = difficulty_hard_color;
|
||||
scoreboard_->setColor(difficulty_color_);
|
||||
scoreboard_->setColor(scoreboard_hard_color);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -179,15 +140,13 @@ void Game::init(int player_id)
|
||||
|
||||
// Variables para el marcador
|
||||
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_)
|
||||
{
|
||||
scoreboard_->setName(player->getScoreBoardPanel(), player->getName());
|
||||
if (player->isWaiting())
|
||||
{
|
||||
scoreboard_->setMode(player->getScoreBoardPanel(), ScoreboardMode::WAITING);
|
||||
}
|
||||
}
|
||||
scoreboard_->setMode(SCOREBOARD_CENTER_PANEL, ScoreboardMode::STAGE_INFO);
|
||||
|
||||
// Resto de variables
|
||||
ticks_ = 0;
|
||||
@@ -232,10 +191,12 @@ void Game::init(int player_id)
|
||||
if (demo_.enabled)
|
||||
{
|
||||
// Selecciona una pantalla al azar
|
||||
constexpr auto demos = 3;
|
||||
const auto demo = rand() % demos;
|
||||
const int stages[demos] = {0, 3, 5};
|
||||
current_stage_ = stages[demo];
|
||||
{
|
||||
constexpr auto demos = 3;
|
||||
const auto demo = rand() % demos;
|
||||
const int stages[demos] = {0, 3, 5};
|
||||
current_stage_ = stages[demo];
|
||||
}
|
||||
|
||||
// Actualiza el numero de globos explotados según la fase de la demo
|
||||
for (int i = 0; i < current_stage_; ++i)
|
||||
@@ -299,11 +260,26 @@ void Game::init(int player_id)
|
||||
smart_sprites_.clear();
|
||||
}
|
||||
|
||||
// Carga los recursos necesarios para la sección 'Game'
|
||||
void Game::loadMedia()
|
||||
Game::~Game()
|
||||
{
|
||||
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
|
||||
{
|
||||
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
|
||||
void Game::deployBalloonFormation()
|
||||
{
|
||||
@@ -1176,7 +1135,7 @@ ItemType Game::dropItem()
|
||||
// Crea un objeto item
|
||||
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
|
||||
@@ -1371,8 +1330,9 @@ void Game::updateBalloonDeployCounter()
|
||||
// Actualiza el juego
|
||||
void Game::update()
|
||||
{
|
||||
// Comprueba que la diferencia de ticks sea mayor a la velocidad del juego
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
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
|
||||
void Game::reloadTextures()
|
||||
{
|
||||
@@ -2014,8 +1964,8 @@ void Game::pause(bool value)
|
||||
// Añade una puntuación a la tabla de records
|
||||
void Game::addScoreToScoreBoard(const std::string &name, int score)
|
||||
{
|
||||
const auto entry = (HiScoreEntry){trim(name), score};
|
||||
auto manager = std::make_unique<ManageHiScoreTable>(&options.game.hi_score_table);
|
||||
const auto entry = HiScoreEntry(trim(name), score);
|
||||
auto manager = std::make_unique<ManageHiScoreTable>(options.game.hi_score_table);
|
||||
manager->add(entry);
|
||||
manager->saveToFile(asset_->get("score.bin"));
|
||||
}
|
||||
@@ -2057,26 +2007,28 @@ void Game::checkPlayersStatusPlaying()
|
||||
// Obtiene un jugador a partir de su "id"
|
||||
std::shared_ptr<Player> Game::getPlayer(int id)
|
||||
{
|
||||
for (const auto &player : players_)
|
||||
{
|
||||
if (player->getId() == id)
|
||||
{
|
||||
return player;
|
||||
}
|
||||
}
|
||||
auto it = std::find_if(players_.begin(), players_.end(), [id](const auto &player)
|
||||
{ return player->getId() == id; });
|
||||
|
||||
if (it != players_.end())
|
||||
{
|
||||
return *it;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Obtiene un controlador a partir del "id" del jugador
|
||||
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 i;
|
||||
}
|
||||
return std::distance(options.controller.begin(), it);
|
||||
}
|
||||
|
||||
return -1;
|
||||
@@ -2117,7 +2069,7 @@ void Game::checkPauseInput()
|
||||
void Game::handleDemoMode()
|
||||
{
|
||||
int i = 0;
|
||||
for (auto &player : players_)
|
||||
for (const auto &player : players_)
|
||||
{
|
||||
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).
|
||||
void Game::handlePlayersInput()
|
||||
{
|
||||
for (auto &player : players_)
|
||||
for (const auto &player : players_)
|
||||
{
|
||||
if (player->isPlaying())
|
||||
{
|
||||
|
||||
@@ -76,6 +76,12 @@ private:
|
||||
int item_clock_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
|
||||
|
||||
// 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
|
||||
@@ -87,7 +93,6 @@ private:
|
||||
static constexpr int GAME_COMPLETED_END_ = 700;
|
||||
static constexpr int GAME_OVER_COUNTER_ = 350;
|
||||
static constexpr int TIME_STOPPED_COUNTER_ = 300;
|
||||
static constexpr int TICKS_SPEED_ = 15;
|
||||
|
||||
// Porcentaje de aparición de los objetos
|
||||
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
|
||||
GameDifficulty difficulty_; // Dificultad del juego
|
||||
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
|
||||
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
|
||||
@@ -183,14 +187,8 @@ private:
|
||||
// Comprueba los eventos que hay en cola
|
||||
void checkEvents();
|
||||
|
||||
// Inicializa las variables necesarias para la sección 'Game'
|
||||
void init(int player_id);
|
||||
|
||||
// Carga los recursos necesarios para la sección 'Game'
|
||||
void loadMedia();
|
||||
|
||||
// Libera los recursos previamente cargados
|
||||
void unloadMedia();
|
||||
// Asigna los recursos a variables privadas del objeto
|
||||
void setResources();
|
||||
|
||||
// Crea una formación de enemigos
|
||||
void deployBalloonFormation();
|
||||
@@ -366,9 +364,6 @@ private:
|
||||
// Comprueba si todos los jugadores han terminado de jugar
|
||||
bool allPlayersAreNotPlaying();
|
||||
|
||||
// Elimina todos los objetos contenidos en vectores
|
||||
void deleteAllVectorObjects();
|
||||
|
||||
// Recarga las texturas
|
||||
void reloadTextures();
|
||||
|
||||
|
||||
@@ -51,7 +51,6 @@ void GameLogo::init()
|
||||
shake_.origin = xp;
|
||||
|
||||
// Inicializa el bitmap de 'Coffee'
|
||||
coffee_sprite_->init();
|
||||
coffee_sprite_->setPosX(xp);
|
||||
coffee_sprite_->setPosY(y_ - coffee_texture_->getHeight() - desp);
|
||||
coffee_sprite_->setWidth(coffee_texture_->getWidth());
|
||||
@@ -67,7 +66,6 @@ void GameLogo::init()
|
||||
coffee_sprite_->setDestY(y_ - coffee_texture_->getHeight());
|
||||
|
||||
// Inicializa el bitmap de 'Crisis'
|
||||
crisis_sprite_->init();
|
||||
crisis_sprite_->setPosX(xp + 15);
|
||||
crisis_sprite_->setPosY(y_ + desp);
|
||||
crisis_sprite_->setWidth(crisis_texture_->getWidth());
|
||||
|
||||
@@ -61,8 +61,9 @@ HiScoreTable::~HiScoreTable()
|
||||
// Actualiza las variables
|
||||
void HiScoreTable::update()
|
||||
{
|
||||
// Actualiza las variables
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
@@ -87,7 +88,7 @@ void HiScoreTable::update()
|
||||
|
||||
if (counter_ == 150)
|
||||
{
|
||||
background_->setColor({0, 0, 0});
|
||||
background_->setColor(Color(0, 0, 0));
|
||||
background_->setAlpha(96);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@ class HiScoreTable
|
||||
private:
|
||||
// Constantes
|
||||
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
|
||||
SDL_Renderer *renderer_; // El renderizador de la ventana
|
||||
|
||||
@@ -25,32 +25,22 @@ struct JA_Music_t; // lines 22-22
|
||||
|
||||
// Constructor
|
||||
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
|
||||
backbuffer_ = SDL_CreateTexture(renderer_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, param.game.width, param.game.height);
|
||||
SDL_SetTextureBlendMode(backbuffer_, SDL_BLENDMODE_BLEND);
|
||||
|
||||
// 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);
|
||||
|
||||
// Inicializa variables
|
||||
section::name = section::Name::INSTRUCTIONS;
|
||||
ticks_ = 0;
|
||||
ticks_speed_ = 15;
|
||||
counter_ = 0;
|
||||
counter_end_ = 700;
|
||||
view_ = {0, 0, param.game.width, param.game.height};
|
||||
sprite_pos_ = {0, 0};
|
||||
item_space_ = 2;
|
||||
|
||||
// Inicializa objetos
|
||||
fade_->setColor(fade_color.r, fade_color.g, fade_color.b);
|
||||
@@ -214,8 +204,9 @@ void Instructions::fillBackbuffer()
|
||||
// Actualiza las variables
|
||||
void Instructions::update()
|
||||
{
|
||||
// Actualiza las variables
|
||||
if (SDL_GetTicks() - ticks_ > ticks_speed_)
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
@@ -30,24 +30,23 @@ class Instructions
|
||||
{
|
||||
private:
|
||||
// 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::unique_ptr<Sprite>> sprites_; // Vector con los sprites de los items
|
||||
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<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
|
||||
int counter_; // Contador
|
||||
int counter_end_; // Valor final para el contador
|
||||
Uint32 ticks_; // 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_Point sprite_pos_; // Posición del primer sprite
|
||||
int item_space_; // Espacio entre los items
|
||||
int counter_ = 0; // Contador
|
||||
int counter_end_ = 700; // Valor final para el contador
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
SDL_Rect view_; // Vista del backbuffer que se va amostrar por pantalla
|
||||
SDL_Point sprite_pos_ = {0, 0}; // Posición del primer sprite
|
||||
int item_space_ = 2; // Espacio entre los items
|
||||
|
||||
// Actualiza las variables
|
||||
void update();
|
||||
|
||||
@@ -21,17 +21,13 @@ struct JA_Music_t; // lines 19-19
|
||||
|
||||
// Constructor
|
||||
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
|
||||
section::name = section::Name::INTRO;
|
||||
section::options = section::Options::NONE;
|
||||
ticks_ = 0;
|
||||
ticks_speed_ = 15;
|
||||
scene_ = 1;
|
||||
|
||||
// Inicializa los bitmaps de la intro
|
||||
constexpr int totalBitmaps = 6;
|
||||
@@ -372,7 +368,9 @@ void Intro::updateScenes()
|
||||
// Actualiza las variables del objeto
|
||||
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
|
||||
ticks_ = SDL_GetTicks();
|
||||
|
||||
@@ -26,9 +26,8 @@ private:
|
||||
std::vector<std::unique_ptr<Writer>> texts_; // Textos de la intro
|
||||
|
||||
// Variables
|
||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
Uint8 ticks_speed_; // Velocidad a la que se repiten los bucles del programa
|
||||
int scene_; // Indica que escena está activa
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
int scene_ = 1; // Indica que escena está activa
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void update();
|
||||
|
||||
@@ -5,27 +5,26 @@
|
||||
class Texture;
|
||||
|
||||
// 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)),
|
||||
accel_x_(0.0f),
|
||||
floor_collision_(false),
|
||||
type_(type),
|
||||
enabled_(true),
|
||||
play_area_(play_area),
|
||||
time_to_live_(600)
|
||||
play_area_(play_area)
|
||||
{
|
||||
if (type == ItemType::COFFEE_MACHINE)
|
||||
switch (type)
|
||||
{
|
||||
case ItemType::COFFEE_MACHINE:
|
||||
{
|
||||
width_ = 28;
|
||||
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_;
|
||||
vel_x_ = 0.0f;
|
||||
vel_y_ = -0.1f;
|
||||
accel_y_ = 0.1f;
|
||||
collider_.r = 10;
|
||||
break;
|
||||
}
|
||||
else
|
||||
default:
|
||||
{
|
||||
width_ = 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;
|
||||
accel_y_ = 0.2f;
|
||||
collider_.r = width_ / 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
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)
|
||||
{
|
||||
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
|
||||
sprite_->setPosX(int(pos_x_));
|
||||
sprite_->setPosY(int(pos_y_));
|
||||
sprite_->setPosX(pos_x_);
|
||||
sprite_->setPosY(pos_y_);
|
||||
|
||||
// Alinea el circulo de colisión con el objeto
|
||||
shiftColliders();
|
||||
@@ -94,7 +95,7 @@ void Item::move()
|
||||
vel_y_ += accel_y_;
|
||||
|
||||
// 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
|
||||
pos_x_ -= vel_x_;
|
||||
@@ -114,14 +115,14 @@ void Item::move()
|
||||
}
|
||||
|
||||
// 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
|
||||
vel_y_ = 0;
|
||||
vel_x_ = 0;
|
||||
accel_x_ = 0;
|
||||
accel_y_ = 0;
|
||||
pos_y_ = play_area_->h - height_;
|
||||
pos_y_ = play_area_.h - height_;
|
||||
if (type_ == ItemType::COFFEE_MACHINE)
|
||||
{
|
||||
floor_collision_ = true;
|
||||
|
||||
@@ -29,20 +29,20 @@ private:
|
||||
std::unique_ptr<AnimatedSprite> sprite_; // Sprite con los graficos del objeto
|
||||
|
||||
// Variables
|
||||
float pos_x_; // Posición X del objeto
|
||||
float pos_y_; // Posición Y del objeto
|
||||
int width_; // Ancho del objeto
|
||||
int height_; // Alto del objeto
|
||||
float vel_x_; // Velocidad en el eje X
|
||||
float vel_y_; // Velocidad en el eje Y
|
||||
float accel_x_; // Aceleración en el eje X
|
||||
float accel_y_; // Aceleración en el eje Y
|
||||
bool floor_collision_; // Indica si el objeto colisiona con el suelo
|
||||
ItemType type_; // Especifica el tipo de objeto que es
|
||||
bool enabled_; // Especifica si el objeto está habilitado
|
||||
Circle collider_; // Circulo de colisión del objeto
|
||||
SDL_Rect *play_area_; // Rectangulo con la zona de juego
|
||||
Uint16 time_to_live_; // Temporizador con el tiempo que el objeto está presente
|
||||
float pos_x_; // Posición X del objeto
|
||||
float pos_y_; // Posición Y del objeto
|
||||
int width_; // Ancho del objeto
|
||||
int height_; // Alto del objeto
|
||||
float vel_x_; // Velocidad en el eje X
|
||||
float vel_y_; // Velocidad en el eje Y
|
||||
float accel_x_ = 0.0f; // Aceleración en el eje X
|
||||
float accel_y_; // Aceleración en el eje Y
|
||||
bool floor_collision_ = false; // Indica si el objeto colisiona con el suelo
|
||||
ItemType type_; // Especifica el tipo de objeto que es
|
||||
bool enabled_ = true; // Especifica si el objeto está habilitado
|
||||
Circle collider_; // Circulo de colisión del objeto
|
||||
SDL_Rect play_area_; // Rectangulo con la zona de juego
|
||||
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
|
||||
void shiftColliders();
|
||||
@@ -58,7 +58,7 @@ private:
|
||||
|
||||
public:
|
||||
// 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
|
||||
~Item() = default;
|
||||
|
||||
@@ -19,13 +19,13 @@
|
||||
Logo::Logo()
|
||||
: since_texture_(Resource::get()->getTexture("logo_since_1998.png")),
|
||||
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
|
||||
counter_ = 0;
|
||||
section::name = section::Name::LOGO;
|
||||
ticks_ = 0;
|
||||
dest_.x = param.game.game_area.center_x - jail_texture_->getWidth() / 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()});
|
||||
@@ -45,14 +45,14 @@ Logo::Logo()
|
||||
}
|
||||
|
||||
// Inicializa el vector de colores
|
||||
color_.push_back({0x00, 0x00, 0x00}); // Black
|
||||
color_.push_back({0x00, 0x00, 0xd8}); // Blue
|
||||
color_.push_back({0xd8, 0x00, 0x00}); // Red
|
||||
color_.push_back({0xd8, 0x00, 0xd8}); // Magenta
|
||||
color_.push_back({0x00, 0xd8, 0x00}); // Green
|
||||
color_.push_back({0x00, 0xd8, 0xd8}); // Cyan
|
||||
color_.push_back({0xd8, 0xd8, 0x00}); // Yellow
|
||||
color_.push_back({0xFF, 0xFF, 0xFF}); // Bright white
|
||||
color_.push_back(Color(0x00, 0x00, 0x00)); // Black
|
||||
color_.push_back(Color(0x00, 0x00, 0xd8)); // Blue
|
||||
color_.push_back(Color(0xd8, 0x00, 0x00)); // Red
|
||||
color_.push_back(Color(0xd8, 0x00, 0xd8)); // Magenta
|
||||
color_.push_back(Color(0x00, 0xd8, 0x00)); // Green
|
||||
color_.push_back(Color(0x00, 0xd8, 0xd8)); // Cyan
|
||||
color_.push_back(Color(0xd8, 0xd8, 0x00)); // Yellow
|
||||
color_.push_back(Color(0xFF, 0xFF, 0xFF)); // Bright white
|
||||
}
|
||||
|
||||
// Recarga todas las texturas
|
||||
@@ -165,7 +165,8 @@ void Logo::updateTextureColors()
|
||||
// Actualiza las variables
|
||||
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)
|
||||
{
|
||||
// Actualiza el contador de ticks
|
||||
|
||||
@@ -21,7 +21,6 @@ class Logo
|
||||
{
|
||||
private:
|
||||
// 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 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
|
||||
|
||||
@@ -6,43 +6,36 @@
|
||||
#include <iostream> // for basic_ostream, char_traits, operator<<
|
||||
#include "utils.h" // for HiScoreEntry
|
||||
|
||||
// Constructor
|
||||
ManageHiScoreTable::ManageHiScoreTable(std::vector<HiScoreEntry> *table)
|
||||
: table_(table) {}
|
||||
|
||||
// Resetea la tabla a los valores por defecto
|
||||
void ManageHiScoreTable::clear()
|
||||
{
|
||||
// Limpia la tabla
|
||||
table_->clear();
|
||||
table_.clear();
|
||||
|
||||
// Añade 10 entradas predefinidas
|
||||
table_->push_back({"Bry", 1000000});
|
||||
table_->push_back({"Usufondo", 500000});
|
||||
table_->push_back({"G.Lucas", 100000});
|
||||
table_->push_back({"P.Delgat", 50000});
|
||||
table_->push_back({"P.Arrabalera", 10000});
|
||||
table_->push_back({"Pelechano", 5000});
|
||||
table_->push_back({"Sahuquillo", 1000});
|
||||
table_->push_back({"Bacteriol", 500});
|
||||
table_->push_back({"Pepe", 200});
|
||||
table_->push_back({"Rosita", 100});
|
||||
table_.push_back(HiScoreEntry("Bry", 1000000));
|
||||
table_.push_back(HiScoreEntry("Usufondo", 500000));
|
||||
table_.push_back(HiScoreEntry("G.Lucas", 100000));
|
||||
table_.push_back(HiScoreEntry("P.Delgat", 50000));
|
||||
table_.push_back(HiScoreEntry("P.Arrabalera", 10000));
|
||||
table_.push_back(HiScoreEntry("Pelechano", 5000));
|
||||
table_.push_back(HiScoreEntry("Sahuquillo", 1000));
|
||||
table_.push_back(HiScoreEntry("Bacteriol", 500));
|
||||
table_.push_back(HiScoreEntry("Pepe", 200));
|
||||
table_.push_back(HiScoreEntry("Rosita", 100));
|
||||
}
|
||||
|
||||
// Añade un elemento a la tabla
|
||||
void ManageHiScoreTable::add(HiScoreEntry entry)
|
||||
{
|
||||
// Añade la entrada a la tabla
|
||||
table_->push_back(entry);
|
||||
table_.push_back(entry);
|
||||
|
||||
// Ordena la tabla
|
||||
sort();
|
||||
|
||||
// Deja solo las 10 primeras entradas
|
||||
if (static_cast<int>(table_->size()) > 10)
|
||||
{
|
||||
table_->resize(10);
|
||||
}
|
||||
table_.resize(10);
|
||||
}
|
||||
|
||||
// Ordena la tabla
|
||||
@@ -51,28 +44,27 @@ void ManageHiScoreTable::sort()
|
||||
struct
|
||||
{
|
||||
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
|
||||
bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
||||
{
|
||||
clear();
|
||||
|
||||
auto success = true;
|
||||
auto file = SDL_RWFromFile(file_path.c_str(), "r+b");
|
||||
|
||||
if (file)
|
||||
{
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
std::cout << "Reading file: " << file_name.c_str() << std::endl;
|
||||
for (int i = 0; i < (int)table_->size(); ++i)
|
||||
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||
|
||||
for (auto &entry : table_)
|
||||
{
|
||||
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;
|
||||
break;
|
||||
@@ -84,19 +76,15 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
||||
break;
|
||||
}
|
||||
|
||||
char *name = static_cast<char *>(malloc(nameSize + 1));
|
||||
if (SDL_RWread(file, name, sizeof(char) * nameSize, 1) == 0)
|
||||
std::vector<char> nameBuffer(nameSize + 1);
|
||||
if (SDL_RWread(file, nameBuffer.data(), sizeof(char) * nameSize, 1) == 0)
|
||||
{
|
||||
success = false;
|
||||
free(name);
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
name[nameSize] = 0;
|
||||
table_->at(i).name = name;
|
||||
free(name);
|
||||
}
|
||||
|
||||
nameBuffer[nameSize] = '\0';
|
||||
entry.name = std::string(nameBuffer.data());
|
||||
}
|
||||
|
||||
SDL_RWclose(file);
|
||||
@@ -113,28 +101,26 @@ bool ManageHiScoreTable::loadFromFile(const std::string &file_path)
|
||||
// Guarda la tabla en un fichero
|
||||
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 file = SDL_RWFromFile(file_path.c_str(), "w+b");
|
||||
|
||||
if (file)
|
||||
{
|
||||
// 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);
|
||||
const int nameSize = (int)table_->at(i).name.size();
|
||||
SDL_RWwrite(file, &table_.at(i).score, sizeof(int), 1);
|
||||
const int nameSize = (int)table_.at(i).name.size();
|
||||
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;
|
||||
// Cierra el fichero
|
||||
std::cout << "Writing file: " << getFileName(file_path).c_str() << std::endl;
|
||||
SDL_RWclose(file);
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -17,14 +17,15 @@ class ManageHiScoreTable
|
||||
{
|
||||
private:
|
||||
// Variables
|
||||
std::vector<HiScoreEntry> *table_; // Tabla con los records
|
||||
std::vector<HiScoreEntry> &table_; // Tabla con los records
|
||||
|
||||
// Ordena la tabla
|
||||
void sort();
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> *table);
|
||||
explicit ManageHiScoreTable(std::vector<HiScoreEntry> &table)
|
||||
: table_(table) {}
|
||||
|
||||
// Destructor
|
||||
~ManageHiScoreTable() = default;
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
Notifier *Notifier::notifier_ = nullptr;
|
||||
|
||||
// [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);
|
||||
}
|
||||
@@ -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
|
||||
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
|
||||
Color color = {255, 255, 255};
|
||||
Color color{255, 255, 255};
|
||||
if (num_texts == 2)
|
||||
{ // Dos lineas de texto
|
||||
text_->writeColored(padding_in_h + icon_space, padding_in_v, text1, color);
|
||||
|
||||
@@ -89,7 +89,7 @@ private:
|
||||
|
||||
public:
|
||||
// [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
|
||||
static void destroy();
|
||||
@@ -111,7 +111,7 @@ public:
|
||||
* @param icon Icono opcional para mostrar (valor predeterminado: -1).
|
||||
* @param code Permite asignar un código a la notificación (valor predeterminado: cadena vacía).
|
||||
*/
|
||||
void showText(std::string text1 = std::string(), std::string text2 = std::string(), int icon = -1, std::string code = std::string());
|
||||
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
|
||||
bool isActive();
|
||||
|
||||
@@ -86,14 +86,13 @@ bool loadOptionsFile(std::string file_path)
|
||||
bool success = true;
|
||||
|
||||
// Variables para manejar el fichero
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
std::ifstream file(file_path);
|
||||
|
||||
// Si el fichero se puede abrir
|
||||
if (file.good())
|
||||
{
|
||||
// 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;
|
||||
while (std::getline(file, line))
|
||||
{
|
||||
@@ -105,14 +104,12 @@ bool loadOptionsFile(std::string file_path)
|
||||
// Procesa las dos subcadenas
|
||||
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;
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cierra el fichero
|
||||
file.close();
|
||||
}
|
||||
|
||||
@@ -146,16 +143,15 @@ bool loadOptionsFile(std::string file_path)
|
||||
// Guarda el fichero de configuración
|
||||
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);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
std::cout << "Writing file: " << file_name << std::endl;
|
||||
std::cout << "Writing file: " << getFileName(file_path) << std::endl;
|
||||
|
||||
// Opciones de video
|
||||
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);
|
||||
}
|
||||
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
std::cout << "Reading file: " << file_name << std::endl;
|
||||
std::cout << "Reading file: " << getFileName(file_path) << std::endl;
|
||||
|
||||
std::string line, param1, param2;
|
||||
while (std::getline(file, line))
|
||||
|
||||
@@ -11,26 +11,18 @@
|
||||
#include "options.h"
|
||||
|
||||
// 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])),
|
||||
power_sprite_(std::make_unique<AnimatedSprite>(texture[1], animations[1])),
|
||||
enter_name_(std::make_unique<EnterName>()),
|
||||
play_area_(play_area),
|
||||
id_(id),
|
||||
pos_x_(x),
|
||||
pos_y_(y),
|
||||
play_area_(play_area),
|
||||
default_pos_x_(x),
|
||||
default_pos_y_(y),
|
||||
status_playing_(PlayerStatus::WAITING),
|
||||
scoreboard_panel_(0),
|
||||
name_(std::string()),
|
||||
controller_index_(0),
|
||||
demo_(demo)
|
||||
{
|
||||
// Reserva memoria para los objetos
|
||||
// Configura objetos
|
||||
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_sprite_->setPosY(y - (power_sprite_->getHeight() - player_sprite_->getHeight()));
|
||||
|
||||
@@ -46,25 +38,21 @@ void Player::init()
|
||||
pos_x_ = default_pos_x_;
|
||||
pos_y_ = default_pos_y_;
|
||||
status_walking_ = PlayerStatus::WALKING_STOP;
|
||||
status_firing_ = PlayerStatus::FIRING_NO;
|
||||
status_firing_ = PlayerStatus::FIRING_NONE;
|
||||
status_playing_ = PlayerStatus::WAITING;
|
||||
invulnerable_ = true;
|
||||
invulnerable_counter_ = PLAYER_INVULNERABLE_COUNTER;
|
||||
invulnerable_counter_ = INVULNERABLE_COUNTER_;
|
||||
power_up_ = false;
|
||||
power_up_counter_ = PLAYER_POWERUP_COUNTER;
|
||||
power_up_counter_ = POWERUP_COUNTER_;
|
||||
extra_hit_ = false;
|
||||
coffees_ = 0;
|
||||
input_ = true;
|
||||
continue_ticks_ = 0;
|
||||
continue_counter_ = 10;
|
||||
enter_name_ticks_ = 0;
|
||||
enter_name_counter_ = param.game.enter_name_seconds;
|
||||
width_ = 30;
|
||||
height_ = 30;
|
||||
collider_.r = 9;
|
||||
shiftColliders();
|
||||
vel_x_ = 0;
|
||||
vel_y_ = 0;
|
||||
base_speed_ = 1.5;
|
||||
score_ = 0;
|
||||
score_multiplier_ = 1.0f;
|
||||
cooldown_ = 10;
|
||||
@@ -107,14 +95,14 @@ void Player::setInputPlaying(InputType input)
|
||||
{
|
||||
case InputType::LEFT:
|
||||
{
|
||||
vel_x_ = -base_speed_;
|
||||
vel_x_ = -BASE_SPEED_;
|
||||
setWalkingStatus(PlayerStatus::WALKING_LEFT);
|
||||
break;
|
||||
}
|
||||
|
||||
case InputType::RIGHT:
|
||||
{
|
||||
vel_x_ = base_speed_;
|
||||
vel_x_ = BASE_SPEED_;
|
||||
setWalkingStatus(PlayerStatus::WALKING_RIGHT);
|
||||
break;
|
||||
}
|
||||
@@ -186,7 +174,7 @@ void Player::move()
|
||||
pos_x_ += vel_x_;
|
||||
|
||||
// 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
|
||||
pos_x_ -= vel_x_;
|
||||
@@ -203,7 +191,7 @@ void Player::move()
|
||||
player_sprite_->update();
|
||||
|
||||
// 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
|
||||
const float vx = player_sprite_->getVelX();
|
||||
@@ -226,7 +214,7 @@ void Player::render()
|
||||
{
|
||||
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();
|
||||
}
|
||||
@@ -261,7 +249,7 @@ void Player::setAnimation()
|
||||
// Establece la animación a partir de las cadenas
|
||||
if (isPlaying())
|
||||
{
|
||||
if (status_firing_ == PlayerStatus::FIRING_NO)
|
||||
if (status_firing_ == PlayerStatus::FIRING_NONE)
|
||||
{ // No esta disparando
|
||||
player_sprite_->setCurrentAnimation(a_walking);
|
||||
player_sprite_->setFlip(flip_walk);
|
||||
@@ -301,13 +289,13 @@ int Player::getPosY() const
|
||||
// Obtiene el valor de la variable
|
||||
int Player::getWidth() const
|
||||
{
|
||||
return width_;
|
||||
return WIDTH_;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
int Player::getHeight() const
|
||||
{
|
||||
return height_;
|
||||
return HEIGHT_;
|
||||
}
|
||||
|
||||
// Indica si el jugador puede disparar
|
||||
@@ -336,7 +324,7 @@ void Player::updateCooldown()
|
||||
}
|
||||
else
|
||||
{
|
||||
setFiringStatus(PlayerStatus::FIRING_NO);
|
||||
setFiringStatus(PlayerStatus::FIRING_NONE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,8 +447,8 @@ void Player::setStatusPlaying(PlayerStatus value)
|
||||
{
|
||||
case PlayerStatus::PLAYING:
|
||||
{
|
||||
status_playing_ = PlayerStatus::PLAYING;
|
||||
init();
|
||||
status_playing_ = PlayerStatus::PLAYING;
|
||||
setScoreboardMode(ScoreboardMode::SCORE);
|
||||
break;
|
||||
}
|
||||
@@ -556,7 +544,7 @@ bool Player::isInvulnerable() const
|
||||
void Player::setInvulnerable(bool value)
|
||||
{
|
||||
invulnerable_ = value;
|
||||
invulnerable_counter_ = invulnerable_ ? PLAYER_INVULNERABLE_COUNTER : 0;
|
||||
invulnerable_counter_ = invulnerable_ ? INVULNERABLE_COUNTER_ : 0;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
@@ -599,7 +587,7 @@ bool Player::isPowerUp() const
|
||||
void Player::setPowerUp()
|
||||
{
|
||||
power_up_ = true;
|
||||
power_up_counter_ = PLAYER_POWERUP_COUNTER;
|
||||
power_up_counter_ = POWERUP_COUNTER_;
|
||||
}
|
||||
|
||||
// Obtiene el valor de la variable
|
||||
@@ -654,18 +642,6 @@ void Player::removeExtraHit()
|
||||
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
|
||||
int Player::getCoffees() const
|
||||
{
|
||||
@@ -681,8 +657,8 @@ Circle &Player::getCollider()
|
||||
// Actualiza el circulo de colisión a la posición del jugador
|
||||
void Player::shiftColliders()
|
||||
{
|
||||
collider_.x = int(pos_x_ + (width_ / 2));
|
||||
collider_.y = int(pos_y_ + (height_ / 2));
|
||||
collider_.x = static_cast<int>(pos_x_ + (WIDTH_ / 2));
|
||||
collider_.y = static_cast<int>(pos_y_ + (HEIGHT_ / 2));
|
||||
}
|
||||
|
||||
// Pone las texturas del jugador
|
||||
@@ -703,9 +679,8 @@ void Player::updateContinueCounter()
|
||||
{
|
||||
if (status_playing_ == PlayerStatus::CONTINUE)
|
||||
{
|
||||
constexpr Uint32 ticks_speed = 1000;
|
||||
|
||||
if (SDL_GetTicks() - continue_ticks_ > ticks_speed)
|
||||
constexpr int TICKS_SPEED = 1000;
|
||||
if (SDL_GetTicks() - continue_ticks_ > TICKS_SPEED)
|
||||
{
|
||||
decContinueCounter();
|
||||
}
|
||||
@@ -717,9 +692,8 @@ void Player::updateEnterNameCounter()
|
||||
{
|
||||
if (status_playing_ == PlayerStatus::ENTERING_NAME)
|
||||
{
|
||||
constexpr Uint32 ticks_speed = 1000;
|
||||
|
||||
if (SDL_GetTicks() - enter_name_ticks_ > ticks_speed)
|
||||
constexpr int TICKS_SPEED = 1000;
|
||||
if (SDL_GetTicks() - enter_name_ticks_ > TICKS_SPEED)
|
||||
{
|
||||
decEnterNameCounter();
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ enum class PlayerStatus
|
||||
FIRING_UP,
|
||||
FIRING_LEFT,
|
||||
FIRING_RIGHT,
|
||||
FIRING_NO,
|
||||
FIRING_NONE,
|
||||
|
||||
PLAYING,
|
||||
CONTINUE,
|
||||
@@ -35,54 +35,55 @@ enum class PlayerStatus
|
||||
};
|
||||
|
||||
// Variables del jugador
|
||||
constexpr int PLAYER_INVULNERABLE_COUNTER = 200;
|
||||
constexpr int PLAYER_POWERUP_COUNTER = 1500;
|
||||
|
||||
// Clase Player
|
||||
class Player
|
||||
{
|
||||
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
|
||||
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<EnterName> enter_name_; // Clase utilizada para introducir el nombre
|
||||
SDL_Rect *play_area_; // Rectangulo con la zona de juego
|
||||
|
||||
// Variables
|
||||
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
|
||||
float pos_x_; // Posicion en el eje X
|
||||
int pos_y_; // Posicion en el eje Y
|
||||
float default_pos_x_; // Posición inicial para el jugador
|
||||
int default_pos_y_; // Posición inicial para el jugador
|
||||
int width_; // Anchura
|
||||
int height_; // Altura
|
||||
float vel_x_; // Cantidad de pixeles a desplazarse en el eje X
|
||||
int vel_y_; // Cantidad de pixeles a desplazarse en el eje Y
|
||||
float base_speed_; // Velocidad base del jugador
|
||||
int cooldown_; // Contador durante el cual no puede disparar
|
||||
int score_; // Puntos del jugador
|
||||
float score_multiplier_; // Multiplicador de puntos
|
||||
PlayerStatus status_walking_; // Estado del jugador al moverse
|
||||
PlayerStatus status_firing_; // Estado del jugador al disparar
|
||||
PlayerStatus status_playing_; // Estado del jugador en el juego
|
||||
bool invulnerable_; // Indica si el jugador es invulnerable
|
||||
int invulnerable_counter_; // Contador para la invulnerabilidad
|
||||
bool extra_hit_; // Indica si el jugador tiene un toque extra
|
||||
int coffees_; // Indica cuantos cafes lleva acumulados
|
||||
bool power_up_; // Indica si el jugador tiene activo el modo PowerUp
|
||||
int power_up_counter_; // Temporizador para el modo PowerUp
|
||||
int power_up_desp_x_; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||
bool input_; // Indica si puede recibir ordenes de entrada
|
||||
Circle collider_; // Circulo de colisión del jugador
|
||||
int continue_counter_; // Contador para poder continuar
|
||||
Uint32 continue_ticks_; // Variable para poder cambiar el contador de continue en función del tiempo
|
||||
int scoreboard_panel_; // Panel del marcador asociado al jugador
|
||||
std::string name_; // Nombre del jugador
|
||||
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
|
||||
int controller_index_; // Indice del array de mandos que utilizará para moverse
|
||||
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
|
||||
int id_; // Numero de identificación para el jugador. Player1 = 1, Player2 = 2
|
||||
SDL_Rect play_area_; // Rectangulo con la zona de juego
|
||||
float pos_x_ = 0.0f; // Posicion en el eje X
|
||||
int pos_y_ = 0; // Posicion en el eje Y
|
||||
float default_pos_x_; // Posición inicial para el jugador
|
||||
int default_pos_y_; // Posición inicial para el jugador
|
||||
float vel_x_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje X
|
||||
int vel_y_ = 0.0f; // Cantidad de pixeles a desplazarse en el eje Y
|
||||
int cooldown_ = 10; // Contador durante el cual no puede disparar
|
||||
int score_ = 0; // Puntos del jugador
|
||||
float score_multiplier_ = 1.0f; // Multiplicador de puntos
|
||||
PlayerStatus status_walking_ = PlayerStatus::WALKING_STOP; // Estado del jugador al moverse
|
||||
PlayerStatus status_firing_ = PlayerStatus::FIRING_NONE; // Estado del jugador al disparar
|
||||
PlayerStatus status_playing_ = PlayerStatus::WAITING; // Estado del jugador en el juego
|
||||
bool invulnerable_ = true; // Indica si el jugador es invulnerable
|
||||
int invulnerable_counter_ = INVULNERABLE_COUNTER_; // Contador para la invulnerabilidad
|
||||
bool extra_hit_ = false; // Indica si el jugador tiene un toque extra
|
||||
int coffees_ = 0; // Indica cuantos cafes lleva acumulados
|
||||
bool power_up_ = false; // Indica si el jugador tiene activo el modo PowerUp
|
||||
int power_up_counter_ = POWERUP_COUNTER_; // Temporizador para el modo PowerUp
|
||||
int power_up_desp_x_ = 0; // Desplazamiento del sprite de PowerUp respecto al sprite del jugador
|
||||
Circle collider_ = Circle(0, 0, 9); // Circulo de colisión del jugador
|
||||
int continue_counter_ = 10; // Contador para poder continuar
|
||||
Uint32 continue_ticks_ = 0; // Variable para poder cambiar el contador de continue en función del tiempo
|
||||
int scoreboard_panel_ = 0; // Panel del marcador asociado al jugador
|
||||
std::string name_; // Nombre del jugador
|
||||
std::string record_name_; // Nombre del jugador para la tabla de mejores puntuaciones
|
||||
int controller_index_ = 0; // Indice del array de mandos que utilizará para moverse
|
||||
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_ = 0; // 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
|
||||
void shiftColliders();
|
||||
@@ -113,7 +114,7 @@ private:
|
||||
|
||||
public:
|
||||
// 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
|
||||
~Player() = default;
|
||||
@@ -256,12 +257,6 @@ public:
|
||||
// Quita el toque extra al jugador
|
||||
void removeExtraHit();
|
||||
|
||||
// Habilita la entrada de ordenes
|
||||
void enableInput();
|
||||
|
||||
// Deshabilita la entrada de ordenes
|
||||
void disableInput();
|
||||
|
||||
// Devuelve el número de cafes actuales
|
||||
int getCoffees() const;
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#include <algorithm>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include "resource.h"
|
||||
#include "asset.h"
|
||||
@@ -51,13 +53,14 @@ Resource::~Resource()
|
||||
// Obtiene el sonido a partir de un nombre
|
||||
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 s.sound;
|
||||
}
|
||||
return it->sound;
|
||||
}
|
||||
|
||||
std::cerr << "Error: Sonido no encontrado " << name << std::endl;
|
||||
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
|
||||
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 m.music;
|
||||
}
|
||||
return it->music;
|
||||
}
|
||||
|
||||
std::cerr << "Error: Música no encontrada " << name << std::endl;
|
||||
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
|
||||
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 t.texture;
|
||||
}
|
||||
return it->texture;
|
||||
}
|
||||
|
||||
std::cerr << "Error: Imagen no encontrada " << name << std::endl;
|
||||
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
|
||||
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 t.text_file;
|
||||
}
|
||||
return it->text_file;
|
||||
}
|
||||
|
||||
std::cerr << "Error: TextFile no encontrado " << name << std::endl;
|
||||
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
|
||||
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 a.animation;
|
||||
}
|
||||
return it->animation;
|
||||
}
|
||||
|
||||
std::cerr << "Error: Animación no encontrada " << name << std::endl;
|
||||
throw std::runtime_error("Animación no encontrada: " + name);
|
||||
}
|
||||
@@ -128,19 +135,12 @@ DemoData &Resource::getDemoData(int index)
|
||||
void Resource::loadSounds()
|
||||
{
|
||||
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);
|
||||
sounds_.clear();
|
||||
|
||||
for (const auto &l : list)
|
||||
{
|
||||
// Encuentra el último índice de '/'
|
||||
auto last_index = l.find_last_of('/') + 1;
|
||||
|
||||
// Obtiene la subcadena desde el último '/'
|
||||
auto name = l.substr(last_index);
|
||||
|
||||
auto name = getFileName(l);
|
||||
sounds_.emplace_back(ResourceSound(name, JA_LoadSound(l.c_str())));
|
||||
printWithDots("Sound : ", name, "[ LOADED ]");
|
||||
}
|
||||
@@ -150,19 +150,12 @@ void Resource::loadSounds()
|
||||
void Resource::loadMusics()
|
||||
{
|
||||
std::cout << "\n>> MUSIC FILES" << std::endl;
|
||||
|
||||
// Obtiene la lista con las rutas a los ficheros musicales
|
||||
auto list = Asset::get()->getListByType(AssetType::MUSIC);
|
||||
musics_.clear();
|
||||
|
||||
for (const auto &l : list)
|
||||
{
|
||||
// Encuentra el último índice de '/'
|
||||
auto last_index = l.find_last_of('/') + 1;
|
||||
|
||||
// Obtiene la subcadena desde el último '/'
|
||||
auto name = l.substr(last_index);
|
||||
|
||||
auto name = getFileName(l);
|
||||
musics_.emplace_back(ResourceMusic(name, JA_LoadMusic(l.c_str())));
|
||||
printWithDots("Music : ", name, "[ LOADED ]");
|
||||
}
|
||||
@@ -172,19 +165,12 @@ void Resource::loadMusics()
|
||||
void Resource::loadTextures()
|
||||
{
|
||||
std::cout << "\n>> TEXTURES" << std::endl;
|
||||
|
||||
// Obtiene la lista con las rutas a los ficheros png
|
||||
auto list = Asset::get()->getListByType(AssetType::BITMAP);
|
||||
textures_.clear();
|
||||
|
||||
for (const auto &l : list)
|
||||
{
|
||||
// Encuentra el último índice de '/'
|
||||
auto last_index = l.find_last_of('/') + 1;
|
||||
|
||||
// Obtiene la subcadena desde el último '/'
|
||||
auto name = l.substr(last_index);
|
||||
|
||||
auto name = getFileName(l);
|
||||
textures_.emplace_back(ResourceTexture(name, std::make_shared<Texture>(Screen::get()->getRenderer(), l)));
|
||||
}
|
||||
}
|
||||
@@ -193,18 +179,12 @@ void Resource::loadTextures()
|
||||
void Resource::loadTextFiles()
|
||||
{
|
||||
std::cout << "\n>> TEXT FILES" << std::endl;
|
||||
// Obtiene la lista con las rutas a los ficheros png
|
||||
auto list = Asset::get()->getListByType(AssetType::FONT);
|
||||
text_files_.clear();
|
||||
|
||||
for (const auto &l : list)
|
||||
{
|
||||
// Encuentra el último índice de '/'
|
||||
auto last_index = l.find_last_of('/') + 1;
|
||||
|
||||
// Obtiene la subcadena desde el último '/'
|
||||
auto name = l.substr(last_index);
|
||||
|
||||
auto name = getFileName(l);
|
||||
text_files_.emplace_back(ResourceTextFile(name, loadTextFile(l)));
|
||||
}
|
||||
}
|
||||
@@ -213,18 +193,12 @@ void Resource::loadTextFiles()
|
||||
void Resource::loadAnimations()
|
||||
{
|
||||
std::cout << "\n>> ANIMATIONS" << std::endl;
|
||||
// Obtiene la lista con las rutas a los ficheros ani
|
||||
auto list = Asset::get()->getListByType(AssetType::ANIMATION);
|
||||
animations_.clear();
|
||||
|
||||
for (const auto &l : list)
|
||||
{
|
||||
// Encuentra el último índice de '/'
|
||||
auto last_index = l.find_last_of('/') + 1;
|
||||
|
||||
// Obtiene la subcadena desde el último '/'
|
||||
auto name = l.substr(last_index);
|
||||
|
||||
auto name = getFileName(l);
|
||||
animations_.emplace_back(ResourceAnimation(name, loadAnimationsFromFile(l)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ struct ResourceAnimation
|
||||
Animations animation; // Objeto con las animaciones
|
||||
|
||||
// Constructor
|
||||
ResourceAnimation(const std::string &name, Animations animation)
|
||||
ResourceAnimation(const std::string &name, const Animations &animation)
|
||||
: name(name), animation(animation) {}
|
||||
};
|
||||
|
||||
|
||||
@@ -37,19 +37,9 @@ Scoreboard *Scoreboard::get()
|
||||
// Constructor
|
||||
Scoreboard::Scoreboard()
|
||||
: renderer_(Screen::get()->getRenderer()),
|
||||
|
||||
game_power_meter_texture_(Resource::get()->getTexture("game_power_meter.png")),
|
||||
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"))),
|
||||
|
||||
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)
|
||||
text_scoreboard_(std::make_unique<Text>(Resource::get()->getTexture("8bithud.png"), Resource::get()->getTextFile("8bithud.txt")))
|
||||
{
|
||||
// Inicializa variables
|
||||
for (int i = 0; i < SCOREBOARD_MAX_PANELS; ++i)
|
||||
@@ -108,7 +98,9 @@ std::string Scoreboard::updateScoreText(int num)
|
||||
// Actualiza el contador
|
||||
void Scoreboard::updateCounter()
|
||||
{
|
||||
if (SDL_GetTicks() - ticks_ > SCOREBOARD_TICK_SPEED_)
|
||||
constexpr int TICKS_SPEED = 100;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
ticks_ = SDL_GetTicks();
|
||||
counter_++;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <SDL2/SDL_rect.h> // for SDL_Point, SDL_Rect
|
||||
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
|
||||
#include <SDL2/SDL_stdinc.h> // for Uint32
|
||||
#include <SDL2/SDL_timer.h> // for SDL_GetTicks
|
||||
#include <memory> // for unique_ptr, shared_ptr
|
||||
#include <string> // for string
|
||||
#include <vector> // for vector
|
||||
@@ -41,9 +42,6 @@ struct Panel
|
||||
class Scoreboard
|
||||
{
|
||||
private:
|
||||
// Constantes
|
||||
static constexpr int SCOREBOARD_TICK_SPEED_ = 100;
|
||||
|
||||
// [SINGLETON] Objeto scoreboard privado para Don Melitón
|
||||
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<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
|
||||
|
||||
// Variables
|
||||
std::string name_[SCOREBOARD_MAX_PANELS]; // Nom de cada jugador
|
||||
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 score_[SCOREBOARD_MAX_PANELS]; // Puntuación de los jugadores
|
||||
float mult_[SCOREBOARD_MAX_PANELS]; // Multiplicador 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
|
||||
int stage_; // Número de fase actual
|
||||
int hi_score_; // Máxima puntuación
|
||||
float power_; // Poder actual de la fase
|
||||
std::string hi_score_name_; // Nombre del jugador con la máxima puntuación
|
||||
Color color_; // Color del marcador
|
||||
SDL_Rect rect_; // Posición y dimensiones del marcador
|
||||
Uint32 ticks_; // Variable donde almacenar el valor de SDL_GetTiks()
|
||||
int counter_; // Contador
|
||||
std::string name_[SCOREBOARD_MAX_PANELS] = {}; // Nom de cada jugador
|
||||
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 score_[SCOREBOARD_MAX_PANELS] = {}; // Puntuación de los jugadores
|
||||
float mult_[SCOREBOARD_MAX_PANELS] = {}; // Multiplicador 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
|
||||
int stage_ = 1; // Número de fase actual
|
||||
int hi_score_ = 0; // Máxima puntuación
|
||||
float power_ = 0; // Poder actual de la fase
|
||||
std::string hi_score_name_ = std::string(); // Nombre del jugador con la máxima puntuación
|
||||
Color color_ = Color(); // Color del marcador
|
||||
SDL_Rect rect_ = {0, 0, 320, 40}; // Posición y dimensiones del marcador
|
||||
Uint32 ticks_ = SDL_GetTicks(); // Variable donde almacenar el valor de SDL_GetTiks()
|
||||
int counter_ = 0; // Contador
|
||||
|
||||
// Puntos predefinidos para colocar elementos en los paneles
|
||||
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)),
|
||||
|
||||
src_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
|
||||
dst_rect_({0, 0, param.game.width, param.game.height})
|
||||
{
|
||||
// Inicializa variables
|
||||
flash_effect_.enabled = false;
|
||||
flash_effect_.counter = 0;
|
||||
flash_effect_.lenght = 0;
|
||||
flash_effect_.color = {0xFF, 0xFF, 0xFF};
|
||||
flash_effect_.color = Color(0xFF, 0xFF, 0xFF);
|
||||
shake_effect_.enabled = false;
|
||||
shake_effect_.desp = 2;
|
||||
shake_effect_.delay = 3;
|
||||
@@ -480,7 +470,9 @@ void Screen::displayInfo()
|
||||
// Resolution
|
||||
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
|
||||
|
||||
// Variables
|
||||
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
|
||||
Color border_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
|
||||
Uint32 fps_ticks_; // Ticks para contar los frames por segundo
|
||||
int fps_counter_; // Contador de frames por 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
|
||||
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
|
||||
Color border_color_ = Color(); // Color del borde añadido a la textura de juego para rellenar la pantalla
|
||||
bool attenuate_effect_ = false; // Indica si la pantalla ha de estar atenuada
|
||||
Uint32 fps_ticks_ = 0; // Ticks para contar los frames por segundo
|
||||
int fps_counter_ = 0; // Contador de frames por segundo
|
||||
int fps_; // Frames calculados en el último segundo
|
||||
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
|
||||
{
|
||||
@@ -111,7 +115,7 @@ public:
|
||||
void checkInput();
|
||||
|
||||
// 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
|
||||
void start();
|
||||
|
||||
@@ -3,20 +3,7 @@ class Texture;
|
||||
|
||||
// Constructor
|
||||
SmartSprite::SmartSprite(std::shared_ptr<Texture> 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;
|
||||
}
|
||||
: AnimatedSprite(texture) {}
|
||||
|
||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void SmartSprite::update()
|
||||
|
||||
@@ -9,12 +9,12 @@ class SmartSprite : public AnimatedSprite
|
||||
{
|
||||
private:
|
||||
// Variables
|
||||
bool on_destination_; // Indica si está en el destino
|
||||
int dest_x_; // Posicion de destino en el eje X
|
||||
int dest_y_; // Posicion de destino en el eje Y
|
||||
int finished_counter_; // Contador para deshabilitarlo
|
||||
bool finished_; // Indica si ya ha terminado
|
||||
bool enabled_; // Indica si el objeto está habilitado
|
||||
bool on_destination_ = false; // Indica si está en el destino
|
||||
int dest_x_ = 0; // Posicion de destino en el eje X
|
||||
int dest_y_ = 0; // Posicion de destino en el eje Y
|
||||
int finished_counter_ = 0; // Contador para deshabilitarlo
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
|
||||
// Comprueba si ha terminado
|
||||
void checkFinished();
|
||||
@@ -29,9 +29,6 @@ public:
|
||||
// Destructor
|
||||
~SmartSprite() = default;
|
||||
|
||||
// Inicializa el objeto
|
||||
void init();
|
||||
|
||||
// Actualiza la posición y comprueba si ha llegado a su destino
|
||||
void update() override;
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
if (file.is_open() && file.good())
|
||||
@@ -56,15 +55,15 @@ std::shared_ptr<TextFile> loadTextFile(const std::string &file_path)
|
||||
};
|
||||
|
||||
// Cierra el fichero
|
||||
printWithDots("Text File : ", file_name, "[ LOADED ]");
|
||||
printWithDots("Text File : ", getFileName(file_path), "[ LOADED ]");
|
||||
file.close();
|
||||
}
|
||||
|
||||
// El fichero no se puede abrir
|
||||
else
|
||||
{
|
||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||
}
|
||||
|
||||
// Establece las coordenadas para cada caracter ascii de la cadena y su ancho
|
||||
|
||||
@@ -33,13 +33,13 @@ class Text
|
||||
{
|
||||
private:
|
||||
// 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
|
||||
int box_width_; // Anchura de la caja de cada caracter en el png
|
||||
int box_height_; // 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
|
||||
TextOffset offset_[128]; // Vector con las posiciones y ancho de cada letra
|
||||
int box_width_ = 0; // Anchura 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_ = 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
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
|
||||
@@ -15,13 +15,8 @@
|
||||
|
||||
// Constructor
|
||||
Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
||||
: texture_(nullptr),
|
||||
renderer_(renderer),
|
||||
surface_(nullptr),
|
||||
width_(0),
|
||||
height_(0),
|
||||
path_(path),
|
||||
current_palette_(0)
|
||||
: renderer_(renderer),
|
||||
path_(path)
|
||||
{
|
||||
// Carga el fichero en la textura
|
||||
if (!path_.empty())
|
||||
@@ -40,10 +35,10 @@ Texture::Texture(SDL_Renderer *renderer, const std::string &path)
|
||||
{
|
||||
// Crea la surface desde un fichero
|
||||
surface_ = loadSurface(path_);
|
||||
|
||||
|
||||
// Añade la propia paleta del fichero a la lista
|
||||
addPaletteFromFile(path_);
|
||||
//setPaletteColor(0, 0, 0x00000000);
|
||||
addPaletteFromFile(path_);
|
||||
// setPaletteColor(0, 0, 0x00000000);
|
||||
|
||||
// Crea la textura, establece el BlendMode y copia la surface a la textura
|
||||
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);
|
||||
if (!data)
|
||||
{
|
||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||
}
|
||||
else
|
||||
{
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
printWithDots("Image : ", file_name, "[ LOADED ]");
|
||||
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||
}
|
||||
|
||||
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");
|
||||
if (!f)
|
||||
{
|
||||
std::cerr << "Error: Fichero no encontrado " << file_path << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + file_path);
|
||||
std::cerr << "Error: Fichero no encontrado " << getFileName(file_path) << std::endl;
|
||||
throw std::runtime_error("Fichero no encontrado: " + getFileName(file_path));
|
||||
}
|
||||
else
|
||||
{
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
printWithDots("Image : ", file_name, "[ LOADED ]");
|
||||
printWithDots("Image : ", getFileName(file_path), "[ LOADED ]");
|
||||
}
|
||||
|
||||
fseek(f, 0, SEEK_END);
|
||||
|
||||
@@ -24,16 +24,16 @@ class Texture
|
||||
{
|
||||
private:
|
||||
// Objetos y punteros
|
||||
SDL_Texture *texture_; // La textura
|
||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||
std::shared_ptr<Surface> surface_; // Surface para usar imagenes en formato gif con paleta
|
||||
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
|
||||
SDL_Texture *texture_ = nullptr; // La textura
|
||||
std::shared_ptr<Surface> surface_ = nullptr; // Surface para usar imagenes en formato gif con paleta
|
||||
|
||||
// Variables
|
||||
int width_; // Ancho de la imagen
|
||||
int height_; // Alto de la imagen
|
||||
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
|
||||
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
|
||||
std::shared_ptr<Surface> loadSurface(const std::string &file_name);
|
||||
|
||||
@@ -12,7 +12,9 @@
|
||||
TiledBG::TiledBG(SDL_Rect pos, TiledBGMode mode)
|
||||
: renderer_(Screen::get()->getRenderer()),
|
||||
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)
|
||||
{
|
||||
// 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
|
||||
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
|
||||
for (int i = 0; i < 360; ++i)
|
||||
{
|
||||
|
||||
@@ -29,12 +29,12 @@ private:
|
||||
|
||||
// Objetos y punteros
|
||||
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
|
||||
|
||||
// Variables
|
||||
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
|
||||
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_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_))),
|
||||
counter_(0),
|
||||
ticks_(0),
|
||||
demo_(true),
|
||||
next_section_(section::Name::GAME),
|
||||
post_fade_(0),
|
||||
num_controllers_(Input::get()->getNumControllers())
|
||||
{
|
||||
// Configura objetos
|
||||
@@ -59,8 +54,9 @@ Title::~Title()
|
||||
// Actualiza las variables del objeto
|
||||
void Title::update()
|
||||
{
|
||||
// Calcula la lógica de los objetos
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED_)
|
||||
constexpr int TICKS_SPEED = 15;
|
||||
|
||||
if (SDL_GetTicks() - ticks_ > TICKS_SPEED)
|
||||
{
|
||||
// Actualiza el contador de ticks_
|
||||
ticks_ = SDL_GetTicks();
|
||||
@@ -138,7 +134,7 @@ void Title::render()
|
||||
|
||||
if (section::options == section::Options::TITLE_2)
|
||||
{
|
||||
constexpr Color shadow = {0x14, 0x87, 0xc4};
|
||||
constexpr Color shadow = Color(0x14, 0x87, 0xc4);
|
||||
|
||||
// 'PRESS TO PLAY'
|
||||
if (counter_ % 50 > 14 && !define_buttons_->isEnabled())
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include "text.h" // for Text
|
||||
#include "tiled_bg.h" // for TiledBG
|
||||
class Input; // lines 17-17
|
||||
#include "section.h" // for Options, options, Name, name
|
||||
class Screen; // lines 18-18
|
||||
class Texture; // lines 20-20
|
||||
namespace section
|
||||
@@ -42,27 +43,23 @@ constexpr bool ALLOW_TITLE_ANIMATION_SKIP = true;
|
||||
class Title
|
||||
{
|
||||
private:
|
||||
// Constantes
|
||||
static constexpr Uint32 TICKS_SPEED_ = 15; // Velocidad a la que se repiten los bucles del programa
|
||||
|
||||
// Objetos y punteros
|
||||
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<Fade> fade_; // Objeto para realizar fundidos 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<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<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::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
|
||||
|
||||
|
||||
// Variable
|
||||
int counter_; // Temporizador para la pantalla de titulo
|
||||
Uint32 ticks_; // Contador de ticks para ajustar la velocidad del programa
|
||||
bool demo_; // 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
|
||||
int post_fade_; // Opción a realizar cuando termina el fundido
|
||||
int num_controllers_; // Número de mandos conectados
|
||||
int counter_ = 0; // Temporizador para la pantalla de titulo
|
||||
Uint32 ticks_ = 0; // Contador de ticks para ajustar la velocidad del programa
|
||||
bool demo_ = true; // Indica si el modo demo estará activo
|
||||
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_ = 0; // Opción a realizar cuando termina el fundido
|
||||
int num_controllers_; // Número de mandos conectados
|
||||
|
||||
// Actualiza las variables del objeto
|
||||
void update();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
#include "utils.h"
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <algorithm> // for min, clamp, find_if_not, transform
|
||||
@@ -8,18 +9,20 @@
|
||||
struct JA_Music_t; // lines 7-7
|
||||
struct JA_Sound_t; // lines 8-8
|
||||
|
||||
// Variables
|
||||
Overrides overrides = Overrides();
|
||||
|
||||
// Colores
|
||||
const Color bg_color = {0x27, 0x27, 0x36};
|
||||
const Color no_color = {0xFF, 0xFF, 0xFF};
|
||||
const Color shdw_txt_color = {0x43, 0x43, 0x4F};
|
||||
const Color separator_color = {0x0D, 0x1A, 0x2B};
|
||||
const Color scoreboard_color = {0x2E, 0x3F, 0x47};
|
||||
const Color difficulty_easy_color = {0x4B, 0x69, 0x2F};
|
||||
const Color difficulty_normal_color = {0xFF, 0x7A, 0x00};
|
||||
const Color difficulty_hard_color = {0x76, 0x42, 0x8A};
|
||||
const Color flash_color = {0xFF, 0xFF, 0xFF};
|
||||
const Color fade_color = {0x27, 0x27, 0x36};
|
||||
const Color orange_color = {0xFF, 0x7A, 0x00};
|
||||
const Color bg_color = Color(0x27, 0x27, 0x36);
|
||||
const Color no_color = Color(0xFF, 0xFF, 0xFF);
|
||||
const Color shdw_txt_color = Color(0x43, 0x43, 0x4F);
|
||||
const Color separator_color = Color(0x0D, 0x1A, 0x2B);
|
||||
const Color scoreboard_easy_color = Color(0x4B, 0x69, 0x2F);
|
||||
const Color scoreboard_normal_color = Color(0x2E, 0x3F, 0x47);
|
||||
const Color scoreboard_hard_color = Color(0x76, 0x42, 0x8A);
|
||||
const Color flash_color = Color(0xFF, 0xFF, 0xFF);
|
||||
const Color fade_color = Color(0x27, 0x27, 0x36);
|
||||
const Color orange_color = Color(0xFF, 0x7A, 0x00);
|
||||
|
||||
// Calcula el cuadrado de la distancia entre dos puntos
|
||||
double distanceSquared(int x1, int y1, int x2, int y2)
|
||||
@@ -218,8 +221,7 @@ DemoData loadDemoDataFromFile(const std::string &file_path)
|
||||
}
|
||||
else
|
||||
{
|
||||
const std::string file_name = file_path.substr(file_path.find_last_of("\\/") + 1);
|
||||
printWithDots("DemoData : ", file_name, "[ LOADED ]");
|
||||
printWithDots("DemoData : ", getFileName(file_path), "[ LOADED ]");
|
||||
|
||||
// Lee todos los datos del fichero y los deja en el destino
|
||||
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)
|
||||
{
|
||||
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");
|
||||
|
||||
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)
|
||||
{
|
||||
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;
|
||||
break;
|
||||
}
|
||||
}
|
||||
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
|
||||
SDL_RWclose(file);
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
// 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
|
||||
struct Circle
|
||||
{
|
||||
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
|
||||
struct Color
|
||||
{
|
||||
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
|
||||
@@ -57,6 +79,10 @@ struct HiScoreEntry
|
||||
{
|
||||
std::string name; // Nombre
|
||||
int score; // Puntuación
|
||||
|
||||
// Constructor
|
||||
explicit HiScoreEntry(const std::string &n = "", int s = 0)
|
||||
: name(n), score(s) {}
|
||||
};
|
||||
|
||||
struct DemoKeys
|
||||
@@ -69,7 +95,7 @@ struct DemoKeys
|
||||
Uint8 fire_right;
|
||||
|
||||
// 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) {}
|
||||
};
|
||||
|
||||
@@ -82,6 +108,14 @@ struct Demo
|
||||
int counter; // Contador para el 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
|
||||
|
||||
// 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
|
||||
@@ -289,15 +323,20 @@ DemoData loadDemoDataFromFile(const std::string &file_path);
|
||||
bool saveDemoFile(const std::string &file_path, const DemoData &dd);
|
||||
#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
|
||||
extern const Color bg_color;
|
||||
extern const Color no_color;
|
||||
extern const Color shdw_txt_color;
|
||||
extern const Color separator_color;
|
||||
extern const Color scoreboard_color;
|
||||
extern const Color difficulty_easy_color;
|
||||
extern const Color difficulty_normal_color;
|
||||
extern const Color difficulty_hard_color;
|
||||
extern const Color scoreboard_easy_color;
|
||||
extern const Color scoreboard_normal_color;
|
||||
extern const Color scoreboard_hard_color;
|
||||
extern const Color flash_color;
|
||||
extern const Color fade_color;
|
||||
extern const Color orange_color;
|
||||
@@ -1,22 +1,6 @@
|
||||
#include "writer.h"
|
||||
#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
|
||||
void Writer::update()
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory> // for shared_ptr
|
||||
#include <string> // for string
|
||||
#include <memory> // for shared_ptr
|
||||
#include <string> // for string
|
||||
class 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
|
||||
|
||||
// Variables
|
||||
int pos_x_; // 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 kerning_; // Kerning del texto, es decir, espaciado entre caracteres
|
||||
std::string caption_; // El texto para escribir
|
||||
int speed_; // Velocidad de escritura
|
||||
int writing_counter_; // Temporizador de escritura para cada caracter
|
||||
int index_; // Posición del texto que se está escribiendo
|
||||
int lenght_; // Longitud de la cadena a escribir
|
||||
bool completed_; // Indica si se ha escrito todo el texto
|
||||
bool enabled_; // Indica si el objeto está habilitado
|
||||
int enabled_counter_; // Temporizador para deshabilitar el objeto
|
||||
bool finished_; // Indica si ya ha terminado
|
||||
int pos_x_ = 0; // Posicion en el eje X donde empezar a escribir el texto
|
||||
int pos_y_ = 0; // Posicion en el eje Y donde empezar a escribir el texto
|
||||
int kerning_ = 0; // Kerning del texto, es decir, espaciado entre caracteres
|
||||
std::string caption_ = std::string(); // El texto para escribir
|
||||
int speed_ = 0; // Velocidad de escritura
|
||||
int writing_counter_ = 0; // Temporizador de escritura para cada caracter
|
||||
int index_ = 0; // Posición del texto que se está escribiendo
|
||||
int lenght_ = 0; // Longitud de la cadena a escribir
|
||||
bool completed_ = false; // Indica si se ha escrito todo el texto
|
||||
bool enabled_ = false; // Indica si el objeto está habilitado
|
||||
int enabled_counter_ = 0; // Temporizador para deshabilitar el objeto
|
||||
bool finished_ = false; // Indica si ya ha terminado
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
explicit Writer(std::shared_ptr<Text> text);
|
||||
explicit Writer(std::shared_ptr<Text> text)
|
||||
: text_(text) {}
|
||||
|
||||
// Destructor
|
||||
~Writer() = default;
|
||||
|
||||