Commit pa que Mon arregle el codi mentre em dutxe

This commit is contained in:
2024-10-09 21:48:01 +02:00
parent 3c1dcad3ab
commit f2fa216b0d
34 changed files with 862 additions and 1218 deletions

View File

@@ -5,15 +5,15 @@
#include "texture.h" // for Texture
// Carga la animación desde un fichero
animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose)
animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath)
{
// Inicializa variables
animatedSprite_t as;
as.texture = texture;
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
auto framesPerRow = 0;
auto frameWidth = 0;
auto frameHeight = 0;
auto maxTiles = 0;
const std::string filename = filePath.substr(filePath.find_last_of("\\/") + 1);
std::ifstream file(filePath);
@@ -23,16 +23,15 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
if (file.good())
{
// Procesa el fichero linea a linea
if (verbose)
{
#ifdef VERBOSE
std::cout << "Animation loaded: " << filename << std::endl;
}
#endif
while (std::getline(file, line))
{
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
animation_t buffer;
Animation buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
@@ -71,7 +70,7 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
while (getline(ss, tmp, ','))
{
// Comprueba que el tile no sea mayor que el maximo indice permitido
const int numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
const auto numTile = std::stoi(tmp) > maxTiles ? 0 : std::stoi(tmp);
rect.x = (numTile % framesPerRow) * frameWidth;
rect.y = (numTile / framesPerRow) * frameHeight;
buffer.frames.push_back(rect);
@@ -80,7 +79,9 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
else
{
#ifdef VERBOSE
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
#endif
}
}
} while (line != "[/animation]");
@@ -115,7 +116,9 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
else
{
#ifdef VERBOSE
std::cout << "Warning: file " << filename.c_str() << "\n, unknown parameter \"" << line.substr(0, pos).c_str() << "\"" << std::endl;
#endif
}
// Normaliza valores
@@ -126,8 +129,8 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
const auto w = texture->getWidth() / frameWidth;
const auto h = texture->getHeight() / frameHeight;
maxTiles = w * h;
}
}
@@ -140,17 +143,16 @@ animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, b
// El fichero no se puede abrir
else
{
if (verbose)
{
#ifdef VERBOSE
std::cout << "Warning: Unable to open " << filename.c_str() << " file" << std::endl;
}
#endif
}
return as;
}
// Constructor
AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vector<std::string> *buffer)
AnimatedSprite::AnimatedSprite(std::shared_ptr<Texture> texture, std::string file, std::vector<std::string> *buffer)
{
// Copia los punteros
setTexture(texture);
@@ -163,7 +165,7 @@ AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vector<s
// Copia los datos de las animaciones
for (auto animation : as.animations)
{
this->animation.push_back(animation);
animations_.push_back(animation);
}
}
@@ -173,7 +175,7 @@ AnimatedSprite::AnimatedSprite(Texture *texture, std::string file, std::vector<s
}
// Inicializa variables
currentAnimation = 0;
currentAnimation_ = 0;
}
// Constructor
@@ -183,27 +185,27 @@ AnimatedSprite::AnimatedSprite(animatedSprite_t *animation)
setTexture(animation->texture);
// Inicializa variables
currentAnimation = 0;
currentAnimation_ = 0;
// Copia los datos de las animaciones
for (auto a : animation->animations)
{
this->animation.push_back(a);
animations_.push_back(a);
}
}
// Destructor
AnimatedSprite::~AnimatedSprite()
{
animation.clear();
animations_.clear();
}
// Obtiene el indice de la animación a partir del nombre
int AnimatedSprite::getIndex(std::string name)
{
int index = -1;
auto index = -1;
for (auto a : animation)
for (auto a : animations_)
{
index++;
if (a.name == name)
@@ -211,147 +213,147 @@ int AnimatedSprite::getIndex(std::string name)
return index;
}
}
#ifdef VERBOSE
std::cout << "** Warning: could not find \"" << name.c_str() << "\" animation" << std::endl;
#endif
return -1;
}
// Calcula el frame correspondiente a la animación
void AnimatedSprite::animate()
{
if (!enabled || animation[currentAnimation].speed == 0)
if (!enabled_ || animations_[currentAnimation_].speed == 0)
{
return;
}
// Calcula el frame actual a partir del contador
animation[currentAnimation].currentFrame = animation[currentAnimation].counter / animation[currentAnimation].speed;
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].counter / animations_[currentAnimation_].speed;
// Si alcanza el final de la animación, reinicia el contador de la animación
// en función de la variable loop y coloca el nuevo frame
if (animation[currentAnimation].currentFrame >= (int)animation[currentAnimation].frames.size())
if (animations_[currentAnimation_].currentFrame >= (int)animations_[currentAnimation_].frames.size())
{
if (animation[currentAnimation].loop == -1)
if (animations_[currentAnimation_].loop == -1)
{ // Si no hay loop, deja el último frame
animation[currentAnimation].currentFrame = animation[currentAnimation].frames.size();
animation[currentAnimation].completed = true;
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].frames.size();
animations_[currentAnimation_].completed = true;
}
else
{ // Si hay loop, vuelve al frame indicado
animation[currentAnimation].counter = 0;
animation[currentAnimation].currentFrame = animation[currentAnimation].loop;
animations_[currentAnimation_].counter = 0;
animations_[currentAnimation_].currentFrame = animations_[currentAnimation_].loop;
}
}
// En caso contrario
else
{
// Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]);
// Incrementa el contador de la animacion
animation[currentAnimation].counter++;
animations_[currentAnimation_].counter++;
}
}
// Obtiene el número de frames de la animación actual
int AnimatedSprite::getNumFrames()
{
return (int)animation[currentAnimation].frames.size();
return (int)animations_[currentAnimation_].frames.size();
}
// Establece el frame actual de la animación
void AnimatedSprite::setCurrentFrame(int num)
{
// Descarta valores fuera de rango
if (num >= (int)animation[currentAnimation].frames.size())
if (num >= (int)animations_[currentAnimation_].frames.size())
{
num = 0;
}
// Cambia el valor de la variable
animation[currentAnimation].currentFrame = num;
animation[currentAnimation].counter = 0;
animations_[currentAnimation_].currentFrame = num;
animations_[currentAnimation_].counter = 0;
// Escoge el frame correspondiente de la animación
setSpriteClip(animation[currentAnimation].frames[animation[currentAnimation].currentFrame]);
setSpriteClip(animations_[currentAnimation_].frames[animations_[currentAnimation_].currentFrame]);
}
// Establece el valor del contador
void AnimatedSprite::setAnimationCounter(std::string name, int num)
{
animation[getIndex(name)].counter = num;
animations_[getIndex(name)].counter = num;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(std::string name, int speed)
{
animation[getIndex(name)].counter = speed;
animations_[getIndex(name)].counter = speed;
}
// Establece la velocidad de una animación
void AnimatedSprite::setAnimationSpeed(int index, int speed)
{
animation[index].counter = speed;
animations_[index].counter = speed;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(std::string name, int loop)
{
animation[getIndex(name)].loop = loop;
animations_[getIndex(name)].loop = loop;
}
// Establece si la animación se reproduce en bucle
void AnimatedSprite::setAnimationLoop(int index, int loop)
{
animation[index].loop = loop;
animations_[index].loop = loop;
}
// Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(std::string name, bool value)
{
animation[getIndex(name)].completed = value;
animations_[getIndex(name)].completed = value;
}
// OLD - Establece el valor de la variable
void AnimatedSprite::setAnimationCompleted(int index, bool value)
{
animation[index].completed = value;
animations_[index].completed = value;
}
// Comprueba si ha terminado la animación
bool AnimatedSprite::animationIsCompleted()
{
return animation[currentAnimation].completed;
return animations_[currentAnimation_].completed;
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(std::string name, Uint8 index)
{
return animation[getIndex(name)].frames[index];
return animations_[getIndex(name)].frames[index];
}
// Devuelve el rectangulo de una animación y frame concreto
SDL_Rect AnimatedSprite::getAnimationClip(int indexA, Uint8 indexF)
{
return animation[indexA].frames[indexF];
return animations_[indexA].frames[indexF];
}
// Carga la animación desde un vector
bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
{
// Inicializa variables
int framesPerRow = 0;
int frameWidth = 0;
int frameHeight = 0;
int maxTiles = 0;
auto framesPerRow = 0;
auto frameWidth = 0;
auto frameHeight = 0;
auto maxTiles = 0;
// Indicador de éxito en el proceso
bool success = true;
auto success = true;
std::string line;
// Recorre todo el vector
int index = 0;
auto index = 0;
while (index < (int)source->size())
{
// Lee desde el vector
@@ -360,7 +362,7 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
// Si la linea contiene el texto [animation] se realiza el proceso de carga de una animación
if (line == "[animation]")
{
animation_t buffer;
Animation buffer;
buffer.counter = 0;
buffer.currentFrame = 0;
buffer.completed = false;
@@ -410,14 +412,16 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
else
{
#ifdef VERBOSE
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
#endif
success = false;
}
}
} while (line != "[/animation]");
// Añade la animación al vector de animaciones
animation.push_back(buffer);
animations_.push_back(buffer);
}
// En caso contrario se parsea el fichero para buscar las variables y los valores
@@ -446,20 +450,22 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
else
{
#ifdef VERBOSE
std::cout << "Warning: unknown parameter " << line.substr(0, pos).c_str() << std::endl;
#endif
success = false;
}
// Normaliza valores
if (framesPerRow == 0 && frameWidth > 0)
{
framesPerRow = texture->getWidth() / frameWidth;
framesPerRow = texture_->getWidth() / frameWidth;
}
if (maxTiles == 0 && frameWidth > 0 && frameHeight > 0)
{
const int w = texture->getWidth() / frameWidth;
const int h = texture->getHeight() / frameHeight;
const int w = texture_->getWidth() / frameWidth;
const int h = texture_->getHeight() / frameHeight;
maxTiles = w * h;
}
}
@@ -478,26 +484,26 @@ bool AnimatedSprite::loadFromVector(std::vector<std::string> *source)
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(std::string name)
{
const int newAnimation = getIndex(name);
if (currentAnimation != newAnimation)
const auto newAnimation = getIndex(name);
if (currentAnimation_ != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
currentAnimation_ = newAnimation;
animations_[currentAnimation_].currentFrame = 0;
animations_[currentAnimation_].counter = 0;
animations_[currentAnimation_].completed = false;
}
}
// Establece la animacion actual
void AnimatedSprite::setCurrentAnimation(int index)
{
const int newAnimation = index;
if (currentAnimation != newAnimation)
const auto newAnimation = index;
if (currentAnimation_ != newAnimation)
{
currentAnimation = newAnimation;
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
currentAnimation_ = newAnimation;
animations_[currentAnimation_].currentFrame = 0;
animations_[currentAnimation_].counter = 0;
animations_[currentAnimation_].completed = false;
}
}
@@ -511,13 +517,13 @@ void AnimatedSprite::update()
// Establece el rectangulo para un frame de una animación
void AnimatedSprite::setAnimationFrames(Uint8 index_animation, Uint8 index_frame, int x, int y, int w, int h)
{
animation[index_animation].frames.push_back({x, y, w, h});
animations_[index_animation].frames.push_back({x, y, w, h});
}
// OLD - Establece el contador para todas las animaciones
void AnimatedSprite::setAnimationCounter(int value)
{
for (auto &a : animation)
for (auto &a : animations_)
{
a.counter = value;
}
@@ -526,7 +532,7 @@ void AnimatedSprite::setAnimationCounter(int value)
// Reinicia la animación
void AnimatedSprite::resetAnimation()
{
animation[currentAnimation].currentFrame = 0;
animation[currentAnimation].counter = 0;
animation[currentAnimation].completed = false;
animations_[currentAnimation_].currentFrame = 0;
animations_[currentAnimation_].counter = 0;
animations_[currentAnimation_].completed = false;
}

View File

@@ -5,9 +5,10 @@
#include <string> // for string, basic_string
#include <vector> // for vector
#include "moving_sprite.h" // for MovingSprite
class Texture;
#include "texture.h"
#include <memory>
struct animation_t
struct Animation
{
std::string name; // Nombre de la animacion
std::vector<SDL_Rect> frames; // Cada uno de los frames que componen la animación
@@ -20,23 +21,23 @@ struct animation_t
struct animatedSprite_t
{
std::vector<animation_t> animations; // Vector con las diferentes animaciones
Texture *texture; // Textura con los graficos para el sprite
std::vector<Animation> animations; // Vector con las diferentes animaciones
std::shared_ptr<Texture> texture; // Textura con los graficos para el sprite
};
// Carga la animación desde un fichero
animatedSprite_t loadAnimationFromFile(Texture *texture, std::string filePath, bool verbose = false);
animatedSprite_t loadAnimationFromFile(std::shared_ptr<Texture> texture, std::string filePath);
class AnimatedSprite : public MovingSprite
{
private:
// Variables
std::vector<animation_t> animation; // Vector con las diferentes animaciones
int currentAnimation; // Animacion activa
std::vector<Animation> animations_; // Vector con las diferentes animaciones
int currentAnimation_; // Animacion activa
public:
// Constructor
AnimatedSprite(Texture *texture = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(std::shared_ptr<Texture> texture = nullptr, std::string file = "", std::vector<std::string> *buffer = nullptr);
AnimatedSprite(animatedSprite_t *animation);
// Destructor

View File

@@ -4,21 +4,18 @@
#include <algorithm> // for max, min
#include <string> // for basic_string
#include "asset.h" // for Asset
#include "moving_sprite.h" // for MovingSprite
#include "param.h" // for param
#include "sprite.h" // for Sprite
#include "texture.h" // for Texture
// Constructor
Background::Background(SDL_Renderer *renderer)
: renderer(renderer)
{
// Carga las texturas
buildingsTexture = new Texture(renderer, Asset::get()->get("game_buildings.png"));
topCloudsTexture = new Texture(renderer, Asset::get()->get("game_clouds1.png"));
bottomCloudsTexture = new Texture(renderer, Asset::get()->get("game_clouds2.png"));
grassTexture = new Texture(renderer, Asset::get()->get("game_grass.png"));
gradientsTexture = new Texture(renderer, Asset::get()->get("game_sky_colors.png"));
buildingsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_buildings.png"));
topCloudsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds1.png"));
bottomCloudsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_clouds2.png"));
grassTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_grass.png"));
gradientsTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_sky_colors.png"));
// Inicializa variables
gradientNumber = 0;
@@ -53,15 +50,15 @@ Background::Background(SDL_Renderer *renderer)
const int bottomClouds_y = base - 101;
const float topCloudsSpeed = 0.1f;
const float bottomCloudsSpeed = 0.05f;
topCloudsSprite_A = new MovingSprite(0, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture);
topCloudsSprite_B = new MovingSprite(rect.w, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture);
topCloudsSprite_A = std::make_unique<MovingSprite>(0, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture);
topCloudsSprite_B = std::make_unique<MovingSprite>(rect.w, topClouds_y, rect.w, topCloudsTexture->getHeight(), -topCloudsSpeed, 0.0f, 0.0f, 0.0f, topCloudsTexture);
bottomCloudsSprite_A = new MovingSprite(0, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture);
bottomCloudsSprite_B = new MovingSprite(rect.w, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture);
bottomCloudsSprite_A = std::make_unique<MovingSprite>(0, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture);
bottomCloudsSprite_B = std::make_unique<MovingSprite>(rect.w, bottomClouds_y, rect.w, bottomCloudsTexture->getHeight(), -bottomCloudsSpeed, 0.0f, 0.0f, 0.0f, bottomCloudsTexture);
buildingsSprite = new Sprite(0, 0, buildingsTexture->getWidth(), buildingsTexture->getHeight(), buildingsTexture);
gradientSprite = new Sprite(0, 0, rect.w, rect.h, gradientsTexture);
grassSprite = new Sprite(0, 0, grassTexture->getWidth(), grassTexture->getHeight() / 2, grassTexture);
buildingsSprite = std::make_unique<Sprite>(0, 0, buildingsTexture->getWidth(), buildingsTexture->getHeight(), buildingsTexture);
gradientSprite = std::make_unique<Sprite>(0, 0, rect.w, rect.h, gradientsTexture);
grassSprite = std::make_unique<Sprite>(0, 0, grassTexture->getWidth(), grassTexture->getHeight() / 2, grassTexture);
// Inicializa objetos
topCloudsSprite_A->setSpriteClip(0, 0, topCloudsTexture->getWidth(), topCloudsTexture->getHeight());
@@ -85,19 +82,6 @@ Background::Background(SDL_Renderer *renderer)
// Destructor
Background::~Background()
{
delete buildingsTexture;
delete topCloudsTexture;
delete bottomCloudsTexture;
delete grassTexture;
delete gradientsTexture;
delete topCloudsSprite_A;
delete topCloudsSprite_B;
delete bottomCloudsSprite_A;
delete bottomCloudsSprite_B;
delete buildingsSprite;
delete gradientSprite;
delete grassSprite;
SDL_DestroyTexture(canvas);
SDL_DestroyTexture(colorTexture);
}

View File

@@ -3,10 +3,10 @@
#include <SDL2/SDL_rect.h> // for SDL_Rect
#include <SDL2/SDL_render.h> // for SDL_Renderer, SDL_Texture
#include "utils.h" // for color_t
class Asset;
class MovingSprite;
class Sprite;
class Texture;
#include "moving_sprite.h"
#include "sprite.h"
#include "texture.h"
#include <memory>
/*
Esta clase es la encargada de dibujar el fondo que aparece durante la sección
@@ -52,20 +52,20 @@ private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
Texture *buildingsTexture; // Textura con los edificios de fondo
Texture *topCloudsTexture; // Textura con las nubes de fondo
Texture *bottomCloudsTexture; // Textura con las nubes de fondo
Texture *grassTexture; // Textura con la hierba del suelo
Texture *gradientsTexture; // Textura con los diferentes colores de fondo del juego
std::shared_ptr<Texture> buildingsTexture; // Textura con los edificios de fondo
std::shared_ptr<Texture> topCloudsTexture; // Textura con las nubes de fondo
std::shared_ptr<Texture> bottomCloudsTexture; // Textura con las nubes de fondo
std::shared_ptr<Texture> grassTexture; // Textura con la hierba del suelo
std::shared_ptr<Texture> gradientsTexture; // Textura con los diferentes colores de fondo del juego
MovingSprite *topCloudsSprite_A; // Sprite para las nubes superiores
MovingSprite *topCloudsSprite_B; // Sprite para las nubes superiores
MovingSprite *bottomCloudsSprite_A; // Sprite para las nubes inferiores
MovingSprite *bottomCloudsSprite_B; // Sprite para las nubes inferiores
std::unique_ptr<MovingSprite> topCloudsSprite_A; // Sprite para las nubes superiores
std::unique_ptr<MovingSprite> topCloudsSprite_B; // Sprite para las nubes superiores
std::unique_ptr<MovingSprite> bottomCloudsSprite_A; // Sprite para las nubes inferiores
std::unique_ptr<MovingSprite> bottomCloudsSprite_B; // Sprite para las nubes inferiores
Sprite *buildingsSprite; // Sprite con los edificios de fondo
Sprite *gradientSprite; // Sprite con los graficos del degradado de color de fondo
Sprite *grassSprite; // Sprite para la hierba
std::unique_ptr<Sprite> buildingsSprite; // Sprite con los edificios de fondo
std::unique_ptr<Sprite> gradientSprite; // Sprite con los graficos del degradado de color de fondo
std::unique_ptr<Sprite> grassSprite; // Sprite para la hierba
SDL_Texture *canvas; // Textura para componer el fondo
SDL_Texture *colorTexture; // Textura para atenuar el fondo

View File

@@ -7,7 +7,7 @@
#include "texture.h" // for Texture
// Constructor
Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation)
Balloon::Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
: kind(kind), speed(speed)
{
sprite = std::make_unique<AnimatedSprite>(texture, "", animation);

View File

@@ -6,7 +6,7 @@
#include <memory>
#include "utils.h" // for circle_t
#include "animated_sprite.h"
class Texture;
#include "texture.h"
// Cantidad de elementos del vector con los valores de la deformación del globo al rebotar
constexpr int MAX_BOUNCE = 10;
@@ -141,7 +141,7 @@ private:
public:
// Constructor
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, Texture *texture, std::vector<std::string> *animation);
Balloon(float x, float y, Uint8 kind, float velx, float speed, Uint16 creationtimer, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Destructor
~Balloon() = default;

View File

@@ -11,7 +11,7 @@ constexpr int BULLET_VELX_LEFT = -2;
constexpr int BULLET_VELX_RIGHT = 2;
// Constructor
Bullet::Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, Texture *texture)
Bullet::Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr<Texture> texture)
: posX(x), posY(y), width(BULLET_WIDTH), height(BULLET_HEIGHT), velX(0), velY(BULLET_VELY),
kind(kind), owner(owner), playArea(playArea)
{

View File

@@ -5,7 +5,7 @@
#include <memory> // for unique_ptr
#include "sprite.h" // for Sprite
#include "utils.h" // for circle_t
class Texture; // lines 9-9
#include "texture.h" // lines 9-9
// Enumeración para los diferentes tipos de balas
enum class BulletType
@@ -42,7 +42,7 @@ private:
void shiftColliders(); // Alinea el círculo de colisión con el objeto
public:
Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, Texture *texture);
Bullet(int x, int y, BulletType kind, bool poweredUp, int owner, SDL_Rect *playArea, std::shared_ptr<Texture> texture);
~Bullet() = default;
void render(); // Pinta el objeto en pantalla

View File

@@ -18,7 +18,7 @@ Explosions::~Explosions()
// Actualiza la lógica de la clase
void Explosions::update()
{
for (auto explosion : explosions)
for (auto &explosion : explosions)
{
explosion->update();
}
@@ -30,18 +30,18 @@ void Explosions::update()
// Dibuja el objeto en pantalla
void Explosions::render()
{
for (auto explosion : explosions)
for (auto &explosion : explosions)
{
explosion->render();
}
}
// Añade texturas al objeto
void Explosions::addTexture(int size, Texture *texture, std::vector<std::string> *animation)
void Explosions::addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
{
explosion_texture_t temp;
temp.size = size;
temp.texture = texture;
temp.texture = texture.get();
temp.animation = animation;
textures.push_back(temp);
}
@@ -50,9 +50,9 @@ void Explosions::addTexture(int size, Texture *texture, std::vector<std::string>
void Explosions::add(int x, int y, int size)
{
const int index = getIndexBySize(size);
AnimatedSprite *sprite = new AnimatedSprite(textures[index].texture, "", textures[index].animation);
auto sprite = std::make_unique<AnimatedSprite>(textures[index].texture, "", textures[index].animation);
sprite->setPos(x, y);
explosions.push_back(sprite);
explosions.push_back(std::move(sprite));
}
// Vacia el vector de elementos finalizados
@@ -64,7 +64,6 @@ void Explosions::freeExplosions()
{
if (explosions[i]->animationIsCompleted())
{
delete explosions[i];
explosions.erase(explosions.begin() + i);
}
}

View File

@@ -2,8 +2,9 @@
#include <string> // for string
#include <vector> // for vector
class AnimatedSprite;
class Texture;
#include "animated_sprite.h"
#include <memory>
#include "texture.h"
struct explosion_texture_t
{
@@ -18,7 +19,7 @@ class Explosions
private:
// Variables
std::vector<explosion_texture_t> textures; // Vector con las texturas a utilizar
std::vector<AnimatedSprite *> explosions; // Lista con todas las explosiones
std::vector<std::unique_ptr<AnimatedSprite>> explosions; // Lista con todas las explosiones
// Vacia el vector de elementos finalizados
void freeExplosions();
@@ -40,7 +41,7 @@ public:
void render();
// Añade texturas al objeto
void addTexture(int size, Texture *texture, std::vector<std::string> *animation);
void addTexture(int size, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Añade una explosión
void add(int x, int y, int size);

File diff suppressed because it is too large Load Diff

View File

@@ -8,21 +8,21 @@
#include "section.h" // for options_e
#include "utils.h" // for demoKeys_t, color_t, hiScoreEntry_t
#include <memory>
class Asset; // lines 11-11
class Background; // lines 12-12
class Balloon; // lines 13-13
class Bullet; // lines 14-14
class EnemyFormations; // lines 15-15
class Explosions; // lines 16-16
class Fade; // lines 17-17
class Input; // lines 18-18
class Item; // lines 19-19
class Player; // lines 20-20
class Scoreboard; // lines 21-21
class Screen; // lines 22-22
class SmartSprite; // lines 23-23
class Text; // lines 24-24
class Texture; // lines 25-25
#include "asset.h" // lines 11-11
#include "background.h" // lines 12-12
#include "balloon.h" // lines 13-13
#include "bullet.h" // lines 14-14
#include "enemy_formations.h" // lines 15-15
#include "explosions.h" // lines 16-16
#include "fade.h" // lines 17-17
#include "input.h" // lines 18-18
#include "item.h" // lines 19-19
#include "player.h" // lines 20-20
#include "scoreboard.h" // lines 21-21
#include "screen.h" // lines 22-22
#include "smart_sprite.h" // lines 23-23
#include "text.h" // lines 24-24
#include "texture.h" // lines 24-24
enum class BulletType;
struct JA_Music_t; // lines 26-26
struct JA_Sound_t; // lines 27-27
@@ -118,38 +118,38 @@ private:
SDL_Texture *canvas; // Textura para dibujar la zona de juego
std::vector<Player *> players; // Vector con los jugadores
std::vector<Balloon *> balloons; // Vector con los globos
std::vector<Bullet *> bullets; // Vector con las balas
std::vector<Item *> items; // Vector con los items
std::vector<std::shared_ptr<Player>> players; // Vector con los jugadores
std::vector<std::shared_ptr<Balloon>> balloons; // Vector con los globos
std::vector<std::unique_ptr<Bullet>> bullets; // Vector con las balas
std::vector<std::unique_ptr<Item>> items; // Vector con los items
std::vector<SmartSprite *> smartSprites; // Vector con los smartsprites
std::unique_ptr<Texture> bulletTexture; // Textura para las balas
std::vector<Texture *> itemTextures; // Vector con las texturas de los items
std::vector<Texture *> balloonTextures; // Vector con las texturas de los globos
std::vector<Texture *> explosionsTextures; // Vector con las texturas de las explosiones
std::vector<Texture *> player1Textures; // Vector con las texturas del jugador
std::vector<Texture *> player2Textures; // Vector con las texturas del jugador
std::vector<std::vector<Texture *>> playerTextures; // Vector con todas las texturas de los jugadores;
std::shared_ptr<Texture> bulletTexture; // Textura para las balas
std::vector<std::shared_ptr<Texture>> itemTextures; // Vector con las texturas de los items
std::vector<std::shared_ptr<Texture>> balloonTextures; // Vector con las texturas de los globos
std::vector<std::shared_ptr<Texture>> explosionsTextures; // Vector con las texturas de las explosiones
std::vector<std::shared_ptr<Texture>> player1Textures; // Vector con las texturas del jugador
std::vector<std::shared_ptr<Texture>> player2Textures; // Vector con las texturas del jugador
std::vector<std::vector<std::shared_ptr<Texture>>> playerTextures; // Vector con todas las texturas de los jugadores;
std::unique_ptr<Texture> gameTextTexture; // Textura para los sprites con textos
std::shared_ptr<Texture> gameTextTexture; // Textura para los sprites con textos
std::vector<std::vector<std::string> *> itemAnimations; // Vector con las animaciones de los items
std::vector<std::vector<std::string> *> playerAnimations; // Vector con las animaciones del jugador
std::vector<std::vector<std::string> *> balloonAnimations; // Vector con las animaciones de los globos
std::vector<std::vector<std::string> *> explosionsAnimations; // Vector con las animaciones de las explosiones
Text *text; // Fuente para los textos del juego
Text *textBig; // Fuente de texto grande
Text *textNokia2; // Otra fuente de texto para mensajes
Text *textNokiaBig2; // Y la versión en grande
std::unique_ptr<Text> text; // Fuente para los textos del juego
std::unique_ptr<Text> textBig; // Fuente de texto grande
std::unique_ptr<Text> textNokia2; // Otra fuente de texto para mensajes
std::unique_ptr<Text> textNokiaBig2; // Y la versión en grande
std::unique_ptr<Fade> fade; // Objeto para renderizar fades
std::unique_ptr<SDL_Event> eventHandler; // Manejador de eventos
std::unique_ptr<SmartSprite> n1000Sprite; // Sprite con el texto 1.000
std::unique_ptr<SmartSprite> n2500Sprite; // Sprite con el texto 2.500
std::unique_ptr<SmartSprite> n5000Sprite; // Sprite con el texto 5.000
std::shared_ptr<SmartSprite> n1000Sprite; // Sprite con el texto 1.000
std::shared_ptr<SmartSprite> n2500Sprite; // Sprite con el texto 2.500
std::shared_ptr<SmartSprite> n5000Sprite; // Sprite con el texto 5.000
JA_Sound_t *balloonSound; // Sonido para la explosión del globo
JA_Sound_t *bulletSound; // Sonido para los disparos
@@ -259,7 +259,7 @@ private:
void renderBalloons();
// Crea un globo nuevo en el vector de globos
int createBalloon(float x, int y, int kind, float velx, float speed, int stoppedcounter);
std::shared_ptr<Balloon> createBalloon(float x, int y, int kind, float velx, float speed, int stoppedcounter);
// Crea una PowerBall
void createPowerBall();
@@ -277,10 +277,10 @@ private:
void updateBalloonSpeed();
// Explosiona un globo. Lo destruye y crea otros dos si es el caso
void popBalloon(Balloon *balloon);
void popBalloon(std::shared_ptr<Balloon> &balloon);
// Explosiona un globo. Lo destruye
void destroyBalloon(Balloon *balloon);
void destroyBalloon(std::shared_ptr<Balloon> &balloon);
// Explosiona todos los globos
void popAllBalloons();
@@ -301,10 +301,10 @@ private:
void freeBalloons();
// Comprueba la colisión entre el jugador y los globos activos
bool checkPlayerBalloonCollision(Player *player);
bool checkPlayerBalloonCollision(std::shared_ptr<Player> &player);
// Comprueba la colisión entre el jugador y los items
void checkPlayerItemCollision(Player *player);
void checkPlayerItemCollision(std::shared_ptr<Player> &player);
// Comprueba la colisión entre las balas y los globos
void checkBulletBalloonCollision();
@@ -337,7 +337,7 @@ private:
void freeItems();
// Crea un objeto SmartSprite
void createItemScoreSprite(int x, int y, SmartSprite *sprite);
void createItemScoreSprite(int x, int y, std::shared_ptr<SmartSprite> sprite);
// Vacia el vector de smartsprites
void freeSmartSprites();
@@ -352,19 +352,19 @@ private:
void renderSmartSprites();
// Acciones a realizar cuando el jugador muere
void killPlayer(Player *player);
void killPlayer(std::shared_ptr<Player> &player);
// Calcula y establece el valor de amenaza en funcion de los globos activos
void evaluateAndSetMenace();
// Obtiene el valor de la variable
int getMenace();
int getMenace() const;
// Establece el valor de la variable
void setTimeStopped(bool value);
// Obtiene el valor de la variable
bool isTimeStopped();
bool isTimeStopped() const;
// Establece el valor de la variable
void setTimeStoppedCounter(int value);
@@ -451,14 +451,11 @@ private:
void checkPlayersStatusPlaying();
// Obtiene un jugador a partir de su "id"
Player *getPlayer(int id);
std::shared_ptr<Player> getPlayer(int id);
// Obtiene un controlador a partir del "id" del jugador
int getController(int playerId);
// Termina
void quit(section::options_e code);
public:
// Constructor
Game(int playerID, int currentStage, bool demo, JA_Music_t *music);

View File

@@ -69,7 +69,7 @@ void GameLogo::init()
coffeeSprite->setAccelY(0.1f);
coffeeSprite->setSpriteClip(0, 0, coffeeTexture->getWidth(), coffeeTexture->getHeight());
coffeeSprite->setEnabled(true);
coffeeSprite->setEnabledCounter(0);
coffeeSprite->setFinishedCounter(0);
coffeeSprite->setDestX(xp);
coffeeSprite->setDestY(y - coffeeTexture->getHeight());
@@ -85,7 +85,7 @@ void GameLogo::init()
crisisSprite->setAccelY(-0.1f);
crisisSprite->setSpriteClip(0, 0, crisisTexture->getWidth(), crisisTexture->getHeight());
crisisSprite->setEnabled(true);
crisisSprite->setEnabledCounter(0);
crisisSprite->setFinishedCounter(0);
crisisSprite->setDestX(xp + 15);
crisisSprite->setDestY(y);

View File

@@ -23,12 +23,11 @@ Intro::Intro(JA_Music_t *music)
: music(music)
{
// Copia los punteros
SDL_Renderer *renderer = Screen::get()->getRenderer();
auto renderer = Screen::get()->getRenderer();
// Reserva memoria para los objetos
eventHandler = std::make_unique<SDL_Event>();
texture = std::make_unique<Texture>(renderer, Asset::get()->get("intro.png"));
text = std::make_unique<Text>(Asset::get()->get("nokia.png"), Asset::get()->get("nokia.txt"), renderer);
texture = std::make_shared<Texture>(renderer, Asset::get()->get("intro.png"));
text = std::make_shared<Text>(Asset::get()->get("nokia.png"), Asset::get()->get("nokia.txt"), renderer);
// Inicializa variables
section::name = section::NAME_INTRO;
@@ -41,10 +40,10 @@ Intro::Intro(JA_Music_t *music)
constexpr int totalBitmaps = 6;
for (int i = 0; i < totalBitmaps; ++i)
{
auto ss = std::make_unique<SmartSprite>(texture.get());
auto ss = std::make_unique<SmartSprite>(texture);
ss->setWidth(128);
ss->setHeight(96);
ss->setEnabledCounter(20);
ss->setFinishedCounter(20);
ss->setDestX(param.game.gameArea.centerX - 64);
ss->setDestY(param.game.gameArea.firstQuarterY - 24);
bitmaps.push_back(std::move(ss));
@@ -73,7 +72,7 @@ Intro::Intro(JA_Music_t *music)
bitmaps[2]->setAccelX(0.1f);
bitmaps[2]->setAccelY(0.3f);
bitmaps[2]->setSpriteClip(0, 96, 128, 96);
bitmaps[2]->setEnabledCounter(250);
bitmaps[2]->setFinishedCounter(250);
bitmaps[3]->setPosX(param.game.gameArea.centerX - 64);
bitmaps[3]->setPosY(param.game.height);
@@ -103,12 +102,12 @@ Intro::Intro(JA_Music_t *music)
constexpr int totalTexts = 9;
for (int i = 0; i < totalTexts; ++i)
{
auto w = std::make_unique<Writer>(text.get());
auto w = std::make_unique<Writer>(text);
w->setPosX(BLOCK * 0);
w->setPosY(param.game.height - (BLOCK * 6));
w->setKerning(-1);
w->setEnabled(false);
w->setEnabledCounter(180);
w->setFinishedCounter(180);
texts.push_back(std::move(w));
}
@@ -164,23 +163,30 @@ void Intro::reloadTextures()
// Comprueba los eventos
void Intro::checkEvents()
{
SDL_Event event;
// Comprueba los eventos que hay en la cola
while (SDL_PollEvent(eventHandler.get()) != 0)
while (SDL_PollEvent(&event))
{
// Evento de salida de la aplicación
if (eventHandler->type == SDL_QUIT)
switch (event.type)
{
case SDL_QUIT:
{
section::name = section::NAME_QUIT;
break;
}
// Comprueba si se ha cambiado el tamaño de la ventana
else if (eventHandler->type == SDL_WINDOWEVENT)
case SDL_WINDOWEVENT:
{
if (eventHandler->window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
{
reloadTextures();
}
break;
}
default:
break;
}
}
}

View File

@@ -20,9 +20,8 @@ class Intro
{
private:
// Objetos
std::unique_ptr<Texture> texture; // Textura con los graficos
std::unique_ptr<SDL_Event> eventHandler; // Manejador de eventos
std::unique_ptr<Text> text; // Textos de la intro
std::shared_ptr<Texture> texture; // Textura con los graficos
std::shared_ptr<Text> text; // Textos de la intro
std::vector<std::unique_ptr<SmartSprite>> bitmaps; // Vector con los sprites inteligentes para los dibujos de la intro
std::vector<std::unique_ptr<Writer>> texts; // Textos de la intro

View File

@@ -5,10 +5,10 @@
class Texture;
// Constructor
Item::Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std::vector<std::string> *animation)
Item::Item(int kind, float x, float y, SDL_Rect *playArea, std::shared_ptr<Texture> texture, std::vector<std::string> *animation)
: kind(kind), playArea(playArea)
{
sprite = new AnimatedSprite(texture, "", animation);
sprite = std::make_unique<AnimatedSprite>(texture, "", animation);
enabled = true;
timeToLive = 600;
@@ -43,12 +43,6 @@ Item::Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std
shiftColliders();
}
// Destructor
Item::~Item()
{
delete sprite;
}
// Centra el objeto en la posición X
void Item::allignTo(int x)
{

View File

@@ -4,9 +4,10 @@
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <string> // for string
#include <vector> // for vector
#include <memory>
#include "utils.h" // for circle_t
class AnimatedSprite;
class Texture;
#include "animated_sprite.h"
#include "texture.h"
// Tipos de objetos
#define ITEM_POINTS_1_DISK 1
@@ -22,7 +23,7 @@ class Item
{
private:
// Objetos y punteros
AnimatedSprite *sprite; // Sprite con los graficos del objeto
std::unique_ptr<AnimatedSprite> sprite; // Sprite con los graficos del objeto
// Variables
float posX; // Posición X del objeto
@@ -49,10 +50,10 @@ public:
Uint16 timeToLive; // Temporizador con el tiempo que el objeto está presente
// Constructor
Item(int kind, float x, float y, SDL_Rect *playArea, Texture *texture, std::vector<std::string> *animation);
Item(int kind, float x, float y, SDL_Rect *playArea, std::shared_ptr<Texture> texture, std::vector<std::string> *animation);
// Destructor
~Item();
~Item() = default;
// Centra el objeto en la posición X
void allignTo(int x);

View File

@@ -2,260 +2,231 @@
#include "texture.h" // for Texture
// Constructor
MovingSprite::MovingSprite(float x, float y, int w, int h, float velx, float vely, float accelx, float accely, Texture *texture)
: x(x), y(y)
MovingSprite::MovingSprite(float x, float y, int w, int h, float vx, float vy, float ax, float ay, std::shared_ptr<Texture> texture)
: Sprite((int)x, (int)y, w, h, texture), x_(x), y_(y), vx_(vx), vy_(vy), ax_(ax), ay_(ay)
{
// Copia los punteros
this->texture = texture;
// Establece el alto y el ancho del sprite
this->w = w;
this->h = h;
// Establece la posición X,Y del sprite
xPrev = x;
yPrev = y;
// Establece la velocidad X,Y del sprite
vx = velx;
vy = vely;
// Establece la aceleración X,Y del sprite
ax = accelx;
ay = accely;
// Establece el zoom W,H del sprite
zoomW = 1;
zoomH = 1;
zoomW_ = 1;
zoomH_ = 1;
// Establece el angulo con el que se dibujará
angle = (double)0;
angle_ = (double)0;
// Establece los valores de rotacion
rotateEnabled = false;
rotateSpeed = 0;
rotateAmount = (double)0;
rotateEnabled_ = false;
rotateSpeed_ = 0;
rotateAmount_ = (double)0;
// Contador interno
counter = 0;
counter_ = 0;
// Establece el rectangulo de donde coger la imagen
spriteClip = {0, 0, w, h};
spriteClip_ = {0, 0, w_, h_};
// Establece el centro de rotación
center = nullptr;
center_ = nullptr;
// Establece el tipo de volteado
currentFlip = SDL_FLIP_NONE;
currentFlip_ = SDL_FLIP_NONE;
};
// Reinicia todas las variables
void MovingSprite::clear()
{
x = 0.0f; // Posición en el eje X
y = 0.0f; // Posición en el eje Y
x_ = 0.0f; // Posición en el eje X
y_ = 0.0f; // Posición en el eje Y
vx = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
vx_ = 0.0f; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
vy_ = 0.0f; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
ax = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
ax_ = 0.0f; // Aceleración en el eje X. Variación de la velocidad
ay_ = 0.0f; // Aceleración en el eje Y. Variación de la velocidad
zoomW = 1.0f; // Zoom aplicado a la anchura
zoomH = 1.0f; // Zoom aplicado a la altura
zoomW_ = 1.0f; // Zoom aplicado a la anchura
zoomH_ = 1.0f; // Zoom aplicado a la altura
angle = 0.0; // Angulo para dibujarlo
rotateEnabled = false; // Indica si ha de rotar
center = nullptr; // Centro de rotación
rotateSpeed = 0; // Velocidad de giro
rotateAmount = 0.0; // Cantidad de grados a girar en cada iteración
counter = 0; // Contador interno
angle_ = 0.0; // Angulo para dibujarlo
rotateEnabled_ = false; // Indica si ha de rotar
center_ = nullptr; // Centro de rotación
rotateSpeed_ = 0; // Velocidad de giro
rotateAmount_ = 0.0; // Cantidad de grados a girar en cada iteración
counter_ = 0; // Contador interno
currentFlip = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
currentFlip_ = SDL_FLIP_NONE; // Establece como se ha de voltear el sprite
}
// Mueve el sprite
void MovingSprite::move()
{
if (enabled)
{
xPrev = x;
yPrev = y;
x_ += vx_;
y_ += vy_;
x += vx;
y += vy;
vx += ax;
vy += ay;
}
vx_ += ax_;
vy_ += ay_;
}
// Muestra el sprite por pantalla
void MovingSprite::render()
{
if (enabled)
{
texture->render((int)x, (int)y, &spriteClip, zoomW, zoomH, angle, center, currentFlip);
}
texture_->render((int)x_, (int)y_, &spriteClip_, zoomW_, zoomH_, angle_, center_, currentFlip_);
}
// Obtiene el valor de la variable
float MovingSprite::getPosX()
float MovingSprite::getPosX() const
{
return x;
return x_;
}
// Obtiene el valor de la variable
float MovingSprite::getPosY()
float MovingSprite::getPosY() const
{
return y;
return y_;
}
// Obtiene el valor de la variable
float MovingSprite::getVelX()
float MovingSprite::getVelX() const
{
return vx;
return vx_;
}
// Obtiene el valor de la variable
float MovingSprite::getVelY()
float MovingSprite::getVelY() const
{
return vy;
return vy_;
}
// Obtiene el valor de la variable
float MovingSprite::getAccelX()
float MovingSprite::getAccelX() const
{
return ax;
return ax_;
}
// Obtiene el valor de la variable
float MovingSprite::getAccelY()
float MovingSprite::getAccelY() const
{
return ay;
return ay_;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomW()
float MovingSprite::getZoomW() const
{
return zoomW;
return zoomW_;
}
// Obtiene el valor de la variable
float MovingSprite::getZoomH()
float MovingSprite::getZoomH() const
{
return zoomH;
return zoomH_;
}
// Obtiene el valor de la variable
double MovingSprite::getAngle()
double MovingSprite::getAngle() const
{
return angle;
return angle_;
}
// Establece la posición y el tamaño del objeto
// Establece la posición y_ el tamaño del objeto
void MovingSprite::setRect(SDL_Rect rect)
{
x = (float)rect.x;
y = (float)rect.y;
w = rect.w;
h = rect.h;
x_ = (float)rect.x;
y_ = (float)rect.y;
w_ = rect.w;
h_ = rect.h;
}
// Establece el valor de las variables
void MovingSprite::setPos(float x, float y)
{
this->x = x;
this->y = y;
x_ = x;
y_ = y;
}
// Establece el valor de la variable
void MovingSprite::setPosX(float value)
{
x = value;
x_ = value;
}
// Establece el valor de la variable
void MovingSprite::setPosY(float value)
{
y = value;
y_ = value;
}
// Establece el valor de la variable
void MovingSprite::setVelX(float value)
{
vx = value;
vx_ = value;
}
// Establece el valor de la variable
void MovingSprite::setVelY(float value)
{
vy = value;
vy_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelX(float value)
{
ax = value;
ax_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAccelY(float value)
{
ay = value;
ay_ = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomW(float value)
{
zoomW = value;
zoomW_ = value;
}
// Establece el valor de la variable
void MovingSprite::setZoomH(float value)
{
zoomH = value;
zoomH_ = value;
}
// Establece el valor de la variable
void MovingSprite::setAngle(double value)
{
angle = value;
angle_ = value;
}
// Incrementa el valor de la variable
void MovingSprite::incAngle(double value)
{
angle += value;
angle_ += value;
}
// Decrementa el valor de la variable
void MovingSprite::decAngle(double value)
{
angle -= value;
angle_ -= value;
}
// Obtiene el valor de la variable
bool MovingSprite::getRotate()
bool MovingSprite::getRotate() const
{
return rotateEnabled;
return rotateEnabled_;
}
// Obtiene el valor de la variable
Uint16 MovingSprite::getRotateSpeed()
Uint16 MovingSprite::getRotateSpeed() const
{
return rotateSpeed;
return rotateSpeed_;
}
// Establece la rotacion
void MovingSprite::rotate()
{
if (enabled)
if (rotateEnabled)
if (rotateEnabled_)
{
if (counter % rotateSpeed == 0)
if (counter_ % rotateSpeed_ == 0)
{
incAngle(rotateAmount);
incAngle(rotateAmount_);
}
}
}
@@ -263,33 +234,26 @@ void MovingSprite::rotate()
// Establece el valor de la variable
void MovingSprite::setRotate(bool value)
{
rotateEnabled = value;
rotateEnabled_ = value;
}
// Establece el valor de la variable
void MovingSprite::setRotateSpeed(int value)
{
if (value < 1)
{
rotateSpeed = 1;
}
else
{
rotateSpeed = value;
}
rotateSpeed_ = (value < 1) ? 1 : value;
}
// Establece el valor de la variable
void MovingSprite::setRotateAmount(double value)
{
rotateAmount = value;
rotateAmount_ = value;
}
// Establece el valor de la variable
void MovingSprite::disableRotate()
{
rotateEnabled = false;
angle = (double)0;
rotateEnabled_ = false;
angle_ = (double)0;
}
// Actualiza las variables internas del objeto
@@ -297,71 +261,35 @@ void MovingSprite::update()
{
move();
rotate();
if (enabled)
{
++counter %= 60000;
}
++counter_ %= 60000;
}
// Cambia el sentido de la rotación
void MovingSprite::switchRotate()
{
rotateAmount *= -1;
rotateAmount_ *= -1;
}
// Establece el valor de la variable
void MovingSprite::setFlip(SDL_RendererFlip flip)
{
currentFlip = flip;
currentFlip_ = flip;
}
// Gira el sprite horizontalmente
void MovingSprite::flip()
{
currentFlip = (currentFlip == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
currentFlip_ = (currentFlip_ == SDL_FLIP_HORIZONTAL) ? SDL_FLIP_NONE : SDL_FLIP_HORIZONTAL;
}
// Obtiene el valor de la variable
SDL_RendererFlip MovingSprite::getFlip()
{
return currentFlip;
return currentFlip_;
}
// Devuelve el rectangulo donde está el sprite
SDL_Rect MovingSprite::getRect()
{
const SDL_Rect rect = {(int)x, (int)y, w, h};
return rect;
}
// Deshace el último movimiento
void MovingSprite::undoMove()
{
x = xPrev;
y = yPrev;
}
// Deshace el último movimiento en el eje X
void MovingSprite::undoMoveX()
{
x = xPrev;
}
// Deshace el último movimiento en el eje Y
void MovingSprite::undoMoveY()
{
y = yPrev;
}
// Pone a cero las velocidades de desplacamiento
void MovingSprite::clearVel()
{
vx = vy = 0.0f;
}
// Devuelve el incremento en el eje X en pixels
int MovingSprite::getIncX()
{
return (int)x - (int)xPrev;
return (SDL_Rect){(int)x_, (int)y_, w_, h_};
}

View File

@@ -3,39 +3,37 @@
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
#include <SDL2/SDL_render.h> // for SDL_RendererFlip
#include <SDL2/SDL_stdinc.h> // for Uint16
#include <memory>
#include "sprite.h" // for Sprite
class Texture;
#include "texture.h"
// Clase MovingSprite. Añade posicion y velocidad en punto flotante
class MovingSprite : public Sprite
{
protected:
float x; // Posición en el eje X
float y; // Posición en el eje Y
float x_; // Posición en el eje X
float y_; // Posición en el eje Y
float xPrev; // Posición anterior en el eje X
float yPrev; // Posición anterior en el eje Y
float vx_; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy_; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float vx; // Velocidad en el eje X. Cantidad de pixeles a desplazarse
float vy; // Velocidad en el eje Y. Cantidad de pixeles a desplazarse
float ax_; // Aceleración en el eje X. Variación de la velocidad
float ay_; // Aceleración en el eje Y. Variación de la velocidad
float ax; // Aceleración en el eje X. Variación de la velocidad
float ay; // Aceleración en el eje Y. Variación de la velocidad
float zoomW_; // Zoom aplicado a la anchura
float zoomH_; // Zoom aplicado a la altura
float zoomW; // Zoom aplicado a la anchura
float zoomH; // Zoom aplicado a la altura
double angle; // Angulo para dibujarlo
bool rotateEnabled; // Indica si ha de rotar
int rotateSpeed; // Velocidad de giro
double rotateAmount; // Cantidad de grados a girar en cada iteración
int counter; // Contador interno
SDL_Point *center; // Centro de rotación
SDL_RendererFlip currentFlip; // Indica como se voltea el sprite
double angle_; // Angulo para dibujarlo
bool rotateEnabled_; // Indica si ha de rotar
int rotateSpeed_; // Velocidad de giro
double rotateAmount_; // Cantidad de grados a girar en cada iteración
int counter_; // Contador interno
SDL_Point *center_; // Centro de rotación
SDL_RendererFlip currentFlip_; // Indica como se voltea el sprite
public:
// Constructor
MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, Texture *texture = nullptr);
MovingSprite(float x = 0, float y = 0, int w = 0, int h = 0, float velx = 0, float vely = 0, float accelx = 0, float accely = 0, std::shared_ptr<Texture> texture = nullptr);
// Mueve el sprite
void move();
@@ -53,37 +51,25 @@ public:
void render();
// Obten el valor de la variable
float getPosX();
float getPosX() const;
float getPosY() const;
// Obten el valor de la variable
float getPosY();
float getVelX() const;
float getVelY() const;
// Obten el valor de la variable
float getVelX();
float getAccelX() const;
float getAccelY() const;
// Obten el valor de la variable
float getVelY();
float getZoomW() const;
float getZoomH() const;
// Obten el valor de la variable
float getAccelX();
// Obten el valor de la variable
float getAccelY();
// Obten el valor de la variable
float getZoomW();
// Obten el valor de la variable
float getZoomH();
// Obten el valor de la variable
double getAngle();
// Obtiene el valor de la variable
bool getRotate();
// Obtiene el valor de la variable
Uint16 getRotateSpeed();
double getAngle() const;
bool getRotate() const;
Uint16 getRotateSpeed() const;
// Establece la posición y el tamaño del objeto
void setRect(SDL_Rect rect);
@@ -93,44 +79,28 @@ public:
// Establece el valor de la variable
void setPosX(float value);
// Establece el valor de la variable
void setPosY(float value);
// Establece el valor de la variable
void setVelX(float value);
// Establece el valor de la variable
void setVelY(float value);
// Establece el valor de la variable
void setAccelX(float value);
// Establece el valor de la variable
void setAccelY(float value);
// Establece el valor de la variable
void setZoomW(float value);
// Establece el valor de la variable
void setZoomH(float value);
// Establece el valor de la variable
void setAngle(double vaue);
// Incrementa el valor de la variable
void incAngle(double value);
// Decrementa el valor de la variable
void decAngle(double value);
// Establece el valor de la variable
void setRotate(bool value);
// Establece el valor de la variable
void setRotateSpeed(int value);
// Establece el valor de la variable
void setRotateAmount(double value);
// Quita el efecto de rotación y deja el sprite en su angulo inicial.
@@ -150,19 +120,4 @@ public:
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect();
// Deshace el último movimiento
void undoMove();
// Deshace el último movimiento en el eje X
void undoMoveX();
// Deshace el último movimiento en el eje Y
void undoMoveY();
// Pone a cero las velocidades de desplacamiento
void clearVel();
// Devuelve el incremento en el eje X en pixels
int getIncX();
};

View File

@@ -128,7 +128,7 @@ void Notify::update()
}
}
notifications[i].sprite->setRect(notifications[i].rect);
notifications[i].sprite->setPos(notifications[i].rect);
}
clearFinishedNotifications();
@@ -225,7 +225,7 @@ void Notify::showText(std::string text1, std::string text2, int icon)
n.rect = {despH, yPos, width, height};
// Crea la textura
n.texture = new Texture(renderer);
n.texture = std::make_shared<Texture>(renderer);
n.texture->createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET);
n.texture->setBlendMode(SDL_BLENDMODE_BLEND);
@@ -258,7 +258,7 @@ void Notify::showText(std::string text1, std::string text2, int icon)
// Dibuja el icono de la notificación
if (hasIcons && icon >= 0 && numTexts == 2)
{
auto sp = std::make_unique<Sprite>((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture.get());
auto sp = std::make_unique<Sprite>((SDL_Rect){0, 0, iconSize, iconSize}, iconTexture);
sp->setPos({paddingIn, paddingIn, iconSize, iconSize});
sp->setSpriteClip({iconSize * (icon % 10), iconSize * (icon / 10), iconSize, iconSize});
sp->render();
@@ -280,7 +280,7 @@ void Notify::showText(std::string text1, std::string text2, int icon)
SDL_SetRenderTarget(renderer, nullptr);
// Crea el sprite de la notificación
n.sprite = new Sprite(n.rect, n.texture);
n.sprite = std::make_shared<Sprite>(n.rect, n.texture);
// Deja la notificación invisible
n.texture->setAlpha(0);

View File

@@ -42,8 +42,8 @@ private:
struct Notification
{
Texture *texture;
Sprite *sprite;
std::shared_ptr<Texture> texture;
std::shared_ptr<Sprite> sprite;
std::string text1;
std::string text2;
int counter;
@@ -58,7 +58,7 @@ private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
std::unique_ptr<Texture> iconTexture; // Textura para los iconos de las notificaciones
std::shared_ptr<Texture> iconTexture; // Textura para los iconos de las notificaciones
std::unique_ptr<Text> text; // Objeto para dibujar texto
// Variables

View File

@@ -11,7 +11,7 @@
#include "options.h"
// Constructor
Player::Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations)
Player::Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations)
{
// Reserva memoria para los objetos
playerSprite = std::make_unique<AnimatedSprite>(texture[0], "", animations[0]);
@@ -679,7 +679,7 @@ void Player::shiftColliders()
}
// Pone las texturas del jugador
void Player::setPlayerTextures(std::vector<Texture *> texture)
void Player::setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture)
{
playerSprite->setTexture(texture[0]);
powerSprite->setTexture(texture[1]);

View File

@@ -8,7 +8,7 @@
#include "animated_sprite.h" // for AnimatedSprite
#include "enter_name.h" // for EnterName
#include "utils.h" // for circle_t
class Texture; // lines 12-12
#include "texture.h" // lines 12-12
enum class ScoreboardMode;
// Estados del jugador
@@ -103,7 +103,7 @@ private:
public:
// Constructor
Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector<Texture *> texture, std::vector<std::vector<std::string> *> animations);
Player(int id, float x, int y, bool demo, SDL_Rect *playArea, std::vector<std::shared_ptr<Texture>> texture, std::vector<std::vector<std::string> *> animations);
// Destructor
~Player() = default;
@@ -118,7 +118,7 @@ public:
void render();
// Pone las texturas del jugador
void setPlayerTextures(std::vector<Texture *> texture);
void setPlayerTextures(std::vector<std::shared_ptr<Texture>> texture);
// Actua en consecuencia de la entrada recibida
void setInput(int input);

View File

@@ -67,9 +67,9 @@ Scoreboard::Scoreboard(SDL_Renderer *renderer)
recalculateAnchors();
// Crea objetos
gamePowerMeterTexture = std::unique_ptr<Texture>(new Texture(renderer, Asset::get()->get("game_power_meter.png")));
powerMeterSprite = std::unique_ptr<Sprite>(new Sprite(slot4_2.x - 20, slot4_2.y, 40, 7, gamePowerMeterTexture.get()));
textScoreBoard = std::unique_ptr<Text>(new Text(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer));
gamePowerMeterTexture = std::make_shared<Texture>(renderer, Asset::get()->get("game_power_meter.png"));
powerMeterSprite = std::make_unique<Sprite>(slot4_2.x - 20, slot4_2.y, 40, 7, gamePowerMeterTexture);
textScoreBoard = std::make_unique<Text>(Asset::get()->get("8bithud.png"), Asset::get()->get("8bithud.txt"), renderer);
// Crea la textura de fondo
background = nullptr;

View File

@@ -7,9 +7,9 @@
#include <string> // for string, basic_string
#include <vector> // for vector
#include "utils.h" // for color_t
class Sprite; // lines 11-11
class Text; // lines 12-12
class Texture; // lines 13-13
#include "sprite.h" // lines 11-11
#include "text.h" // lines 12-12
#include "texture.h" // lines 13-13
// Defines
constexpr int SCOREBOARD_LEFT_PANEL = 0;
@@ -48,7 +48,7 @@ private:
// Objetos y punteros
SDL_Renderer *renderer; // El renderizador de la ventana
std::unique_ptr<Texture> gamePowerMeterTexture; // Textura con el marcador de poder de la fase
std::shared_ptr<Texture> gamePowerMeterTexture; // Textura con el marcador de poder de la fase
std::unique_ptr<Sprite> powerMeterSprite; // Sprite para el medidor de poder de la fase
std::unique_ptr<Text> textScoreBoard; // Fuente para el marcador del juego

View File

@@ -3,99 +3,66 @@
class Texture;
// Constructor
SmartSprite::SmartSprite(Texture *texture)
SmartSprite::SmartSprite(std::shared_ptr<Texture> texture)
{
// Copia punteros
setTexture(texture);
// Inicializa el objeto
init();
}
// Inicializa el objeto
void SmartSprite::init()
{
enabled = false;
enabledCounter = 0;
onDestination = false;
destX = 0;
destY = 0;
counter = 0;
finished = false;
finishedCounter_ = 0;
onDestination_ = false;
destX_ = 0;
destY_ = 0;
finished_ = false;
}
// Actualiza la posición y comprueba si ha llegado a su destino
void SmartSprite::update()
{
if (enabled)
{
// Actualiza las variables internas del objeto
MovingSprite::update();
// Comprueba el movimiento
checkMove();
// Comprueba si ha terminado
checkFinished();
}
}
// Pinta el objeto en pantalla
void SmartSprite::render()
{
if (enabled)
{
// Muestra el sprite por pantalla
MovingSprite::render();
}
}
// Obtiene el valor de la variable
bool SmartSprite::isEnabled()
{
return enabled;
}
// Establece el valor de la variable
void SmartSprite::setEnabled(bool enabled)
void SmartSprite::setFinishedCounter(int value)
{
this->enabled = enabled;
}
// Obtiene el valor de la variable
int SmartSprite::getEnabledCounter()
{
return enabledCounter;
}
// Establece el valor de la variable
void SmartSprite::setEnabledCounter(int value)
{
enabledCounter = value;
finishedCounter_ = value;
}
// Establece el valor de la variable
void SmartSprite::setDestX(int x)
{
destX = x;
destX_ = x;
}
// Establece el valor de la variable
void SmartSprite::setDestY(int y)
{
destY = y;
destY_ = y;
}
// Obtiene el valor de la variable
int SmartSprite::getDestX()
int SmartSprite::getDestX() const
{
return destX;
return destX_;
}
// Obtiene el valor de la variable
int SmartSprite::getDestY()
int SmartSprite::getDestY() const
{
return destY;
return destY_;
}
// Comprueba el movimiento
@@ -105,10 +72,10 @@ void SmartSprite::checkMove()
if (getAccelX() > 0 || getVelX() > 0)
{
// Comprueba si ha llegado al destino
if (getPosX() > destX)
if (getPosX() > destX_)
{
// Lo coloca en posición
setPosX(destX);
setPosX(destX_);
// Lo detiene
setVelX(0.0f);
@@ -119,10 +86,10 @@ void SmartSprite::checkMove()
else if (getAccelX() < 0 || getVelX() < 0)
{
// Comprueba si ha llegado al destino
if (getPosX() < destX)
if (getPosX() < destX_)
{
// Lo coloca en posición
setPosX(destX);
setPosX(destX_);
// Lo detiene
setVelX(0.0f);
@@ -134,10 +101,10 @@ void SmartSprite::checkMove()
if (getAccelY() > 0 || getVelY() > 0)
{
// Comprueba si ha llegado al destino
if (getPosY() > destY)
if (getPosY() > destY_)
{
// Lo coloca en posición
setPosY(destY);
setPosY(destY_);
// Lo detiene
setVelY(0.0f);
@@ -148,10 +115,10 @@ void SmartSprite::checkMove()
else if (getAccelY() < 0 || getVelY() < 0)
{
// Comprueba si ha llegado al destino
if (getPosY() < destY)
if (getPosY() < destY_)
{
// Lo coloca en posición
setPosY(destY);
setPosY(destY_);
// Lo detiene
setVelY(0.0f);
@@ -164,29 +131,29 @@ void SmartSprite::checkMove()
void SmartSprite::checkFinished()
{
// Comprueba si ha llegado a su destino
onDestination = (getPosX() == destX && getPosY() == destY) ? true : false;
onDestination_ = (getPosX() == destX_ && getPosY() == destY_) ? true : false;
if (onDestination)
{ // Si esta en el destino comprueba su contador
if (enabledCounter == 0)
{ // Si ha llegado a cero, deshabilita el objeto y lo marca como finalizado
finished = true;
if (onDestination_)
{
if (finishedCounter_ == 0)
{
finished_ = true;
}
else
{ // Si no ha llegado a cero, decrementa el contador
enabledCounter--;
{
--finishedCounter_;
}
}
}
// Obtiene el valor de la variable
bool SmartSprite::isOnDestination()
bool SmartSprite::isOnDestination() const
{
return onDestination;
return onDestination_;
}
// Obtiene el valor de la variable
bool SmartSprite::hasFinished()
bool SmartSprite::hasFinished() const
{
return finished;
return finished_;
}

View File

@@ -1,19 +1,19 @@
#pragma once
#include "animated_sprite.h" // for AnimatedSprite
class Texture;
#include "texture.h"
#include <memory>
// Clase SmartSprite
class SmartSprite : public AnimatedSprite
{
private:
// Variables
bool enabled; // Indica si esta habilitado
bool onDestination; // Indica si está en el destino
int destX; // Posicion de destino en el eje X
int destY; // Posicion de destino en el eje Y
int enabledCounter; // Contador para deshabilitarlo
bool finished; // Indica si ya ha terminado
bool onDestination_; // Indica si está en el destino
int destX_; // Posicion de destino en el eje X
int destY_; // Posicion de destino en el eje Y
int finishedCounter_; // Contador para deshabilitarlo
bool finished_; // Indica si ya ha terminado
// Comprueba el movimiento
void checkMove();
@@ -23,7 +23,7 @@ private:
public:
// Constructor
SmartSprite(Texture *texture);
SmartSprite(std::shared_ptr<Texture> texture);
// Destructor
~SmartSprite() = default;
@@ -37,17 +37,8 @@ public:
// Pinta el objeto en pantalla
void render();
// Obtiene el valor de la variable
bool isEnabled();
// Establece el valor de la variable
void setEnabled(bool enabled);
// Obtiene el valor de la variable
int getEnabledCounter();
// Establece el valor de la variable
void setEnabledCounter(int value);
void setFinishedCounter(int value);
// Establece el valor de la variable
void setDestX(int x);
@@ -56,14 +47,14 @@ public:
void setDestY(int y);
// Obtiene el valor de la variable
int getDestX();
int getDestX() const;
// Obtiene el valor de la variable
int getDestY();
int getDestY() const;
// Obtiene el valor de la variable
bool isOnDestination();
bool isOnDestination() const;
// Obtiene el valor de la variable
bool hasFinished();
bool hasFinished() const;
};

View File

@@ -1,165 +1,162 @@
#include "sprite.h"
#include "texture.h" // for Texture
// Constructor
Sprite::Sprite(int x, int y, int w, int h, Texture *texture)
: x(x), y(y), w(w), h(h), texture(texture)
Sprite::Sprite(int x, int y, int w, int h, std::shared_ptr<Texture> texture)
: x_(x), y_(y), w_(w), h_(h), texture_(texture)
{
// Establece el rectangulo de donde coger la imagen
spriteClip = {0, 0, w, h};
spriteClip_ = {0, 0, w, h};
// Inicializa variables
enabled = true;
enabled_ = true;
}
Sprite::Sprite(SDL_Rect rect, Texture *texture)
: x(rect.x), y(rect.y), w(rect.w), h(rect.h), texture(texture)
Sprite::Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture)
: x_(rect.x), y_(rect.y), w_(rect.w), h_(rect.h), texture_(texture)
{
// Establece el rectangulo de donde coger la imagen
spriteClip = {0, 0, w, h};
spriteClip_ = {0, 0, w_, h_};
// Inicializa variables
enabled = true;
enabled_ = true;
}
// Muestra el sprite por pantalla
void Sprite::render()
{
if (enabled)
if (enabled_)
{
texture->render(x, y, &spriteClip);
texture_->render(x_, y_, &spriteClip_);
}
}
// Obten el valor de la variable
int Sprite::getPosX() const
{
return x;
return x_;
}
// Obten el valor de la variable
int Sprite::getPosY() const
{
return y;
return y_;
}
// Obten el valor de la variable
int Sprite::getWidth() const
{
return w;
return w_;
}
// Obten el valor de la variable
int Sprite::getHeight() const
{
return h;
return h_;
}
// Establece la posición del objeto
void Sprite::setPos(int x, int y)
{
x_ = x;
y_ = y;
}
// Establece la posición del objeto
void Sprite::setPos(SDL_Point p)
{
this->x = p.x;
this->y = p.y;
x_ = p.x;
y_ = p.y;
}
// Establece la posición del objeto
void Sprite::setPos(SDL_Rect r)
{
this->x = r.x;
this->y = r.y;
this->w = r.w;
this->h = r.h;
x_ = r.x;
y_ = r.y;
w_ = r.w;
h_ = r.h;
}
// Establece el valor de la variable
void Sprite::setPosX(int x)
{
this->x = x;
x_ = x;
}
// Establece el valor de la variable
void Sprite::setPosY(int y)
{
this->y = y;
y_ = y;
}
// Establece el valor de la variable
void Sprite::setWidth(int w)
{
this->w = w;
w_ = w;
}
// Establece el valor de la variable
void Sprite::setHeight(int h)
{
this->h = h;
h_ = h;
}
// Obten el valor de la variable
SDL_Rect Sprite::getSpriteClip() const
{
return spriteClip;
return spriteClip_;
}
// Establece el valor de la variable
void Sprite::setSpriteClip(SDL_Rect rect)
{
spriteClip = rect;
spriteClip_ = rect;
}
// Establece el valor de la variable
void Sprite::setSpriteClip(int x, int y, int w, int h)
{
spriteClip = {x, y, w, h};
spriteClip_ = (SDL_Rect){x, y, w, h};
}
// Obten el valor de la variable
Texture *Sprite::getTexture()
std::shared_ptr<Texture> Sprite::getTexture() const
{
return texture;
return texture_;
}
// Establece el valor de la variable
void Sprite::setTexture(Texture *texture)
void Sprite::setTexture(std::shared_ptr<Texture> texture)
{
this->texture = texture;
texture_ = texture;
}
// Establece el valor de la variable
void Sprite::setEnabled(bool value)
{
enabled = value;
enabled_ = value;
}
// Comprueba si el objeto está habilitado
bool Sprite::isEnabled() const
{
return enabled;
return enabled_;
}
// Devuelve el rectangulo donde está el sprite
SDL_Rect Sprite::getRect() const
{
return (SDL_Rect){x, y, w, h};
}
// Establece los valores de posición y tamaño del sprite
void Sprite::setRect(SDL_Rect rect)
{
x = rect.x;
y = rect.y;
w = rect.w;
h = rect.h;
return (SDL_Rect){x_, y_, w_, h_};
}
// Incrementa el valor de la variable
void Sprite::incPosX(int value)
{
x += value;
x_ += value;
}
// Incrementa el valor de la variable
void Sprite::incPosY(int value)
{
y += value;
y_ += value;
}

View File

@@ -1,26 +1,27 @@
#pragma once
#include <SDL2/SDL_rect.h> // for SDL_Rect, SDL_Point
class Texture;
#include "texture.h"
#include <memory>
// Clase sprite
class Sprite
{
protected:
int x; // Posición en el eje X donde dibujar el sprite
int y; // Posición en el eje Y donde dibujar el sprite
int w; // Ancho del sprite
int h; // Alto del sprite
int x_; // Posición en el eje X donde dibujar el sprite
int y_; // Posición en el eje Y donde dibujar el sprite
int w_; // Ancho del sprite
int h_; // Alto del sprite
Texture *texture; // Textura donde estan todos los dibujos del sprite
SDL_Rect spriteClip; // Rectangulo de origen de la textura que se dibujará en pantalla
std::shared_ptr<Texture> texture_; // Textura donde estan todos los dibujos del sprite
SDL_Rect spriteClip_; // Rectangulo de origen de la textura que se dibujará en pantalla
bool enabled; // Indica si el sprite esta habilitado
bool enabled_; // Indica si el sprite esta habilitado
public:
// Constructor
Sprite(int x = 0, int y = 0, int w = 0, int h = 0, Texture *texture = nullptr);
Sprite(SDL_Rect rect, Texture *texture = nullptr);
Sprite(int x = 0, int y = 0, int w = 0, int h = 0, std::shared_ptr<Texture> texture = nullptr);
Sprite(SDL_Rect rect, std::shared_ptr<Texture> texture = nullptr);
// Destructor
~Sprite() = default;
@@ -30,52 +31,40 @@ public:
// Obten el valor de la variable
int getPosX() const;
// Obten el valor de la variable
int getPosY() const;
// Obten el valor de la variable
int getWidth() const;
// Obten el valor de la variable
int getHeight() const;
// Establece la posición del objeto
void setPos(int x, int y);
void setPos(SDL_Point p);
void setPos(SDL_Rect r);
// Establece el valor de la variable
void setPosX(int x);
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect() const;
// Establece el valor de la variable
void setPosX(int x);
void setPosY(int y);
void setWidth(int w);
void setHeight(int h);
// Incrementa el valor de la variable
void incPosX(int value);
// Incrementa el valor de la variable
void incPosY(int value);
// Establece el valor de la variable
void setWidth(int w);
// Establece el valor de la variable
void setHeight(int h);
// Obten el valor de la variable
SDL_Rect getSpriteClip() const;
// Establece el valor de la variable
void setSpriteClip(SDL_Rect rect);
// Establece el valor de la variable
void setSpriteClip(int x, int y, int w, int h);
// Obten el valor de la variable
Texture *getTexture();
std::shared_ptr<Texture> getTexture() const;
// Establece el valor de la variable
void setTexture(Texture *texture);
void setTexture(std::shared_ptr<Texture> texture);
// Establece el valor de la variable
void setEnabled(bool value);
@@ -83,9 +72,4 @@ public:
// Comprueba si el objeto está habilitado
bool isEnabled() const;
// Devuelve el rectangulo donde está el sprite
SDL_Rect getRect() const;
// Establece los valores de posición y tamaño del sprite
void setRect(SDL_Rect rect);
};

View File

@@ -12,36 +12,36 @@
// Constructor
Texture::Texture(SDL_Renderer *renderer, std::string path)
: renderer(renderer), path(path)
: renderer_(renderer), path_(path)
{
// Inicializa
surface = nullptr;
texture = nullptr;
width = 0;
height = 0;
paletteIndex = 0;
palettes.clear();
surface_ = nullptr;
texture_ = nullptr;
width_ = 0;
height_ = 0;
paletteIndex_ = 0;
palettes_.clear();
// Carga el fichero en la textura
if (path != "")
if (path_ != "")
{
// Obtiene la extensión
const std::string extension = path.substr(path.find_last_of(".") + 1);
const std::string extension = path_.substr(path_.find_last_of(".") + 1);
// .png
if (extension == "png")
{
loadFromFile(path);
loadFromFile(path_);
}
// .gif
else if (extension == "gif")
{
surface = loadSurface(path.c_str());
addPalette(path.c_str());
surface_ = loadSurface(path_.c_str());
addPalette(path_.c_str());
setPaletteColor(0, 0, 0x00000000);
createBlank(width, height, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
createBlank(width_, height_, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING);
SDL_SetTextureBlendMode(texture_, SDL_BLENDMODE_BLEND);
flipSurface();
}
}
@@ -106,7 +106,7 @@ bool Texture::loadFromFile(std::string path)
else
{
// Crea la textura desde los pixels de la surface
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
newTexture = SDL_CreateTextureFromSurface(renderer_, loadedSurface);
if (newTexture == nullptr)
{
#ifdef VERBOSE
@@ -116,8 +116,8 @@ bool Texture::loadFromFile(std::string path)
else
{
// Obtiene las dimensiones de la imagen
this->width = loadedSurface->w;
this->height = loadedSurface->h;
width_ = loadedSurface->w;
height_ = loadedSurface->h;
}
// Elimina la textura cargada
@@ -126,71 +126,73 @@ bool Texture::loadFromFile(std::string path)
// Return success
stbi_image_free(data);
texture = newTexture;
return texture != nullptr;
texture_ = newTexture;
return texture_ != nullptr;
}
// Crea una textura en blanco
bool Texture::createBlank(int width, int height, SDL_PixelFormatEnum format, SDL_TextureAccess access)
{
// Crea una textura sin inicializar
texture = SDL_CreateTexture(renderer, format, access, width, height);
if (texture == nullptr)
texture_ = SDL_CreateTexture(renderer_, format, access, width, height);
if (!texture_)
{
#ifdef VERBOSE
std::cout << "Unable to create blank texture! SDL Error: " << SDL_GetError() << std::endl;
#endif
}
else
{
this->width = width;
this->height = height;
width_ = width;
height_ = height;
}
return texture != nullptr;
return texture_ != nullptr;
}
// Libera la memoria de la textura
void Texture::unload()
{
// Libera la textura
if (texture != nullptr)
if (texture_)
{
SDL_DestroyTexture(texture);
texture = nullptr;
width = 0;
height = 0;
SDL_DestroyTexture(texture_);
texture_ = nullptr;
width_ = 0;
height_ = 0;
}
// Libera la surface
if (surface != nullptr)
if (surface_)
{
deleteSurface(surface);
surface = nullptr;
deleteSurface(surface_);
surface_ = nullptr;
}
}
// Establece el color para la modulacion
void Texture::setColor(Uint8 red, Uint8 green, Uint8 blue)
{
SDL_SetTextureColorMod(texture, red, green, blue);
SDL_SetTextureColorMod(texture_, red, green, blue);
}
// Establece el blending
void Texture::setBlendMode(SDL_BlendMode blending)
{
SDL_SetTextureBlendMode(texture, blending);
SDL_SetTextureBlendMode(texture_, blending);
}
// Establece el alpha para la modulación
void Texture::setAlpha(Uint8 alpha)
{
SDL_SetTextureAlphaMod(texture, alpha);
SDL_SetTextureAlphaMod(texture_, alpha);
}
// Renderiza la textura en un punto específico
void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, double angle, SDL_Point *center, SDL_RendererFlip flip)
{
// Establece el destino de renderizado en la pantalla
SDL_Rect renderQuad = {x, y, width, height};
SDL_Rect renderQuad = {x, y, width_, height_};
// Obtiene las dimesiones del clip de renderizado
if (clip != nullptr)
@@ -203,37 +205,37 @@ void Texture::render(int x, int y, SDL_Rect *clip, float zoomW, float zoomH, dou
renderQuad.h = renderQuad.h * zoomH;
// Renderiza a pantalla
SDL_RenderCopyEx(renderer, texture, clip, &renderQuad, angle, center, flip);
SDL_RenderCopyEx(renderer_, texture_, clip, &renderQuad, angle, center, flip);
}
// Establece la textura como objetivo de renderizado
void Texture::setAsRenderTarget(SDL_Renderer *renderer)
{
SDL_SetRenderTarget(renderer, texture);
SDL_SetRenderTarget(renderer, texture_);
}
// Obtiene el ancho de la imagen
int Texture::getWidth()
{
return width;
return width_;
}
// Obtiene el alto de la imagen
int Texture::getHeight()
{
return height;
return height_;
}
// Recarga la textura
bool Texture::reLoad()
{
return loadFromFile(path);
return loadFromFile(path_);
}
// Obtiene la textura
SDL_Texture *Texture::getSDLTexture()
{
return texture;
return texture_;
}
// Crea una nueva surface
@@ -291,8 +293,8 @@ Surface Texture::loadSurface(const char *filename)
surface->data = pixels;
free(buffer);
this->width = w;
this->height = h;
width_ = w;
height_ = h;
return surface;
}
@@ -301,27 +303,27 @@ Surface Texture::loadSurface(const char *filename)
void Texture::flipSurface()
{
// Limpia la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer);
SDL_SetRenderTarget(renderer, texture);
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
SDL_SetRenderTarget(renderer, temp);
auto *temp = SDL_GetRenderTarget(renderer_);
SDL_SetRenderTarget(renderer_, texture_);
SDL_SetRenderDrawColor(renderer_, 0, 0, 0, 0);
SDL_RenderClear(renderer_);
SDL_SetRenderTarget(renderer_, temp);
// Vuelca los datos
Uint32 *pixels;
int pitch;
SDL_LockTexture(texture, nullptr, (void **)&pixels, &pitch);
for (int i = 0; i < width * height; ++i)
SDL_LockTexture(texture_, nullptr, (void **)&pixels, &pitch);
for (int i = 0; i < width_ * height_; ++i)
{
pixels[i] = palettes[paletteIndex][surface->data[i]];
pixels[i] = palettes_[paletteIndex_][surface_->data[i]];
}
SDL_UnlockTexture(texture);
SDL_UnlockTexture(texture_);
}
// Establece un color de la paleta
void Texture::setPaletteColor(int palette, int index, Uint32 color)
{
palettes.at(palette)[index] = color;
palettes_.at(palette)[index] = color;
}
// Carga una paleta desde un fichero
@@ -361,16 +363,16 @@ std::vector<Uint32> Texture::loadPal(const char *filename)
// Añade una paleta a la lista
void Texture::addPalette(std::string path)
{
palettes.push_back(loadPal(path.c_str()));
setPaletteColor((int)palettes.size() - 1, 0, 0x00000000);
palettes_.push_back(loadPal(path.c_str()));
setPaletteColor((int)palettes_.size() - 1, 0, 0x00000000);
}
// Cambia la paleta de la textura
void Texture::setPalette(int palette)
{
if (palette < (int)palettes.size())
if (palette < (int)palettes_.size())
{
paletteIndex = palette;
paletteIndex_ = palette;
flipSurface();
}
}
@@ -378,5 +380,5 @@ void Texture::setPalette(int palette)
// Obtiene el renderizador
SDL_Renderer *Texture::getRenderer()
{
return renderer;
return renderer_;
}

View File

@@ -21,16 +21,16 @@ class Texture
{
private:
// Objetos y punteros
SDL_Texture *texture; // La textura
SDL_Renderer *renderer; // Renderizador donde dibujar la textura
Surface surface; // Surface para usar imagenes en formato gif con paleta
SDL_Texture *texture_; // La textura
SDL_Renderer *renderer_; // Renderizador donde dibujar la textura
Surface surface_; // 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
std::vector<std::vector<Uint32>> palettes; // Vector con las diferentes paletas
int paletteIndex; // Indice de la paleta en uso
int width_; // Ancho de la imagen
int height_; // Alto de la imagen
std::string path_; // Ruta de la imagen de la textura
std::vector<std::vector<Uint32>> palettes_; // Vector con las diferentes paletas
int paletteIndex_; // Indice de la paleta en uso
// Crea una nueva surface
Surface newSurface(int w, int h);

View File

@@ -58,16 +58,16 @@ void Tiledbg::init()
void Tiledbg::fillTexture()
{
// Crea los objetos para pintar en la textura de fondo
Texture *bgTileTexture = new Texture(renderer, texturePath);
Sprite *tile = new Sprite({0, 0, tileWidth, tileHeight}, bgTileTexture);
auto bgTileTexture = std::make_shared<Texture>(renderer, texturePath);
auto tile = std::make_unique<Sprite>((SDL_Rect){0, 0, tileWidth, tileHeight}, bgTileTexture);
// Prepara para dibujar sobre la textura
SDL_Texture *temp = SDL_GetRenderTarget(renderer);
auto temp = SDL_GetRenderTarget(renderer);
SDL_SetRenderTarget(renderer, canvas);
// Rellena la textura con el tile
const int iMax = pos.w * 2 / tileWidth;
const int jMax = pos.h * 2 / tileHeight;
const auto iMax = pos.w * 2 / tileWidth;
const auto jMax = pos.h * 2 / tileHeight;
tile->setSpriteClip(0, 0, tileWidth, tileHeight);
for (int i = 0; i < iMax; ++i)
{
@@ -84,8 +84,6 @@ void Tiledbg::fillTexture()
// Libera la memoria utilizada por los objetos
bgTileTexture->unload();
delete bgTileTexture;
delete tile;
}
// Pinta la clase en pantalla

View File

@@ -1,138 +1,131 @@
#include "writer.h"
#include "text.h" // for Text
// Constructor
Writer::Writer(Text *text)
: text(text)
Writer::Writer(std::shared_ptr<Text> text)
: text_(text)
{
// Inicializa variables
posX = 0;
posY = 0;
kerning = 0;
caption = "";
speed = 0;
writingCounter = 0;
index = 0;
lenght = 0;
completed = false;
enabled = false;
enabledCounter = 0;
finished = false;
posX_ = 0;
posY_ = 0;
kerning_ = 0;
caption_ = "";
speed_ = 0;
writingCounter_ = 0;
index_ = 0;
lenght_ = 0;
completed_ = false;
enabled_ = false;
enabledCounter_ = 0;
finished_ = false;
}
// Actualiza el objeto
void Writer::update()
{
if (enabled)
if (enabled_)
{
if (!completed)
if (!completed_)
{
// No completado
if (writingCounter > 0)
if (writingCounter_ > 0)
{
writingCounter--;
writingCounter_--;
}
else if (writingCounter == 0)
else if (writingCounter_ == 0)
{
index++;
writingCounter = speed;
index_++;
writingCounter_ = speed_;
}
if (index == lenght)
if (index_ == lenght_)
{
completed = true;
completed_ = true;
}
}
else
{
// Completado
if (enabledCounter > 0)
if (enabledCounter_ > 0)
{
enabledCounter--;
enabledCounter_--;
}
else if (enabledCounter == 0)
else if (enabledCounter_ == 0)
{
finished = true;
finished_ = true;
}
}
}
}
// Dibuja el objeto en pantalla
void Writer::render()
void Writer::render() const
{
if (enabled)
if (enabled_)
{
text->write(posX, posY, caption, kerning, index);
text_->write(posX_, posY_, caption_, kerning_, index_);
}
}
// Establece el valor de la variable
void Writer::setPosX(int value)
{
posX = value;
posX_ = value;
}
// Establece el valor de la variable
void Writer::setPosY(int value)
{
posY = value;
posY_ = value;
}
// Establece el valor de la variable
void Writer::setKerning(int value)
{
kerning = value;
kerning_ = value;
}
// Establece el valor de la variable
void Writer::setCaption(std::string text)
{
caption = text;
lenght = text.length();
caption_ = text;
lenght_ = text.length();
}
// Establece el valor de la variable
void Writer::setSpeed(int value)
{
speed = value;
writingCounter = value;
speed_ = value;
writingCounter_ = value;
}
// Establece el valor de la variable
void Writer::setEnabled(bool value)
{
enabled = value;
enabled_ = value;
}
// Obtiene el valor de la variable
bool Writer::IsEnabled() const
{
return enabled;
return enabled_;
}
// Establece el valor de la variable
void Writer::setEnabledCounter(int time)
void Writer::setFinishedCounter(int time)
{
enabledCounter = time;
}
// Obtiene el valor de la variable
int Writer::getEnabledCounter() const
{
return enabledCounter;
enabledCounter_ = time;
}
// Centra la cadena de texto a un punto X
void Writer::center(int x)
{
setPosX(x - (text->lenght(caption, kerning) / 2));
setPosX(x - (text_->lenght(caption_, kerning_) / 2));
}
// Obtiene el valor de la variable
bool Writer::hasFinished() const
{
return finished;
return finished_;
}

View File

@@ -1,32 +1,33 @@
#pragma once
#include <string> // for string, basic_string
class Text;
#include <memory>
#include "text.h"
// Clase Writer. Pinta texto en pantalla letra a letra a partir de una cadena y un bitmap
class Writer
{
private:
// Objetos y punteros
Text *text; // Objeto encargado de escribir el texto
std::shared_ptr<Text> text_; // Objeto encargado de escribir el texto
// Variables
int posX; // Posicion en el eje X donde empezar a escribir el texto
int posY; // 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 writingCounter; // 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 enabledCounter; // Temporizador para deshabilitar el objeto
bool finished; // Indica si ya ha terminado
int posX_; // Posicion en el eje X donde empezar a escribir el texto
int posY_; // 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 writingCounter_; // 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 enabledCounter_; // Temporizador para deshabilitar el objeto
bool finished_; // Indica si ya ha terminado
public:
// Constructor
Writer(Text *text);
Writer(std::shared_ptr<Text> text);
// Destructor
~Writer() = default;
@@ -35,7 +36,7 @@ public:
void update();
// Dibuja el objeto en pantalla
void render();
void render() const;
// Establece el valor de la variable
void setPosX(int value);
@@ -59,10 +60,7 @@ public:
bool IsEnabled() const;
// Establece el valor de la variable
void setEnabledCounter(int time);
// Obtiene el valor de la variable
int getEnabledCounter() const;
void setFinishedCounter(int time);
// Centra la cadena de texto a un punto X
void center(int x);