Compare commits

...

5 Commits

14 changed files with 165 additions and 299 deletions

View File

@@ -1,3 +0,0 @@
#!/bin/bash
valgrind --suppressions=valgrind_exceptions --leak-check=full ~/coffee_crisis_arcade_edition/coffee_crisis_arcade_edition_debug > ~/coffee_crisis_arcade_edition/debug.txt 2>&1

View File

View File

@@ -5,6 +5,6 @@ SOURCEPATH=../source/
for i in "$SOURCEPATH"/*.cpp
do
include-what-you-use -D DEBUG -D VERBOSE -std=c++20 -Wall "$i"
read -p "Presiona cualquier tecla para continuar..."
read -r -p "Presiona cualquier tecla para continuar..."
clear
done

View File

@@ -0,0 +1,14 @@
#!/bin/bash
# warning,style,performance
#cppcheck --force --enable=warning,style,performance --std=c++20 \
# --suppressions-list=/home/sergio/gitea/coffee_crisis_arcade_edition/linux-utils/cppcheck_suppressions \
# /home/sergio/gitea/coffee_crisis_arcade_edition/source/ \
# 2>/home/sergio/cppcheck-result-warning-style-performance
# all
cppcheck --force --enable=all -I /usr/include --std=c++20 \
--suppress=missingIncludeSystem \
--suppressions-list=/home/sergio/gitea/coffee_crisis_arcade_edition/linux-utils/cppcheck_suppressions \
/home/sergio/gitea/coffee_crisis_arcade_edition/source/ \
2>/home/sergio/cppcheck-result-all

View File

@@ -0,0 +1,4 @@
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/stb*
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/gif.c
*:/home/sergio/gitea/coffee_crisis_arcade_edition/source/jail*
*:/usr/include/*

View File

View File

@@ -0,0 +1,6 @@
#!/bin/bash
valgrind --suppressions=valgrind_exceptions \
--leak-check=full \
~/coffee_crisis_arcade_edition/coffee_crisis_arcade_edition_debug \
> ~/coffee_crisis_arcade_edition/debug.txt 2>&1

View File

@@ -8,9 +8,8 @@
#include "utils.h"
// Carga las animaciones en un vector(Animations) desde un fichero
Animations loadAnimationsFromFile(const std::string &file_path)
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path)
{
std::vector<std::string> buffer;
std::ifstream file(file_path);
if (!file)
{
@@ -18,12 +17,14 @@ Animations loadAnimationsFromFile(const std::string &file_path)
throw std::runtime_error("Fichero no encontrado: " + file_path);
}
std::string line;
printWithDots("Animation : ", file_path.substr(file_path.find_last_of("\\/") + 1), "[ LOADED ]");
std::vector<std::string> buffer;
std::string line;
while (std::getline(file, line))
{
buffer.push_back(line);
if (!line.empty())
buffer.push_back(line);
}
return buffer;
@@ -31,30 +32,25 @@ Animations loadAnimationsFromFile(const std::string &file_path)
// Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path)
: MovingSprite(texture),
current_animation_(0)
: MovingSprite(texture)
{
// Carga las animaciones
if (!file_path.empty())
{
animations_ = loadFromFile(file_path);
}
}
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const Animations &animations)
: MovingSprite(texture),
current_animation_(0)
{
if (!animations.empty())
{
loadFromVector(animations);
AnimationsFileBuffer v = loadAnimationsFromFile(file_path);
loadFromAnimationsFileBuffer(v);
}
}
// Constructor
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture)
: MovingSprite(texture),
current_animation_(0) {}
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations)
: MovingSprite(texture)
{
if (!animations.empty())
{
loadFromAnimationsFileBuffer(animations);
}
}
// Obtiene el indice de la animación a partir del nombre
int AnimatedSprite::getIndex(const std::string &name)
@@ -249,255 +245,91 @@ void AnimatedSprite::resetAnimation()
animations_[current_animation_].completed = false;
}
// Carga la animación desde un fichero
std::vector<Animation> AnimatedSprite::loadFromFile(const std::string &file_path)
// Carga la animación desde un vector de cadenas
void AnimatedSprite::loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source)
{
// Inicializa variables
std::vector<Animation> animations;
auto frame_width = 1;
auto frame_height = 1;
int frame_width = 1;
int frame_height = 1;
int frames_per_row = 1;
int max_tiles = 1;
std::ifstream file(file_path);
std::string line;
// El fichero se puede abrir
if (file.good())
size_t index = 0;
while (index < source.size())
{
// Procesa el fichero linea a linea
std::cout << "Animation loaded: " << getFileName(file_path) << std::endl;
while (std::getline(file, line))
std::string line = source.at(index);
// Parsea el fichero para buscar variables y valores
if (line != "[animation]")
{
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]")
// Encuentra la posición del caracter '='
size_t pos = line.find("=");
// Procesa las dos subcadenas
if (pos != std::string::npos)
{
Animation animation = Animation();
std::string key = line.substr(0, pos);
int value = std::stoi(line.substr(pos + 1));
if (key == "frame_width")
frame_width = value;
else if (key == "frame_height")
frame_height = value;
else
std::cout << "Warning: unknown parameter " << key << std::endl;
do
{
std::getline(file, line);
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != static_cast<int>(line.npos))
{
if (line.substr(0, pos) == "name")
{
animation.name = line.substr(pos + 1, line.length());
}
else if (line.substr(0, pos) == "speed")
{
animation.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
animation.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const auto num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
animation.frames.push_back(rect);
}
}
else
{
std::cout << "Warning: file " << getFileName(file_path).c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animations.push_back(animation);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
if (line != "[animation]")
{
// Encuentra la posición del caracter '='
size_t pos = line.find("=");
// Procesa las dos subcadenas
if (pos != line.npos)
{
if (line.substr(0, pos) == "frame_width")
{
frame_width = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_height")
{
frame_height = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
std::cout << "Warning: file " << getFileName(file_path) << "\n, unknown parameter \"" << line.substr(0, pos) << "\"" << std::endl;
}
frames_per_row = texture_->getWidth() / frame_width;
const auto w = texture_->getWidth() / frame_width;
const auto h = texture_->getHeight() / frame_height;
max_tiles = w * h;
}
frames_per_row = texture_->getWidth() / frame_width;
const int w = texture_->getWidth() / frame_width;
const int h = texture_->getHeight() / frame_height;
max_tiles = w * h;
}
}
// Cierra el fichero
file.close();
}
// El fichero no se puede abrir
else
{
std::cout << "Warning: Unable to open " << getFileName(file_path).c_str() << " file" << std::endl;
}
// Pone un valor por defecto
setWidth(frame_width);
setHeight(frame_height);
return animations;
}
// Carga la animación desde un vector
bool AnimatedSprite::loadFromVector(const Animations &source)
{
// Inicializa variables
auto frames_per_row = 0;
auto frame_width = 0;
auto frame_height = 0;
auto max_tiles = 0;
// Indicador de éxito en el proceso
auto success = true;
std::string line;
// Recorre todo el vector
auto index = 0;
while (index < (int)source.size())
{
// Lee desde el vector
line = source.at(index);
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
Animation animation = Animation();
Animation animation;
do
{
// Aumenta el indice para leer la siguiente linea
index++;
line = source.at(index);
size_t pos = line.find("=");
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != static_cast<int>(line.npos))
if (pos != std::string::npos)
{
if (line.substr(0, pos) == "name")
{
animation.name = line.substr(pos + 1, line.length());
}
std::string key = line.substr(0, pos);
std::string value = line.substr(pos + 1);
else if (line.substr(0, pos) == "speed")
{
animation.speed = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "loop")
{
animation.loop = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frames")
if (key == "name")
animation.name = value;
else if (key == "speed")
animation.speed = std::stoi(value);
else if (key == "loop")
animation.loop = std::stoi(value);
else if (key == "frames")
{
// Se introducen los valores separados por comas en un vector
std::stringstream ss(line.substr(pos + 1, line.length()));
std::stringstream ss(value);
std::string tmp;
SDL_Rect rect = {0, 0, frame_width, frame_height};
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int num_tile = std::stoi(tmp) > max_tiles ? 0 : std::stoi(tmp);
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
animation.frames.push_back(rect);
const int num_tile = std::stoi(tmp);
if (num_tile <= max_tiles)
{
rect.x = (num_tile % frames_per_row) * frame_width;
rect.y = (num_tile / frames_per_row) * frame_height;
animation.frames.emplace_back(rect);
}
}
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
std::cout << "Warning: unknown parameter " << key << std::endl;
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animations_.push_back(animation);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
else
{
// Encuentra la posición del caracter '='
int pos = line.find("=");
// Procesa las dos subcadenas
if (pos != (int)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")
{
frame_width = std::stoi(line.substr(pos + 1, line.length()));
}
else if (line.substr(0, pos) == "frame_height")
{
frame_height = std::stoi(line.substr(pos + 1, line.length()));
}
else
{
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
success = false;
}
// Normaliza valores
if (frames_per_row == 0 && frame_width > 0)
{
frames_per_row = texture_->getWidth() / frame_width;
}
if (max_tiles == 0 && frame_width > 0 && frame_height > 0)
{
const int w = texture_->getWidth() / frame_width;
const int h = texture_->getHeight() / frame_height;
max_tiles = w * h;
}
}
animations_.emplace_back(animation);
}
// Una vez procesada la linea, aumenta el indice para pasar a la siguiente
@@ -507,6 +339,4 @@ bool AnimatedSprite::loadFromVector(const Animations &source)
// Pone un valor por defecto
setWidth(frame_width);
setHeight(frame_height);
return success;
}

View File

@@ -21,32 +21,30 @@ struct Animation
Animation() : name(std::string()), speed(5), loop(0), completed(false), current_frame(0), counter(0) {}
};
using Animations = std::vector<std::string>;
using AnimationsFileBuffer = std::vector<std::string>;
// Carga las animaciones en un vector(Animations) desde un fichero
Animations loadAnimationsFromFile(const std::string &file_path);
AnimationsFileBuffer loadAnimationsFromFile(const std::string &file_path);
class AnimatedSprite : public MovingSprite
{
protected:
// Variables
std::vector<Animation> animations_; // Vector con las diferentes animaciones
int current_animation_; // Animacion activa
int current_animation_ = 0; // Animacion activa
// Calcula el frame correspondiente a la animación actual
void animate();
// Carga la animación desde un fichero
std::vector<Animation> loadFromFile(const std::string &file_path);
// Carga la animación desde un vector
bool loadFromVector(const Animations &source);
// Carga la animación desde un vector de cadenas
void loadFromAnimationsFileBuffer(const AnimationsFileBuffer &source);
public:
// Constructor
AnimatedSprite(std::shared_ptr<Texture> texture, const std::string &file_path);
AnimatedSprite(std::shared_ptr<Texture> texture, const Animations &animations);
explicit AnimatedSprite(std::shared_ptr<Texture> texture);
AnimatedSprite(std::shared_ptr<Texture> texture, const AnimationsFileBuffer &animations);
explicit AnimatedSprite(std::shared_ptr<Texture> texture)
: MovingSprite(texture) {}
// Destructor
virtual ~AnimatedSprite() = default;

View File

@@ -13,10 +13,17 @@ 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)
{
@@ -220,9 +227,23 @@ 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();
}
@@ -705,8 +726,8 @@ Circle &Balloon::getCollider()
// Alinea el circulo de colisión con la posición del objeto globo
void Balloon::updateColliders()
{
collider_.x = static_cast<int>(pos_x_ + collider_.r);
collider_.y = static_cast<int>(pos_y_ + collider_.r);
collider_.x = Uint16(pos_x_ + collider_.r);
collider_.y = pos_y_ + collider_.r;
}
// Obtiene le valor de la variable

View File

@@ -74,53 +74,49 @@ private:
// Estructura para las variables para el efecto de los rebotes
struct Bouncing
{
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() {}
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
};
// 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_ = 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
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
// Alinea el circulo de colisión con la posición del objeto globo
void updateColliders();

View File

@@ -111,7 +111,7 @@ 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)
AnimationsFileBuffer &Resource::getAnimation(const std::string &name)
{
auto it = std::find_if(animations_.begin(), animations_.end(), [&name](auto &a)
{ return a.name == name; });

View File

@@ -57,11 +57,11 @@ struct ResourceTextFile
// Estructura para almacenar ficheros animaciones y su nombre
struct ResourceAnimation
{
std::string name; // Nombre del fichero
Animations animation; // Objeto con las animaciones
std::string name; // Nombre del fichero
AnimationsFileBuffer animation; // Objeto con las animaciones
// Constructor
ResourceAnimation(const std::string &name, const Animations &animation)
ResourceAnimation(const std::string &name, const AnimationsFileBuffer &animation)
: name(name), animation(animation) {}
};
@@ -130,7 +130,7 @@ public:
std::shared_ptr<TextFile> getTextFile(const std::string &name);
// Obtiene la animación a partir de un nombre
Animations &getAnimation(const std::string &name);
AnimationsFileBuffer &getAnimation(const std::string &name);
// Obtiene el fichero con los datos para el modo demostración a partir de un çindice
DemoData &getDemoData(int index);